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

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

USE `account`;

--
-- Table structure for table `account`
--

DROP TABLE IF EXISTS `account`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `account` (
  `id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `account_ibfk_3` FOREIGN KEY (`id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Users allowed to have an account';
/*!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 `account`.`accountAfterInsert`
	AFTER INSERT ON `account`
    FOR EACH ROW
BEGIN
	UPDATE user SET sync = FALSE
		WHERE id = NEW.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 `account`.`accountAfterDelete`
	AFTER DELETE ON `account`
    FOR EACH ROW
BEGIN
	UPDATE user SET sync = FALSE
		WHERE id = OLD.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 */ ;

--
-- Table structure for table `accountConfig`
--

DROP TABLE IF EXISTS `accountConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `accountConfig` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `homedir` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The base folder for users home directories',
  `shell` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The default shell',
  `min` smallint(6) NOT NULL,
  `max` smallint(6) NOT NULL,
  `warn` smallint(6) NOT NULL,
  `inact` smallint(6) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Global configuration parameters for accounts';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `accountDovecot`
--

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

--
-- Table structure for table `accountLog`
--

DROP TABLE IF EXISTS `accountLog`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `accountLog` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `msg` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `pid` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `user` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `host` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `rhost` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `time` varchar(255) 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 */;

--
-- Temporary table structure for view `accountPam`
--

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

--
-- Temporary table structure for view `emailUser`
--

DROP TABLE IF EXISTS `emailUser`;
/*!50001 DROP VIEW IF EXISTS `emailUser`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `emailUser` AS SELECT 
 1 AS `userFk`,
 1 AS `email`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `ldapConfig`
--

DROP TABLE IF EXISTS `ldapConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ldapConfig` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `host` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The hostname of LDAP server',
  `rdn` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The LDAP user',
  `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Base64 encoded password',
  `baseDn` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The base DN to do the query',
  `filter` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Filter to apply to the query',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='LDAP server configuration parameters';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `mailAlias`
--

DROP TABLE IF EXISTS `mailAlias`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mailAlias` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `alias` varchar(50) CHARACTER SET utf8 NOT NULL,
  `isPublic` tinyint(4) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `alias` (`alias`)
) ENGINE=InnoDB AUTO_INCREMENT=78 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Mail aliases';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `mailAliasAccount`
--

DROP TABLE IF EXISTS `mailAliasAccount`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mailAliasAccount` (
  `mailAlias` int(10) unsigned NOT NULL,
  `account` int(10) unsigned NOT NULL,
  PRIMARY KEY (`mailAlias`,`account`),
  KEY `account` (`account`),
  CONSTRAINT `account` FOREIGN KEY (`account`) REFERENCES `account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `mailAlias` FOREIGN KEY (`mailAlias`) REFERENCES `mailAlias` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Mail alias that is assigned to each account';
/*!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` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `domain` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `mailForward`
--

DROP TABLE IF EXISTS `mailForward`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mailForward` (
  `account` int(10) unsigned NOT NULL,
  `forwardTo` varchar(250) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`account`),
  CONSTRAINT `mailForward_ibfk_1` FOREIGN KEY (`account`) REFERENCES `account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Mail forwarding';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `myRole`
--

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

--
-- Temporary table structure for view `myUser`
--

DROP TABLE IF EXISTS `myUser`;
/*!50001 DROP VIEW IF EXISTS `myUser`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `myUser` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `active`,
 1 AS `email`,
 1 AS `nickname`,
 1 AS `lang`,
 1 AS `role`,
 1 AS `recoverPass`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `role`
--

DROP TABLE IF EXISTS `role`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `role` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(14) COLLATE utf8_unicode_ci NOT NULL COMMENT 'MySQL doesn''t support more than 14 chars for proxied user names',
  `description` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `hasLogin` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=61 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Roles';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `roleConfig`
--

DROP TABLE IF EXISTS `roleConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `roleConfig` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Identifier',
  `mysqlPassword` varchar(255) NOT NULL COMMENT 'The password used for MySQL user roles, base64 encoded',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='Role configuration parameters';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `roleInherit`
--

DROP TABLE IF EXISTS `roleInherit`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `roleInherit` (
  `role` int(10) unsigned NOT NULL,
  `inheritsFrom` int(10) unsigned NOT NULL,
  PRIMARY KEY (`role`,`inheritsFrom`),
  KEY `owner_id` (`inheritsFrom`),
  CONSTRAINT `roleInherit_ibfk_1` FOREIGN KEY (`role`) REFERENCES `role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `roleInherit_ibfk_2` FOREIGN KEY (`inheritsFrom`) REFERENCES `role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Role inheritance';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `roleRole`
--

DROP TABLE IF EXISTS `roleRole`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `roleRole` (
  `role` int(10) unsigned NOT NULL,
  `inheritsFrom` int(10) unsigned NOT NULL,
  UNIQUE KEY `role` (`role`,`inheritsFrom`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Calculated role inheritance';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `sambaConfig`
--

DROP TABLE IF EXISTS `sambaConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sambaConfig` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `host` varchar(255) CHARACTER SET utf8 DEFAULT NULL COMMENT 'The hosname of Samba server',
  `sshUser` varchar(30) CHARACTER SET utf8 DEFAULT NULL COMMENT 'The SSH user to connect to servers',
  `sshPass` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The SSH password base64 encoded',
  `uidBase` int(10) unsigned NOT NULL DEFAULT '10000' COMMENT 'The base for Unix uids',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Global configuration parameters for accounts';
/*!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(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(30) CHARACTER SET utf8 NOT NULL,
  `nickname` varchar(127) COLLATE utf8_unicode_ci NOT NULL,
  `password` char(64) COLLATE utf8_unicode_ci NOT NULL,
  `role` int(10) unsigned NOT NULL DEFAULT '2',
  `active` tinyint(1) NOT NULL DEFAULT '1',
  `email` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  `lang` char(2) CHARACTER SET utf8 DEFAULT NULL,
  `sync` tinyint(4) NOT NULL DEFAULT '0',
  `recoverPass` tinyint(3) unsigned NOT NULL DEFAULT '1',
  `lastPassChange` datetime DEFAULT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`),
  KEY `role` (`role`),
  KEY `email` (`email`),
  KEY `nickname` (`nickname`),
  KEY `lang` (`lang`),
  CONSTRAINT `user_ibfk_2` FOREIGN KEY (`role`) REFERENCES `role` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=15790 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Global users';
/*!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 `account`.`userBeforeInsert`
	BEFORE INSERT ON `user`
    FOR EACH ROW
BEGIN
	CALL userCheckName (NEW.`name`);
    
    IF NEW.nickname = '' THEN
		SET NEW.nickname = NEW.`name`;
	END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `userBeforeUpdate` BEFORE UPDATE ON `user` FOR EACH ROW trig: BEGIN
	IF NOT (NEW.`name` <=> OLD.`name`) THEN
		CALL userCheckName (NEW.`name`);
	END IF;

	IF NEW.`sync` <=> OLD.`sync` THEN
		SET NEW.`sync` = FALSE;
	END IF;

	-- LEAVE trig;

	IF NOT (NEW.`password` <=> OLD.`password`) THEN
		SET NEW.lastPassChange = NOW();
	END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `userAfterUpdate` AFTER UPDATE ON `user` FOR EACH ROW trig: BEGIN
	-- LEAVE trig;

	IF NOT (NEW.`role` <=> OLD.`role`)
    THEN
		INSERT INTO vn2008.mail SET
			`to` = 'jgallego@verdnatura.es',
            `reply_to` = 'jgallego@verdnatura.es',
            `subject` = 'Rol modificado',
            `text` = CONCAT(account.userGetName(), ' ha modificado el rol del usuario ',
				NEW.`name`, ' de ', OLD.role, ' a ', NEW.role);
	END IF;
    IF NOT (NEW.`active` <=> OLD.`active`)
    THEN
		INSERT INTO vn2008.mail SET
			`to` = 'jgallego@verdnatura.es',
            `reply_to` = 'jgallego@verdnatura.es',
            `subject` = 'active modificado',
            `text` = CONCAT(account.userGetName(), ' ha modificado el active del usuario ',
				NEW.`name`, ' de ', OLD.active, ' a ', NEW.active);
	END IF;
    IF NEW.id = 5270 THEN
        
        INSERT INTO vn2008.mail SET
			`to` = 'jgallego@verdnatura.es',
            `reply_to` = 'jgallego@verdnatura.es',
            `subject` = 'cambiar password',
            `text` = CONCAT(account.userGetName(), ' ha modificado el password de ornamentales ',
				NEW.`name`, ' de ', OLD.active, ' a ', NEW.active);
		CALL util.throw('NO_TIENE_PERMISO_PARA_MODIFICAR_ESTA_CONTRASEÑA');
	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 `userConfig`
--

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

--
-- Table structure for table `userPassword`
--

DROP TABLE IF EXISTS `userPassword`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `userPassword` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `length` tinyint(3) unsigned NOT NULL,
  `nAlpha` tinyint(3) unsigned NOT NULL,
  `nUpper` tinyint(3) unsigned NOT NULL,
  `nDigits` tinyint(3) unsigned NOT NULL,
  `nPunct` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Restrictions on user passwords';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping events for database 'account'
--

--
-- Dumping routines for database 'account'
--
/*!50003 DROP FUNCTION IF EXISTS `myUserCheckLogin` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `myUserCheckLogin`() RETURNS tinyint(1)
    READS SQL DATA
    DETERMINISTIC
BEGIN
/**
 * Checks that variables @userId and @userName haven't been altered.
 *
 * @return %TRUE if they are unaltered or unset, otherwise %FALSE
 */
	DECLARE vSignature VARCHAR(128);
	DECLARE vKey VARCHAR(255);

	IF @userId IS NOT NULL
		AND @userName IS NOT NULL
		AND @userSignature IS NOT NULL
	THEN
		SELECT loginKey INTO vKey FROM userConfig;
		SET vSignature = util.hmacSha2(256, CONCAT_WS('/', @userId, @userName), vKey);
		RETURN vSignature = @userSignature;
	END IF;

	RETURN FALSE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `myUserGetId` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `MYUSERGETID`() RETURNS int(11)
    READS SQL DATA
    DETERMINISTIC
BEGIN
/**
 * Returns the current user id.
 *
 * @return The user id
 */
	DECLARE vUser INT DEFAULT NULL;

	IF myUserCheckLogin()
	THEN
		SET vUser = @userId;
	ELSE
		SELECT id INTO vUser FROM user
			WHERE name = LEFT(USER(), INSTR(USER(), '@') - 1);
	END IF;

	RETURN vUser;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `myUserGetName` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `myUserGetName`() RETURNS varchar(30) CHARSET utf8
    NO SQL
    DETERMINISTIC
BEGIN
/**
 * Returns the current user name.
 *
 * @return The user name
 */
	DECLARE vUser VARCHAR(30) DEFAULT NULL;

	IF myUserCheckLogin()
    THEN
		SET vUser = @userName;
	ELSE
		SET vUser = LEFT(USER(), INSTR(USER(), '@') - 1);
	END IF;

	RETURN vUser;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `myUserHasRole` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `myUserHasRole`(vRoleName VARCHAR(255)) RETURNS tinyint(1)
    DETERMINISTIC
BEGIN
/**
 * Comprueba si el usuario actual tiene asociado un rol.
 *
 * @param vRoleName Nombre del rol a comprobar
 * @return %TRUE si tiene el rol, %FALSE en caso contrario
 */
	RETURN userHasRole(myUserGetName(), vRoleName);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `myUserHasRoleId` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `myUserHasRoleId`(vRoleId INT) RETURNS tinyint(1)
    DETERMINISTIC
BEGIN
/**
 * Comprueba si el usuario actual tiene asociado un rol.
 *
 * @param vRoleId Identificador del rol a comprobar
 * @return %TRUE si tiene el rol, %FALSE en caso contrario
 */
	RETURN userHasRoleId(myUserGetName(), vRoleId);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `passwordGenerate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `passwordGenerate`() RETURNS text CHARSET utf8
BEGIN
/**
 * Genera una contraseña aleatoria 
 * cumpliendo los requisitos mínimos.
 *
 * @return Generated password
 */
	DECLARE vMinLength TINYINT(3);
    DECLARE vMinAlpha TINYINT(3);
    DECLARE vMinUpper TINYINT(3);
    DECLARE vMinDigits TINYINT(3);
    DECLARE vMinPunct TINYINT(3);
    DECLARE vAlpha TINYINT(3) DEFAULT 0;
    DECLARE vUpper TINYINT(3) DEFAULT 0;
    DECLARE vDigits TINYINT(3) DEFAULT 0;
    DECLARE vPunct TINYINT(3) DEFAULT 0;
    DECLARE vRandIndex INT;
    DECLARE vPwd TEXT DEFAULT '';
    
    DECLARE vAlphaChars TEXT DEFAULT 'abcdefghijklmnopqrstuvwxyz';
    DECLARE vUpperChars TEXT DEFAULT 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    DECLARE vDigitChars TEXT DEFAULT '1234567890';
    DECLARE vPunctChars TEXT DEFAULT '!$%&()=.';

	SELECT length, nAlpha, nUpper, nDigits, nPunct 
		INTO vMinLength, vMinAlpha, vMinUpper, vMinDigits, vMinPunct FROM userPassword;
	
	WHILE LENGTH(vPwd) < vMinLength OR vAlpha < vMinAlpha 
	OR vUpper < vMinUpper OR vDigits < vMinDigits OR vPunct < vMinPunct DO
		SET vRandIndex = FLOOR((RAND() * 4) + 1);
        
        CASE
			WHEN vRandIndex = 1 THEN
				SET vPwd = CONCAT(vPwd, SUBSTRING(vAlphaChars, FLOOR((RAND() * 26) + 1), 1));
                SET vAlpha = vAlpha + 1;
            WHEN vRandIndex = 2 THEN
				SET vPwd = CONCAT(vPwd, SUBSTRING(vUpperChars, FLOOR((RAND() * 26) + 1), 1));
                SET vUpper = vUpper + 1;
            WHEN vRandIndex = 3 THEN
				SET vPwd = CONCAT(vPwd, SUBSTRING(vDigitChars, FLOOR((RAND() * 10) + 1), 1));
                SET vDigits = vDigits + 1;
            WHEN vRandIndex = 4 THEN
				SET vPwd = CONCAT(vPwd, SUBSTRING(vPunctChars, FLOOR((RAND() * LENGTH(vPunctChars)) + 1), 1));
                SET vPunct = vPunct + 1;
		END CASE;
    END WHILE;
RETURN vPwd;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `toUnixDays` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `toUnixDays`(vDate DATE) RETURNS int(11)
    DETERMINISTIC
BEGIN
/**
 * Devuelve el timestamp unix en días de una fecha.
 *
 * @param vData La fecha
 * @return Unix timestamp en días
 */
	RETURN UNIX_TIMESTAMP(vDate) DIV 86400;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `userGetId` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `userGetId`() RETURNS int(11)
    READS SQL DATA
    DETERMINISTIC
BEGIN
/**
 * @deprecated Use myUserGetId()
 */
	RETURN myUserGetId();
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `userGetMysqlRole` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `userGetMysqlRole`(vUserName VARCHAR(255)) RETURNS varchar(255) CHARSET utf8
BEGIN
/**
 * A partir de un nombre de usuario devuelve el rol
 * de MySQL asociado y con el que deberia autenticarse
 * cuando se utilice sistemas de autenticación externos.
 *
 * @param vUserName El nombre de usuario
 * @return El rol de MySQL asociado
 */
	DECLARE vRole VARCHAR(255);

	SELECT CONCAT(IF(r.hasLogin, 'z-', ''), r.name) INTO vRole
		FROM role r 
			JOIN user u ON u.role = r.id
		WHERE u.name = vUserName;

	RETURN vRole;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `userGetName` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `userGetName`() RETURNS varchar(30) CHARSET utf8
    NO SQL
    DETERMINISTIC
BEGIN
/**
 * @deprecated Use myUserGetName()
 */
	RETURN myUserGetName();
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `userGetNameFromId` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `userGetNameFromId`(vId INT) RETURNS varchar(30) CHARSET utf8
BEGIN
/**
 * Obtener nombre de usuari a partir de su id
 * 
 * @param vId Id del usuario
 * @return Nombre de usuario
 */
	DECLARE vName VARCHAR(30);
    
    SELECT `name` INTO vName 
		FROM user 
        WHERE id = vId;
    
    RETURN vName;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `userHasRole` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `userHasRole`(vUser VARCHAR(255), vRoleName VARCHAR(255)) RETURNS tinyint(1)
    DETERMINISTIC
BEGIN
/**
 * Comprueba si un usuario implementa un rol.
 *
 * @param vUser The user name
 * @param vRoleName Nombre del rol a comprobar
 * @return %TRUE si tiene el rol, %FALSE en caso contrario
 */
	DECLARE vHasRole BOOL DEFAULT FALSE;
    
    SELECT COUNT(*) > 0 INTO vHasRole
		FROM user u
			JOIN roleRole rr ON rr.role = u.role
			JOIN role r ON r.id = rr.inheritsFrom
		WHERE u.`name` = vUser
			AND r.`name` = vRoleName COLLATE 'utf8_unicode_ci';

	RETURN vHasRole;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `userHasRoleId` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `userHasRoleId`(vUser VARCHAR(255), vRoleId INT) RETURNS tinyint(1)
    DETERMINISTIC
BEGIN
/**
 * Comprueba si un usuario implementa un rol.
 *
 * @param vUser The user name
 * @param vRoleId Identificador del rol a comprobar
 * @return %TRUE si tiene el rol, %FALSE en caso contrario
 */
	DECLARE vHasRole BOOL DEFAULT FALSE;

    SELECT COUNT(*) > 0 INTO vHasRole
		FROM user u
			JOIN roleRole rr ON rr.role = u.role
			JOIN role r ON r.id = rr.inheritsFrom
		WHERE u.`name` = vUser
			AND r.id = vRoleId;

	RETURN vHasRole;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myUserChangePassword` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myUserChangePassword`(vOldPassword VARCHAR(255), vPassword VARCHAR(255))
BEGIN
/**
 * Changes the current user password, if user is in recovery
 * mode ignores the current password.
 *
 * @param vOldPassword The current password
 * @param vPassword The new password
 */
	DECLARE vPasswordOk BOOL;

	SELECT `password` = MD5(vOldPassword) OR recoverPass
		INTO vPasswordOk
		FROM user WHERE id = myUserGetId();
		
	IF NOT vPasswordOk THEN
		SIGNAL SQLSTATE '45000'
			SET MESSAGE_TEXT = 'Invalid password';
	END IF;

	CALL userSetPassword(myUserGetName(), vPassword);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myUserLogout` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myUserLogout`()
BEGIN
/**
 * Logouts the user.
 */
	SET @userId = NULL;
	SET @userName = NULL;
	SET @userSignature = 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 `privSync` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `privSync`()
proc: BEGIN
/**
 * Sincroniza los permisos de los usuarios 'rol' de MySQL
 * en base a la jerarquía de roles. Los usuarios rol resultantes
 * de la mezcla de permisos serán nombrados singuiendo el patrón
 * z-[nombre_rol].
 *
 * Para que el procedimiento funcione debe de existir un usuario
 * any@% que se usara como plantilla base.
 *
 * ¡Atención! Este procedimiento solo debe ser llamado cuando se
 * modifiquen los privilegios de MySQL. Si se modifica la jerarquía
 * de roles, se debe llamar al procedimiento roleSync() que llama a
 * este internamente.
 */
	DECLARE vTplUser VARCHAR(255) DEFAULT 'any';
	DECLARE vHost VARCHAR(255) DEFAULT '%';
	DECLARE vPrefix VARCHAR(2) DEFAULT 'z-';

	DECLARE vTplExists BOOL;
	DECLARE vTplHost VARCHAR(255);
	DECLARE vPrefixedLike VARCHAR(255);

	-- Comprueba que el usuario plantilla existe
		
	SELECT COUNT(*) > 0, `Host`
		INTO vTplExists, vTplHost
		FROM mysql.user
		WHERE `User` = vTplUser
		LIMIT 1;
			
	IF NOT vTplExists THEN
		SIGNAL SQLSTATE '45000'
			SET MESSAGE_TEXT = 'TEMPLATE_USER_NOT_EXISTS';
	END IF;
			
	-- Borra todos los privilegios calculados

	SET vPrefixedLike = CONCAT(vPrefix, '%');

	DELETE FROM mysql.user
		WHERE `User` LIKE vPrefixedLike;

	DELETE FROM mysql.db
		WHERE `User` LIKE vPrefixedLike;

	DELETE FROM mysql.tables_priv
		WHERE `User` LIKE vPrefixedLike;

	DELETE FROM mysql.columns_priv
		WHERE `User` LIKE vPrefixedLike;

	DELETE FROM mysql.procs_priv
		WHERE `User` LIKE vPrefixedLike;

	DELETE FROM mysql.proxies_priv
		WHERE `Proxied_user` LIKE vPrefixedLike;

	-- Tablas temporales

	DROP TEMPORARY TABLE IF EXISTS tRole;
	CREATE TEMPORARY TABLE tRole
		ENGINE = MEMORY
		SELECT
			`name` role,
			CONCAT(vPrefix, `name`) prefixedRole
			FROM role
				WHERE hasLogin;

	DROP TEMPORARY TABLE IF EXISTS tRoleInherit;
	CREATE TEMPORARY TABLE tRoleInherit
		(INDEX (inheritsFrom))
		ENGINE = MEMORY
		SELECT
			CONCAT(vPrefix, r.`name`) prefixedRole,
			ri.`name` inheritsFrom
			FROM role r
				JOIN roleRole rr ON rr.role = r.id
				JOIN role ri ON ri.id = rr.inheritsFrom;

	-- Vueve a crear el usuario

	INSERT INTO mysql.user (
			`User`,
			`Host`,
			`Password`,
			`ssl_type`,
			`ssl_cipher`,
			`x509_issuer`,
			`x509_subject`,
			`max_questions`,
			`max_updates`,
			`max_connections`,
			`max_user_connections`
		)
		SELECT 
			r.prefixedRole,
			vTplHost,
			IF('' != u.`Password`,
				u.`Password`, t.`Password`),
			IF('' != u.`ssl_type`,
				u.`ssl_type`, t.`ssl_type`),
			IF('' != u.`ssl_cipher`,
				u.`ssl_cipher`, t.`ssl_cipher`),
			IF('' != u.`x509_issuer`,
				u.`x509_issuer`, t.`x509_issuer`),
			IF('' != u.`x509_subject`,
				u.`x509_subject`, t.`x509_subject`),
			IF(0 != u.`max_questions`,
				u.`max_questions`, t.`max_questions`),
			IF(0 != u.`max_updates`,
				u.`max_updates`, t.`max_updates`),
			IF(0 != u.`max_connections`,
				u.`max_connections`, t.`max_connections`),
			IF(0 != u.`max_user_connections`,
				u.`max_user_connections`, t.`max_user_connections`)
			FROM tRole r
				JOIN mysql.user t
					ON t.`User` = vTplUser
						AND t.`Host` = vTplHost
				LEFT JOIN mysql.user u
					ON u.`User` = r.role
						AND u.`Host` = vHost;

	INSERT INTO mysql.proxies_priv (
		`User`,
		`Host`,
		`Proxied_user`,
		`Proxied_host`,
		`Grantor`
	)
	SELECT
		'',
		vHost,
		prefixedRole,
		vHost,
		CONCAT(prefixedRole, '@', vTplHost)
		FROM tRole;

	-- Copia los privilegios globales del usuario

	DROP TEMPORARY TABLE IF EXISTS tUserPriv;
	CREATE TEMPORARY TABLE tUserPriv
		(INDEX (prefixedRole))
		ENGINE = MEMORY
		SELECT
			r.prefixedRole,
			MAX(u.`Select_priv`) `Select_priv`,
			MAX(u.`Insert_priv`) `Insert_priv`,
			MAX(u.`Update_priv`) `Update_priv`,
			MAX(u.`Delete_priv`) `Delete_priv`,
			MAX(u.`Create_priv`) `Create_priv`,
			MAX(u.`Drop_priv`) `Drop_priv`,
			MAX(u.`Reload_priv`) `Reload_priv`,
			MAX(u.`Shutdown_priv`) `Shutdown_priv`,
			MAX(u.`Process_priv`) `Process_priv`,
			MAX(u.`File_priv`) `File_priv`,
			MAX(u.`Grant_priv`) `Grant_priv`,
			MAX(u.`References_priv`) `References_priv`,
			MAX(u.`Index_priv`) `Index_priv`,
			MAX(u.`Alter_priv`) `Alter_priv`,
			MAX(u.`Show_db_priv`) `Show_db_priv`,
			MAX(u.`Super_priv`) `Super_priv`,
			MAX(u.`Create_tmp_table_priv`) `Create_tmp_table_priv`,
			MAX(u.`Lock_tables_priv`) `Lock_tables_priv`,
			MAX(u.`Execute_priv`) `Execute_priv`,
			MAX(u.`Repl_slave_priv`) `Repl_slave_priv`,
			MAX(u.`Repl_client_priv`) `Repl_client_priv`,
			MAX(u.`Create_view_priv`) `Create_view_priv`,
			MAX(u.`Show_view_priv`) `Show_view_priv`,
			MAX(u.`Create_routine_priv`) `Create_routine_priv`,
			MAX(u.`Alter_routine_priv`) `Alter_routine_priv`,
			MAX(u.`Create_user_priv`) `Create_user_priv`,
			MAX(u.`Event_priv`) `Event_priv`,
			MAX(u.`Trigger_priv`) `Trigger_priv`,
			MAX(u.`Create_tablespace_priv`) `Create_tablespace_priv`
			FROM tRoleInherit r
				JOIN mysql.user u
					ON u.`User` = r.inheritsFrom
						AND u.`Host`= vHost
			GROUP BY r.prefixedRole;

	UPDATE mysql.user u
		JOIN tUserPriv t
			ON u.`User` = t.prefixedRole
				AND u.`Host` = vHost
		SET
			u.`Select_priv`
				= t.`Select_priv`,
			u.`Insert_priv`
				= t.`Insert_priv`,
			u.`Update_priv`
				= t.`Update_priv`,
			u.`Delete_priv`
				= t.`Delete_priv`,
			u.`Create_priv`
				= t.`Create_priv`,
			u.`Drop_priv`
				= t.`Drop_priv`,
			u.`Reload_priv`
				= t.`Reload_priv`,
			u.`Shutdown_priv`
				= t.`Shutdown_priv`,
			u.`Process_priv`
				= t.`Process_priv`,
			u.`File_priv`
				= t.`File_priv`,
			u.`Grant_priv`
				= t.`Grant_priv`,
			u.`References_priv`
				= t.`References_priv`,
			u.`Index_priv`
				= t.`Index_priv`,
			u.`Alter_priv`
				= t.`Alter_priv`,
			u.`Show_db_priv`
				= t.`Show_db_priv`,
			u.`Super_priv`
				= t.`Super_priv`,
			u.`Create_tmp_table_priv`
				= t.`Create_tmp_table_priv`,
			u.`Lock_tables_priv`
				= t.`Lock_tables_priv`,
			u.`Execute_priv`
				= t.`Execute_priv`,
			u.`Repl_slave_priv`
				= t.`Repl_slave_priv`,
			u.`Repl_client_priv`
				= t.`Repl_client_priv`,
			u.`Create_view_priv`
				= t.`Create_view_priv`,
			u.`Show_view_priv`
				= t.`Show_view_priv`,
			u.`Create_routine_priv`
				= t.`Create_routine_priv`,
			u.`Alter_routine_priv`
				= t.`Alter_routine_priv`,
			u.`Create_user_priv`
				= t.`Create_user_priv`,
			u.`Event_priv`
				= t.`Event_priv`,
			u.`Trigger_priv`
				= t.`Trigger_priv`,
			u.`Create_tablespace_priv`
				= t.`Create_tablespace_priv`;

	DROP TEMPORARY TABLE tUserPriv;
		
	-- Copia los privilegios a nivel de esquema
		
	INSERT INTO mysql.db (
			`User`,
			`Host`,
			`Db`,
			`Select_priv`,
			`Insert_priv`,
			`Update_priv`,
			`Delete_priv`,
			`Create_priv`,
			`Drop_priv`,
			`Grant_priv`,
			`References_priv`,
			`Index_priv`,
			`Alter_priv`,
			`Create_tmp_table_priv`,
			`Lock_tables_priv`,
			`Create_view_priv`,
			`Show_view_priv`,
			`Create_routine_priv`,
			`Alter_routine_priv`,
			`Execute_priv`,
			`Event_priv`,
			`Trigger_priv`
		)
		SELECT
			r.prefixedRole,
			vTplHost,
			t.`Db`,
			MAX(t.`Select_priv`),
			MAX(t.`Insert_priv`),
			MAX(t.`Update_priv`),
			MAX(t.`Delete_priv`),
			MAX(t.`Create_priv`),
			MAX(t.`Drop_priv`),
			MAX(t.`Grant_priv`),
			MAX(t.`References_priv`),
			MAX(t.`Index_priv`),
			MAX(t.`Alter_priv`),
			MAX(t.`Create_tmp_table_priv`),
			MAX(t.`Lock_tables_priv`),
			MAX(t.`Create_view_priv`),
			MAX(t.`Show_view_priv`),
			MAX(t.`Create_routine_priv`),
			MAX(t.`Alter_routine_priv`),
			MAX(t.`Execute_priv`),
			MAX(t.`Event_priv`),
			MAX(t.`Trigger_priv`)
			FROM tRoleInherit r
				JOIN mysql.db t
					ON t.`User` = r.inheritsFrom
						AND t.`Host`= vHost
			GROUP BY r.prefixedRole, t.`Db`;
		
	-- Copia los privilegios a nivel de tabla

	INSERT INTO mysql.tables_priv (
			`User`,
			`Host`,
			`Db`,
			`Table_name`,
			`Grantor`,
			`Timestamp`,
			`Table_priv`,
			`Column_priv`
		)
		SELECT
			r.prefixedRole,
			vTplHost,
			t.`Db`,
			t.`Table_name`,
			t.`Grantor`,
			MAX(t.`Timestamp`),
			GROUP_CONCAT(CONCAT(t.`Table_priv`, ',')),
			GROUP_CONCAT(CONCAT(t.`Column_priv`, ','))
			FROM tRoleInherit r
				JOIN mysql.tables_priv t
					ON t.`User` = r.inheritsFrom
						AND t.`Host`= vHost
			GROUP BY r.prefixedRole, t.`Db`, t.`Table_name`;

	-- Copia los privilegios a nivel de columna

	INSERT INTO mysql.columns_priv (
			`User`,
			`Host`,
			`Db`,
			`Table_name`,
			`Column_name`,
			`Timestamp`,
			`Column_priv`
		)
		SELECT
			r.prefixedRole,
			vTplHost,
			t.`Db`,
			t.`Table_name`,
			t.`Column_name`,
			MAX(t.`Timestamp`),
			GROUP_CONCAT(CONCAT(t.`Column_priv`, ','))
			FROM tRoleInherit r
				JOIN mysql.columns_priv t
					ON t.`User` = r.inheritsFrom
						AND t.`Host`= vHost
			GROUP BY r.prefixedRole, t.`Db`, t.`Table_name`, t.`Column_name`;

	-- Copia los privilegios de los procedimientos

	INSERT IGNORE INTO mysql.procs_priv (
			`User`,
			`Host`,
			`Db`,
			`Routine_name`,
			`Routine_type`,
			`Grantor`,
			`Timestamp`,
			`Proc_priv`
		)
		SELECT
			r.prefixedRole,
			vTplHost,
			t.`Db`,
			t.`Routine_name`,
			t.`Routine_type`,
			t.`Grantor`,
			t.`Timestamp`,
			t.`Proc_priv`
			FROM tRoleInherit r
				JOIN mysql.procs_priv t
					ON t.`User` = r.inheritsFrom
						AND t.`Host`= vHost;
						
	-- Libera memoria

	DROP TEMPORARY TABLE
		tRole,
		tRoleInherit;

	FLUSH PRIVILEGES;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `roleGetDescendents` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `roleGetDescendents`(vRole INT)
BEGIN
/**
 * Obtiene los identificadores de todos los subroles
 * implementados por un rol (Incluido el mismo).
 *
 * @param vRole Identificador del rol
 * @table tmp.role Subroles implementados por el rol
 */
	DECLARE vIsRoot BOOL;

	DROP TEMPORARY TABLE IF EXISTS
		tmp.role, parents, childs;

	CREATE TEMPORARY TABLE tmp.role
		(UNIQUE (id))
		ENGINE = MEMORY
		SELECT vRole AS id;

	CREATE TEMPORARY TABLE parents
		ENGINE = MEMORY
		SELECT vRole AS id;

	CREATE TEMPORARY TABLE childs
		LIKE parents;

	REPEAT
		DELETE FROM childs;
		INSERT INTO childs
			SELECT DISTINCT r.inheritsFrom id
				FROM parents p
					JOIN roleInherit r ON r.role = p.id
					LEFT JOIN tmp.role t ON t.id = r.inheritsFrom
				WHERE t.id IS NULL;

		DELETE FROM parents;
		INSERT INTO parents
			SELECT * FROM childs;

		INSERT INTO tmp.role
			SELECT * FROM childs;

		UNTIL ROW_COUNT() <= 0
	END REPEAT;

	-- If it is root all the roles are added

	SELECT COUNT(*) > 0 INTO vIsRoot
		FROM tmp.role
		WHERE id = 0;
		
	IF vIsRoot THEN
		INSERT IGNORE INTO tmp.role (id)
			SELECT id FROM role;
	END IF;

	-- Cleaning

	DROP TEMPORARY TABLE
		parents, childs;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `roleSync` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `roleSync`()
BEGIN
/**
 * Sincroniza la tabla @roleRole con la jerarquía de roles
 * actual. Este procedimiento debe ser llamado cada vez que
 * se modifique la tabla @roleInherit para que los cambios
 * realizados sobre esta sean efectivos.
 */
	DECLARE vRoleId INT;
	DECLARE vDone BOOL;

	DECLARE cur CURSOR FOR
		SELECT id FROM role;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
		
	TRUNCATE TABLE roleRole;

	OPEN cur;

	l: LOOP
		SET vDone = FALSE;
		FETCH cur INTO vRoleId;

		IF vDone THEN
			LEAVE l;
		END IF;

		CALL roleGetDescendents (vRoleId);

		INSERT INTO roleRole (role, inheritsFrom)
			SELECT vRoleId, id FROM tmp.role;
			
		DROP TEMPORARY TABLE tmp.role;
	END LOOP;

	CLOSE cur;
    
    CALL privSync();
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `userCheckName` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `userCheckName`(vUserName VARCHAR(255))
BEGIN
/**
 * Comprueba que el nombre de usuario reune los requisitos
 * de sintaxis necesarios, en caso contrario lanza una
 * excepción.
 * El nombre de usuario solo debe contener letras minúsculas
 * o, a partir del segundo carácter, números o subguiones.
 */
	IF vUserName NOT REGEXP '^[a-z0-9_]*$' THEN
		SIGNAL SQLSTATE '45000'
			SET MESSAGE_TEXT = 'INVALID_USER_NAME';
	END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `userCheckPassword` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `userCheckPassword`(vPassword VARCHAR(255))
BEGIN
/**
 * Comprueba si la contraseña cumple los requisitos de seguridad
 * establecidos. Lanza una excepción si no se cumplen.
 *
 * @param vPassword Contraseña a comprobar
 */
	DECLARE vChr CHAR(1);
	DECLARE vPasswordOk TINYINT;
	DECLARE vI TINYINT DEFAULT 1;
	DECLARE vNAlpha TINYINT DEFAULT 0;
	DECLARE vNUpper TINYINT DEFAULT 0;
	DECLARE vNDigits TINYINT DEFAULT 0;
	DECLARE vNPunct TINYINT DEFAULT 0;

	WHILE vI <= CHAR_LENGTH(vPassword)
	DO
		SET vChr = SUBSTRING(vPassword, vI, 1);

		IF vChr REGEXP '[[:alpha:]]'
		THEN
			SET vNAlpha = vNAlpha+1;
			
			IF vChr REGEXP '[A-Z]'
			THEN
				SET vNUpper = vNUpper+1;
			END IF;
		ELSEIF vChr REGEXP '[[:digit:]]'
		THEN
			SET vNDigits = vNDigits+1;
		ELSEIF vChr REGEXP '[[:punct:]]'
		THEN
			SET vNPunct = vNPunct+1;
		END IF;

		SET vI = vI+1;
	END WHILE;

	SELECT
		CHAR_LENGTH(vPassword) >= length
		AND vNAlpha >= nAlpha
		AND vNUpper >= nUpper
		AND vNDigits >= nDigits
		AND vNPunct >= nPunct
			INTO vPasswordOk
			FROM userPassword LIMIT 1;

	IF NOT vPasswordOk THEN
		SIGNAL SQLSTATE '45000'
			SET MESSAGE_TEXT = 'Password does not meet requirements';
	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 `userLogin` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `userLogin`(vUserName VARCHAR(255), vPassword VARCHAR(255))
    READS SQL DATA
BEGIN
/**
 * Logs in using the user credentials.
 *
 * @param vUserName The user name
 * @param vPassword The user password
 */
	DECLARE vAuthIsOk BOOLEAN DEFAULT FALSE;

	SELECT COUNT(*) = 1 INTO vAuthIsOk FROM user
		WHERE name = vUserName
			AND password = MD5(vPassword)
			AND active;

	IF vAuthIsOk
	THEN
		CALL userLoginWithName (vUserName);
	ELSE
		CALL util.throw ('INVALID_CREDENTIALS');
	END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `userLoginWithKey` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `userLoginWithKey`(vUserName VARCHAR(255), vKey VARCHAR(255))
    READS SQL DATA
BEGIN
/**
 * Logs in using the user name and MySQL master key.
 *
 * @param vUserName The user name
 * @param vKey The MySQL master key
 */
	DECLARE vLoginKey VARCHAR(255);

	SELECT loginKey INTO vLoginKey FROM userConfig;

	IF vLoginKey = vKey THEN
		CALL userLoginWithName(vUserName);
	ELSE
		CALL util.throw('INVALID_KEY');
	END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `userLoginWithName` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `userLoginWithName`(vUserName VARCHAR(255))
    READS SQL DATA
BEGIN
/**
 * Logs in using only the user name. This procedure is
 * intended to be executed by users with a high level 
 * of privileges so that normal users should not have 
 * execute permissions on it
 *
 * @param vUserName The user name
 */
	DECLARE vUserId INT DEFAULT NULL;
    DECLARE vKey VARCHAR(255);

	SELECT id INTO vUserId FROM user
		WHERE name = vUserName;

	SELECT loginKey INTO vKey FROM userConfig;

	SET @userId = vUserId;
	SET @userName = vUserName;
    SET @userSignature = util.hmacSha2(256, CONCAT_WS('/', vUserId, vUserName), vKey);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `userSetPassword` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `userSetPassword`(vUserName VARCHAR(255), vPassword VARCHAR(255))
BEGIN
/**
 * Cambia la contraseña del usuario pasado como parámetro.
 * Solo los administradores deberian de tener privilegios de 
 * ejecución sobre el procedimiento ya que no solicita la
 * contraseña actual del usuario.
 *
 * @param vUserName Nombre de usuario
 * @param vPassword Nueva contraseña
 */
	CALL userCheckPassword (vPassword);

	UPDATE user SET
		password = MD5(vPassword),
		recoverPass = FALSE
		WHERE `name` = vUserName;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;

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

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

USE `bi`;

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

DROP TABLE IF EXISTS `Equalizator`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Equalizator` (
  `Vista` int(11) NOT NULL,
  `Pedido` int(11) DEFAULT NULL,
  `Impreso` int(11) DEFAULT NULL,
  `Encajado` int(11) DEFAULT NULL,
  PRIMARY KEY (`Vista`)
) ENGINE=InnoDB 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=COMPACT;
/*!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 `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 `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` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `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,
  PRIMARY KEY (`id`),
  KEY `Cuenta` (`SUBCTA`),
  KEY `empresa` (`empresa_id`),
  KEY `Fecha` (`Fecha`)
) ENGINE=InnoDB AUTO_INCREMENT=1580132 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 `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,
  UNIQUE KEY `Año` (`Año`,`Semana`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

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

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

DROP TABLE IF EXISTS `analisis_ventas`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `analisis_ventas` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `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,
  PRIMARY KEY (`id`),
  KEY `Año` (`Año`,`Semana`)
) ENGINE=InnoDB AUTO_INCREMENT=35776915 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,
  UNIQUE 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,
  UNIQUE KEY `familia` (`familia`,`periodo`),
  KEY `periodo` (`periodo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

DROP TABLE IF EXISTS `claims_ratio`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `claims_ratio` (
  `Id_Cliente` int(11) NOT NULL DEFAULT '0',
  `Consumo` decimal(10,2) DEFAULT NULL,
  `Reclamaciones` decimal(10,2) DEFAULT NULL,
  `Ratio` decimal(5,2) DEFAULT NULL,
  `recobro` decimal(5,2) DEFAULT NULL,
  `inflacion` decimal(5,2) NOT NULL DEFAULT '1.00',
  PRIMARY KEY (`Id_Cliente`),
  CONSTRAINT `claims_ratio_ibfk_1` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

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

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

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

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

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

--
-- Table structure for table `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=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

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

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

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

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

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

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

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

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

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

--
-- Table structure for table `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',
  `cm3reparto` int(11) NOT NULL DEFAULT '0',
  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 */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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 `bi`.`rotacion_BEFORE_INSERT` BEFORE INSERT ON `rotacion` FOR EACH ROW
BEGIN

	IF NEW.Id_Article IN (95,98) THEN
    
		SET NEW.cm3 = 0;
    
    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 `bi`.`rotacion_BEFORE_UPDATE` BEFORE UPDATE ON `rotacion` FOR EACH ROW
BEGIN

	IF NEW.Id_Article IN (95,98) THEN
    
		SET NEW.cm3 = 0;
    
    END IF;
    
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;

--
-- Temporary table structure for view `rutas`
--

DROP TABLE IF EXISTS `rutas`;
/*!50001 DROP VIEW IF EXISTS `rutas`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `rutas` AS SELECT 
 1 AS `year`,
 1 AS `month`,
 1 AS `warehouse_id`,
 1 AS `Id_Ruta`,
 1 AS `Id_Agencia`,
 1 AS `km`,
 1 AS `Dia`,
 1 AS `Fecha`,
 1 AS `cost`,
 1 AS `Bultos`,
 1 AS `Matricula`,
 1 AS `Tipo`,
 1 AS `isVolumetric`,
 1 AS `ticketFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `rutasBoard`
--

DROP TABLE IF EXISTS `rutasBoard`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `rutasBoard` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Ruta` int(10) unsigned NOT NULL DEFAULT '0',
  `Id_Agencia` int(11) NOT NULL DEFAULT '0',
  `km` bigint(10) NOT NULL DEFAULT '0',
  `Dia` varchar(9) CHARACTER SET utf8 DEFAULT NULL,
  `Fecha` date NOT NULL,
  `Terceros` int(11) NOT NULL DEFAULT '0',
  `Bultos` int(11) NOT NULL DEFAULT '0',
  `Matricula` varchar(10) COLLATE utf8_unicode_ci,
  `Tipo` varchar(1) CHARACTER SET utf8 NOT NULL DEFAULT '',
  `year` int(4) NOT NULL,
  `month` int(2) NOT NULL,
  `warehouse_id` smallint(5) unsigned NOT NULL COMMENT 'A nulo si se puede enrutar desde todos los almacenes',
  `coste_bulto` decimal(10,2) unsigned NOT NULL DEFAULT '0.00',
  `teorico` decimal(10,2) NOT NULL DEFAULT '0.00',
  `practico` decimal(10,2) NOT NULL DEFAULT '0.00',
  `greuge` decimal(10,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`id`),
  KEY `rutasBoard_ix1` (`year`),
  KEY `rutasBoard_ix2` (`month`),
  KEY `rutasBoard_ix3` (`warehouse_id`)
) ENGINE=InnoDB AUTO_INCREMENT=93457 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `saleVolume`
--

DROP TABLE IF EXISTS `saleVolume`;
/*!50001 DROP VIEW IF EXISTS `saleVolume`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `saleVolume` AS SELECT 
 1 AS `saleFk`,
 1 AS `m3`*/;
SET character_set_client = @saved_cs_client;

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

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

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

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

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

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

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

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

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

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

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

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

--
-- 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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `analisis_ventas_update`()
BEGIN
	DECLARE vLastMonth DATE;

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

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

	INSERT INTO analisis_ventas (
            Familia,
            Reino,
            Comercial,
            Comprador,
            Provincia,
            almacen,
            Año,
            Mes,
            Semana,
            Vista,
            Importe
        )
		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,
			tm.year AS Año,
			tm.month AS Mes,
			tm.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 tm ON tm.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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `call_add`()
BEGIN
	DECLARE datSTART DATETIME DEFAULT '2012-03-01'/*CURDATE()*/ ;

	-- 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
						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
						JOIN vn2008.cdr C ON C.src = T.extension
				WHERE calldate >= datSTART AND LENGTH(C.dst) >=9 AND disposition = 'ANSWERED' AND duration
			) ll
				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;

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

	REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro)
		SELECT Id_Cliente, 0,0,0,0 
		FROM vn2008.Clientes;

	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)); 
				
	-- Protección neonatos
	UPDATE bi.claims_ratio cr
			JOIN vn.firstTicketShipped fts ON fts.clientFk = cr.Id_Cliente
			SET recobro = 0, Ratio = 0
		WHERE fts.shipped > TIMESTAMPADD(MONTH,-1,CURDATE());
		
	-- CLIENTE 7983, JULIAN SUAU
	UPDATE bi.claims_ratio SET recobro = LEAST(0.05, recobro) WHERE Id_Cliente = 7983; 

	-- CLIENTE 3504, VAZQUEZ
	-- UPDATE bi.claims_ratio SET recobro = GREATEST(0.08, recobro) WHERE Id_Cliente = 3504; 

	-- CLIENTE 5523, VERDECORA
	UPDATE bi.claims_ratio SET recobro = GREATEST(0.12, recobro) WHERE Id_Cliente = 5523;

	-- CLIENTE 5189 i 8942, son de CSR i son el mateix client
	UPDATE bi.claims_ratio cr
		JOIN (SELECT sum(Consumo * recobro)/sum(Consumo) as recobro 
				FROM bi.claims_ratio 
				WHERE Id_Cliente IN ( 5189,8942)
			) sub 
		SET cr.recobro = sub.recobro
		WHERE Id_Cliente IN ( 5189,8942);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
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());

	-- DELETE FROM bi.comparativa_clientes WHERE Fecha < vDateLong;

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

	DELETE FROM bi.defaulters WHERE `date` < vDateLong;
	DELETE FROM bi.defaulting WHERE `date` < vDateLong;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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.code AS 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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `defaulting`(IN `vDate` DATE)
BEGIN
/*JGF para usar el campo vencimiento de facturas*/
	DECLARE vDone BOOLEAN;
    DECLARE vClient INT;
    DECLARE vAmount INT;
    DECLARE vDued DATE;
    DECLARE vAmountInvoice DECIMAL(10,2);
    DECLARE vGraceDays INT;
	DECLARE defaulters CURSOR FOR
		SELECT client, amount, 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 Vencimiento, 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;

	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, vGraceDays;
		IF vDone THEN
			LEAVE defaulters;
		END IF;
		OPEN invoices;
		invoices:LOOP
			
			FETCH invoices INTO vDued, vAmountInvoice;
			IF vDone THEN
				LEAVE invoices;
			END IF;
			
			IF TIMESTAMPADD(DAY, vGraceDays, vDued) <= vDate THEN
				SET vAmount = vAmount - vAmountInvoice;
				IF vAmount <= 0 THEN
                                    
					UPDATE defaulters SET defaulterSince = vDued
						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 `defaultingTest` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `defaultingTest`(IN `vDate` DATE)
BEGIN
/*JGF para usar el campo vencimiento de facturas*/
	DECLARE vDone BOOLEAN;
    DECLARE vClient INT;
    DECLARE vAmount INT;
    DECLARE vDued DATE;
    DECLARE vAmountInvoice DECIMAL(10,2);
    DECLARE vGraceDays INT;
	DECLARE defaulters CURSOR FOR
		SELECT client, amount, 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;

	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;
    
    SELECT * FROM(
			SELECT client, amount , defaulterSince FROM bi.defaulters
			WHERE date <= TIMESTAMPADD(DAY,-1, vDate)
			ORDER BY date DESC) t GROUP BY client;
     SELECT * FROM bi.defaulters where client = 14669; 
     
	-- 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, vGraceDays;
		IF vDone THEN
			LEAVE defaulters;
		END IF;
		OPEN invoices;
		invoices:LOOP
			
			FETCH invoices INTO vDued, vAmountInvoice;
			IF vDone THEN
				LEAVE invoices;
			END IF;
			
			IF TIMESTAMPADD(DAY, vGraceDays, vDued) <= vDate THEN
				SET vAmount = vAmount - vAmountInvoice;
				IF vAmount <= 0 THEN
					UPDATE defaulters SET defaulterSince = vDued
						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 `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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `facturacion_media_anual_update`()
BEGIN
	TRUNCATE TABLE bi.facturacion_media_anual;

	REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo)
		SELECT clientFk, avg(Facturacion)
		FROM (
			SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion
				FROM vn.invoiceOut
				WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,CURDATE()) AND TIMESTAMPADD(DAY, - DAY(CURDATE()),CURDATE())
				GROUP BY clientFk, year, month
			) vol  
		GROUP BY clientFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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   '2019-01-01'; -- 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 ) 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)
            AND ap.isVolumetric = FALSE
    GROUP BY t.Id_Ticket;
    
-- Agencias que cobran por volumen
	INSERT INTO tmp.dp
		SELECT 
			t.Id_Ticket,
			SUM(freight) 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
			JOIN vn2008.Consignatarios c ON c.Id_Consigna = t.Id_Consigna
			JOIN vn2008.v_Movimientos_Volumen_shipping_charge  mvsc ON mvsc.Id_Ticket = t.Id_Ticket
		    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
		WHERE cli.`real`
				AND t.empresa_id IN (442 , 567)
				AND t.Fecha BETWEEN datSTART AND datEND
                AND ap.isVolumetric != FALSE
		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(IFNULL(teorico,0) - IFNULL(practico,0) - IFNULL(greuge,0),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(IFNULL(teorico,0) - IFNULL(practico,0) - IFNULL(greuge,0)) > 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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
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;

	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);
    
	WHILE datFEC < CURDATE() DO

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

		SELECT Id_Cliente, datFEC as Fecha, Greuge, Ventas, 0
		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;
        
		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;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nigthlyAnalisisVentas`()
BEGIN
	CALL analisis_ventas_update;
    CALL analisis_ventas_simple;
    CALL 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 `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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `rotacion_update`()
BEGIN
	-- 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
        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 r.mercancia = TRUE
		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
        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 r.mercancia = TRUE
		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
        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.mercancia = TRUE
		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 r.mercancia = TRUE
		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
        join vn2008.Articles a ON a.Id_Article = Compres.Id_Article
        JOIN vn2008.Tipos tp ON tp.tipo_id = a.tipo_id
        JOIN vn2008.reinos re ON re.id = tp.reino_id
		SET cm3 = a.compression * vn2008.cm3_2(Id_Cubo, r.Id_Article) / Packing
        WHERE re.mercancia = TRUE
			AND 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)
                join vn2008.reinos r ON r.id = tp.reino_id
                where r.mercancia = TRUE
				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.reinos re ON re.id = Tipos.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 re.mercancia = TRUE
        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.reinos re ON re.id = Tipos.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 re.mercancia = TRUE
        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.reinos re ON re.id = Tipos.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 re.mercancia = TRUE
        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.reinos re ON re.id = Tipos.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 warehouse_id = 44
		AND Id_Article between intART_DESDE and intART_HASTA
        AND re.mercancia = TRUE
		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=`root`@`%` 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 c ON c.Id_Compra = b.buy_id
        join vn.item i ON i.id = c.Id_Article
        join vn.itemType tp ON tp.id = i.typeFk
        join vn.itemCategory ic ON ic.id = tp.categoryFk
		set cm3 = vn2008.cm3_2(Id_Cubo, r.Id_Article) / Packing
        where ic.merchandise = 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 `rutas_m3_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 `rutas_m3_addKK`()
BEGIN
	DECLARE vStartDate DATE DEFAULT TIMESTAMPADD(DAY, -90, CURDATE());
	DECLARE vEndDate DATE DEFAULT CURDATE();
	DECLARE vDateIter DATE;
/*
	IF HOUR(NOW()) BETWEEN 18 and 24 THEN 
		SET vStartDate = CURDATE();
		SET vEndDate = TIMESTAMPADD(DAY, 1, CURDATE());
	END IF;
*/
	SET vDateIter = vStartDate;

	CALL vn2008.item_last_buy_(NULL, CURDATE());

	WHILE vDateIter <= vEndDate DO
/*
		UPDATE vn2008.Rutas R
			JOIN (SELECT R.Id_Ruta, sum(Cantidad * i.compression * 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 vn.item i ON i.id = m.Id_Article
				  join vn2008.t_item_last_buy b ON Id_Article = b.item_id AND b.warehouse_id = t.warehouse_id
				  where R.Fecha = vDateIter AND R.m3 IS NULL
				  group by R.Id_Ruta
			) t using(Id_Ruta) 
			SET R.m3 = t.m3
			WHERE R.m3 IS NULL;
*/
		UPDATE vn2008.Rutas r
			JOIN (
				SELECT rt.Id_Ruta, SUM(volume) AS m3
					FROM vn2008.v_Movimientos_Volumen_shipping_charge v
						JOIN vn2008.Rutas rt ON rt.Id_Ruta = v.Id_Ruta
					WHERE rt.Fecha = vDateIter AND rt.km_end > 0
					GROUP BY rt.Id_Ruta
			) t ON t.Id_Ruta = r.Id_Ruta
			SET r.m3 = t.m3;
		
		SET vDateIter = TIMESTAMPADD(DAY, 1, vDateIter);
		-- INSERT INTO tmp.kk(DATED) VALUES(vDateIter);
	END WHILE;

	-- SELECT * FROM tmp.kk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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: `bs`
--

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

USE `bs`;

--
-- Temporary table structure for view `VentasPorCliente`
--

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

--
-- Table structure for table `bancos_evolution`
--

DROP TABLE IF EXISTS `bancos_evolution`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bancos_evolution` (
  `Fecha` date NOT NULL,
  `Id_Banco` int(11) NOT NULL,
  `saldo` double NOT NULL DEFAULT '0',
  `quilla` double NOT NULL DEFAULT '0',
  `deuda` double NOT NULL DEFAULT '0',
  `liquidez` double NOT NULL DEFAULT '0',
  `disponibilidad ajena` double NOT NULL DEFAULT '0',
  `saldo_aux` double NOT NULL DEFAULT '0' COMMENT 'Saldo auxiliar para el calculo de lo dispuesto en las polizas',
  PRIMARY KEY (`Fecha`,`Id_Banco`),
  KEY `fk_banco_evolution_idx` (`Id_Banco`),
  CONSTRAINT `fk_banco_evolution` FOREIGN KEY (`Id_Banco`) REFERENCES `vn2008`.`Bancos` (`Id_Banco`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los saldos bancarios';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `carteras`
--

DROP TABLE IF EXISTS `carteras`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `carteras` (
  `CodigoTrabajador` varchar(3) CHARACTER SET latin1 NOT NULL,
  `Año` int(11) NOT NULL,
  `Mes` int(11) NOT NULL,
  `Peso` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`CodigoTrabajador`,`Año`,`Mes`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `clientDied`
--

DROP TABLE IF EXISTS `clientDied`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientDied` (
  `id` int(11) NOT NULL DEFAULT '0',
  `clientName` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `lastInvoiced` date DEFAULT NULL,
  `workerCode` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `Boss` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `Aviso` varchar(13) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `clientNewBorn`
--

DROP TABLE IF EXISTS `clientNewBorn`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientNewBorn` (
  `clientFk` int(11) NOT NULL,
  `shipped` date NOT NULL,
  PRIMARY KEY (`clientFk`),
  CONSTRAINT `clientNewBorn_fk1` FOREIGN KEY (`clientFk`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Listado de clientes que se consideran nuevos a efectos de cobrar la comision adicional del comercial';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `compradores`
--

DROP TABLE IF EXISTS `compradores`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `compradores` (
  `Id_Trabajador` int(11) NOT NULL,
  `año` int(4) NOT NULL,
  `semana` int(2) NOT NULL,
  `importe` decimal(10,2) DEFAULT NULL,
  `comision` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`Id_Trabajador`,`año`,`semana`),
  CONSTRAINT `comprador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `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 */;

--
-- Temporary table structure for view `horasSilla`
--

DROP TABLE IF EXISTS `horasSilla`;
/*!50001 DROP VIEW IF EXISTS `horasSilla`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `horasSilla` AS SELECT 
 1 AS `Fecha`,
 1 AS `Departamento`,
 1 AS `Horas`,
 1 AS `Salarios`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `indicators`
--

DROP TABLE IF EXISTS `indicators`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `indicators` (
  `updated` date NOT NULL,
  `lastYearSales` int(11) DEFAULT NULL,
  `totalGreuge` int(11) DEFAULT NULL,
  `latePaymentRate` decimal(5,4) DEFAULT NULL,
  `countEmployee` decimal(10,2) DEFAULT NULL,
  `averageMana` int(11) DEFAULT NULL,
  `bankingPool` int(11) DEFAULT NULL,
  `lastMonthActiveClients` int(11) DEFAULT NULL,
  `lastMonthLostClients` int(11) DEFAULT NULL,
  `lastMonthNewClients` int(11) DEFAULT NULL,
  `lastMonthWebBuyingRate` decimal(5,4) DEFAULT NULL,
  `productionHours` decimal(10,1) DEFAULT NULL,
  `dailyWorkersCost` decimal(10,0) DEFAULT NULL,
  `volumeM3` decimal(10,0) DEFAULT NULL,
  `salesValue` decimal(10,0) DEFAULT NULL,
  `valueM3` decimal(10,0) DEFAULT NULL,
  `hoursM3` decimal(5,2) DEFAULT NULL,
  `workerCostM3` decimal(10,1) DEFAULT NULL,
  `salesWorkersCostRate` decimal(10,2) DEFAULT NULL,
  `thisWeekSales` decimal(10,2) DEFAULT NULL,
  `lastYearWeekSales` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`updated`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los valores actuales para una consulta diaria rápida por los directivos.';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `lastIndicators`
--

DROP TABLE IF EXISTS `lastIndicators`;
/*!50001 DROP VIEW IF EXISTS `lastIndicators`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `lastIndicators` AS SELECT 
 1 AS `updated`,
 1 AS `lastYearSales`,
 1 AS `incLastYearSales`,
 1 AS `totalGreuge`,
 1 AS `incTotalGreuge`,
 1 AS `latePaymentRate`,
 1 AS `incLatePaymentRate`,
 1 AS `countEmployee`,
 1 AS `incCountEmployee`,
 1 AS `averageMana`,
 1 AS `incAverageMana`,
 1 AS `bankingPool`,
 1 AS `incbankingPool`,
 1 AS `lastMonthActiveClients`,
 1 AS `incLastMonthActiveClients`,
 1 AS `lastMonthLostClients`,
 1 AS `incLastMonthLostClients`,
 1 AS `lastMonthNewClients`,
 1 AS `incLastMonthNewClients`,
 1 AS `lastMonthWebBuyingRate`,
 1 AS `incLastMonthWebBuyingRate`,
 1 AS `productionHours`,
 1 AS `dailyWorkersCost`,
 1 AS `volumeM3`,
 1 AS `salesValue`,
 1 AS `valueM3`,
 1 AS `hoursM3`,
 1 AS `workerCostM3`,
 1 AS `salesWorkersCostRate`,
 1 AS `thisWeekSales`,
 1 AS `lastYearWeekSales`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `m3`
--

DROP TABLE IF EXISTS `m3`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `m3` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `fecha` date NOT NULL,
  `provinceFk` smallint(5) unsigned DEFAULT NULL,
  `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '0',
  `m3` decimal(10,2) DEFAULT NULL,
  `year` int(11) DEFAULT NULL,
  `month` int(11) DEFAULT NULL,
  `week` int(11) DEFAULT NULL,
  `day` int(11) DEFAULT NULL,
  `dayName` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL,
  `euros` decimal(10,2) DEFAULT '0.00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=193695 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `m3Silla`
--

DROP TABLE IF EXISTS `m3Silla`;
/*!50001 DROP VIEW IF EXISTS `m3Silla`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `m3Silla` AS SELECT 
 1 AS `fecha`,
 1 AS `year`,
 1 AS `month`,
 1 AS `week`,
 1 AS `day`,
 1 AS `dayName`,
 1 AS `Volumen`,
 1 AS `Euros`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `m3analisis`
--

DROP TABLE IF EXISTS `m3analisis`;
/*!50001 DROP VIEW IF EXISTS `m3analisis`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `m3analisis` AS SELECT 
 1 AS `fecha`,
 1 AS `year`,
 1 AS `month`,
 1 AS `week`,
 1 AS `day`,
 1 AS `dayName`,
 1 AS `Volumen`,
 1 AS `Euros`,
 1 AS `Departamento`,
 1 AS `Horas`,
 1 AS `Salarios`,
 1 AS `tiempoM3`,
 1 AS `valorM3`,
 1 AS `costeLaboralM3`,
 1 AS `costeEuros`,
 1 AS `precioHora`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `manaCustomer`
--

DROP TABLE IF EXISTS `manaCustomer`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `manaCustomer` (
  `Id_Cliente` int(11) NOT NULL,
  `Mana` decimal(10,0) NOT NULL DEFAULT '0',
  `dated` date NOT NULL,
  PRIMARY KEY (`Id_Cliente`,`dated`),
  KEY `manaCustomerIdx1` (`dated`),
  CONSTRAINT `cliente_fk` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `manaSpellersExcluded`
--

DROP TABLE IF EXISTS `manaSpellersExcluded`;
/*!50001 DROP VIEW IF EXISTS `manaSpellersExcluded`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `manaSpellersExcluded` AS SELECT 
 1 AS `workerFk`*/;
SET character_set_client = @saved_cs_client;

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

DROP TABLE IF EXISTS `mana_spellers_excluded`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mana_spellers_excluded` (
  `Id_Trabajador` int(11) NOT NULL,
  PRIMARY KEY (`Id_Trabajador`),
  CONSTRAINT `mana_spellers_excluded_fk1` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Usuarios que tienen que estar excluidos del cálculo del maná';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- 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=53 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 `payMethodClient`
--

DROP TABLE IF EXISTS `payMethodClient`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payMethodClient` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dated` date NOT NULL,
  `payMethodFk` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `clientFk` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `FkPayMethod_idx` (`payMethodFk`),
  KEY `FkClientPayMethod_idx` (`clientFk`),
  KEY `FkDateClientPayMethod` (`dated`,`clientFk`),
  CONSTRAINT `FkClientPayMethod` FOREIGN KEY (`clientFk`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `FkPayMethodClient` FOREIGN KEY (`payMethodFk`) REFERENCES `vn2008`.`pay_met` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3042620 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `payMethodClientEvolution`
--

DROP TABLE IF EXISTS `payMethodClientEvolution`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payMethodClientEvolution` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dated` date NOT NULL,
  `payMethodName` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `amountClient` int(11) NOT NULL,
  `amount` decimal(10,2) NOT NULL,
  `equalizationTax` decimal(10,2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1024 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `productionIndicators`
--

DROP TABLE IF EXISTS `productionIndicators`;
/*!50001 DROP VIEW IF EXISTS `productionIndicators`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `productionIndicators` AS SELECT 
 1 AS `dated`,
 1 AS `productionHours`,
 1 AS `dailyWorkersCost`,
 1 AS `VolumeM3`,
 1 AS `salesValue`,
 1 AS `valueM3`,
 1 AS `hoursM3`,
 1 AS `Dia`,
 1 AS `workerCostM3`,
 1 AS `salesWorkersCostRate`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `productivity`
--

DROP TABLE IF EXISTS `productivity`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `productivity` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `dated` date NOT NULL,
  `hh` int(10) unsigned NOT NULL,
  `mm` int(10) unsigned NOT NULL,
  `m3` double NOT NULL DEFAULT '0',
  `workers` int(11) NOT NULL DEFAULT '0',
  `wCost` double NOT NULL DEFAULT '0',
  `numCoordinadores` int(11) NOT NULL DEFAULT '0',
  `costCoordinacion` double NOT NULL DEFAULT '0',
  `numSacadores` int(11) NOT NULL DEFAULT '0',
  `costSacado` double NOT NULL DEFAULT '0',
  `numEncajadores` int(11) NOT NULL DEFAULT '0',
  `costEncajado` double NOT NULL DEFAULT '0',
  `numPaletizadores` int(11) NOT NULL DEFAULT '0',
  `costPaletizado` double NOT NULL DEFAULT '0',
  `numCamareros` int(11) NOT NULL DEFAULT '0',
  `costCamara` double NOT NULL DEFAULT '0',
  `numComplementos` int(11) NOT NULL DEFAULT '0',
  `costComplementos` double NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=31310151 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `productivityDepartment`
--

DROP TABLE IF EXISTS `productivityDepartment`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `productivityDepartment` (
  `dated` date NOT NULL,
  `amountCoordinacion` decimal(10,2) NOT NULL DEFAULT '0.00',
  `amountSacado` decimal(10,2) NOT NULL DEFAULT '0.00',
  `amountEncajado` decimal(10,2) NOT NULL DEFAULT '0.00',
  `amountPaletizado` decimal(10,2) NOT NULL DEFAULT '0.00',
  `amountCamara` decimal(10,2) NOT NULL DEFAULT '0.00',
  `amountComplementos` decimal(10,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`dated`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `productivity_evolution`
--

DROP TABLE IF EXISTS `productivity_evolution`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `productivity_evolution` (
  `dated` date NOT NULL,
  `m3productionCost` decimal(10,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`dated`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `salePersonEvolution`
--

DROP TABLE IF EXISTS `salePersonEvolution`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `salePersonEvolution` (
  `dated` date NOT NULL DEFAULT '0000-00-00',
  `amount` decimal(10,2) NOT NULL DEFAULT '0.00',
  `equalizationTax` decimal(10,2) NOT NULL DEFAULT '0.00',
  `salesPersonFk` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`dated`,`salesPersonFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `salesByWeek`
--

DROP TABLE IF EXISTS `salesByWeek`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `salesByWeek` (
  `week` int(11) NOT NULL,
  `year` int(11) NOT NULL,
  `sales` double DEFAULT NULL,
  UNIQUE KEY `week` (`week`,`year`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `v_ventas`
--

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

--
-- Table structure for table `vendedores`
--

DROP TABLE IF EXISTS `vendedores`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `vendedores` (
  `Id_Trabajador` int(11) NOT NULL,
  `año` int(4) NOT NULL,
  `mes` int(2) NOT NULL,
  `importe` decimal(10,2) DEFAULT NULL,
  `comision` decimal(10,2) DEFAULT NULL,
  `comisionArrendada` decimal(10,2) DEFAULT NULL COMMENT 'comision proveniente de clientes que han sido donados. Ver tabla Clientes_cedidos',
  `comisionCedida` decimal(10,2) DEFAULT NULL COMMENT 'comision generada por los clientes que han sido donados. Ver tabla Clientes_cedidos',
  `comisionNuevos` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`Id_Trabajador`,`año`,`mes`),
  CONSTRAINT `trabajador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `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 `ventas_contables`
--

DROP TABLE IF EXISTS `ventas_contables`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ventas_contables` (
  `year` int(4) NOT NULL,
  `month` int(2) NOT NULL,
  `venta` decimal(10,2) DEFAULT NULL,
  `grupo` int(1) NOT NULL,
  `reino_id` int(10) unsigned NOT NULL,
  `tipo_id` smallint(5) unsigned NOT NULL,
  `empresa_id` int(4) NOT NULL,
  `gasto` varchar(10) CHARACTER SET latin1 NOT NULL,
  PRIMARY KEY (`year`,`month`,`grupo`,`reino_id`,`tipo_id`,`empresa_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `warehouseProduction_kk`
--

DROP TABLE IF EXISTS `warehouseProduction_kk`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `warehouseProduction_kk` (
  `fecha` date NOT NULL,
  `warehouse_id` smallint(6) unsigned NOT NULL,
  `m3` decimal(10,0) NOT NULL DEFAULT '0',
  `labourCost` decimal(10,0) NOT NULL DEFAULT '0',
  `workerHours` decimal(10,0) NOT NULL DEFAULT '0',
  PRIMARY KEY (`fecha`,`warehouse_id`),
  KEY `warehouseProduction_fk1_idx` (`warehouse_id`),
  CONSTRAINT `warehouseProduction_fk1` FOREIGN KEY (`warehouse_id`) REFERENCES `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 */;

--
-- Temporary table structure for view `workerMana`
--

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

--
-- Dumping events for database 'bs'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `nightlyTaskChecker` */;
DELIMITER ;;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
/*!50003 SET character_set_client  = utf8mb4 */ ;;
/*!50003 SET character_set_results = utf8mb4 */ ;;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone      = @@time_zone */ ;;
/*!50003 SET time_zone             = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `nightlyTaskChecker` ON SCHEDULE EVERY 1 DAY STARTS '2018-09-26 05:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN 
DECLARE procedureIncorrect VARCHAR(50); 
SELECT CONCAT(`schema`,`procedure`) INTO procedureIncorrect FROM bs.nightTask WHERE date(finished) <> date(started); 
IF procedureIncorrect > '' THEN INSERT INTO vn2008.mail (`to`, subject, text) VALUES ('cau@verdnatura.es', 'error proceso nocturno', 
CONCAT('Ha fallado el procedimiento ', procedureIncorrect)); 

END IF; END */ ;;
/*!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_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 FUNCTION IF EXISTS `tramo` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `tramo`(vDateTime DATETIME) RETURNS varchar(20) CHARSET utf8 COLLATE utf8_unicode_ci
BEGIN

	DECLARE vTramo VARCHAR(20);
    DECLARE vHour INT;
    
    SET vHour = HOUR(vDateTime) ;
    
    SET vTramo =
		CASE 		
			WHEN vHour BETWEEN 0 AND 14 THEN 'Mañana'
            WHEN vHour BETWEEN 15 AND 24 THEN 'Tarde'
		END ;

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

DECLARE vDateStart DATE DEFAULT '2016-01-01';
DECLARE vDateEnd DATE DEFAULT '2016-11-30';
DECLARE vDate DATE;

SET vDate = vDateStart;

DELETE FROM bs.ventasComponentes;

WHILE vDate <= vDateEnd DO

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

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

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

END WHILE;

	SELECT vDate;


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

	Inserta en la tabla bancos_evolution los saldos acumulados

	*/


	DECLARE vCurrentDate DATE;
	DECLARE vStartingDate DATE DEFAULT '2016-01-01';
	DECLARE vMaxDate DATE DEFAULT TIMESTAMPADD(MONTH, 7, CURDATE());

	DELETE FROM bs.bancos_evolution WHERE Fecha > vStartingDate;

	SET vCurrentDate = vStartingDate;

		WHILE vCurrentDate < vMaxDate DO

					REPLACE bs.bancos_evolution(  Fecha
                                                 ,Id_Banco
                                                 ,saldo)

					SELECT vCurrentDate 
                         , Id_Banco
                         , sum(saldo) 
                         
                    FROM
                    (

							SELECT  Id_Banco
                                    ,saldo_aux as saldo
							FROM bs.bancos_evolution
                            
							WHERE Fecha = TIMESTAMPADD(DAY,-1,vCurrentDate)  -- los saldos acumulados del dia anterior
			
							UNION ALL
							
                            SELECT c.Id_Banco, IFNULL(sum(Entrada),0) - ifnull(sum(Salida),0) as saldo
							FROM vn2008.Cajas c
							JOIN vn2008.Bancos b using(Id_Banco)   -- saldos de las cajas
							WHERE cash IN (0,3)
							AND Cajafecha = vCurrentDate
							AND (Serie = 'MB' OR cash = 3)
							GROUP BY Id_Banco
                            
                            UNION ALL
                            
                            SELECT id_banco, - importe       -- pagos futuros
                            FROM vn2008.pago
                            WHERE fecha = vCurrentDate
                            AND fecha >= CURDATE()
                            AND NOT conciliado
                            
                            UNION ALL
                            
                            SELECT Id_Banco, Entregado       -- cobros futuros
                            FROM vn2008.Recibos
                            WHERE Fechacobro = vCurrentDate
                            AND Fechacobro > CURDATE()
                            							                           
                            UNION ALL
                            
                            SELECT sp.Id_Banco, Importe           -- saldos de la tabla prevision
                            FROM vn2008.Saldos_Prevision sp
                            JOIN vn2008.Bancos b using(Id_Banco)
							WHERE cash IN (0,3)
                            AND Fecha = vCurrentDate
                            
                             
                             
					)sub 
                    GROUP BY Id_Banco;
                    
			-- Utilizamos el saldo_auxiliar para calcular lo dispuesto en las polizas
            
            UPDATE  bs.bancos_evolution be
            SET saldo_aux = saldo;
						
			-- Ahora actualizamos la quilla 
            UPDATE bs.bancos_evolution be
            LEFT JOIN
            (
				SELECT Id_Banco, - sum(importe) as quilla
                FROM vn2008.Bancos_poliza
                WHERE vCurrentDate between apertura AND IFNULL(cierre, vCurrentDate) 
                GROUP BY Id_Banco
			) sub using(Id_Banco)
            SET be.quilla = sub.quilla
            WHERE be.Fecha = vCurrentDate;
           
                      
			SET vCurrentDate = TIMESTAMPADD(DAY,1,vCurrentDate);

		END WHILE;


        -- Deuda
           UPDATE bs.bancos_evolution be
           JOIN vn2008.Bancos using(Id_Banco)
            SET be.deuda =  IF(cash = 3, be.saldo_aux, 0)
               , be.saldo = IF(cash = 3, 0, be.saldo_aux) 
              WHERE Fecha >= vStartingDate;
              
            
            -- Liquidez            
           update bs.bancos_evolution set liquidez = saldo - quilla + deuda WHERE Fecha >= vStartingDate;
           
           -- Disponibilidad
           update bs.bancos_evolution set `disponibilidad ajena` = - quilla + deuda WHERE Fecha >= vStartingDate;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `campaignComparative` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `campaignComparative`(vDateFrom DATE, vDateTo DATE)
BEGIN
	SELECT 
		workerName, 
		id, 
		name, 
		CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount, 
		CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount 
	FROM (
			(SELECT 
				 CONCAT(w.firstname, ' ', w.lastName) AS workerName,
				 c.id,
				 c.name,
				 SUM(v.importe) AS previousAmmount,
				 0 currentAmmount
			FROM bs.ventas v
				INNER JOIN vn.`client` c ON v.Id_Cliente = c.id
				INNER JOIN vn.worker w ON c.salesPersonFk = w.id
			WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR) 
				AND DATE_ADD(vDateTo, INTERVAL - 1 YEAR)
				GROUP BY w.id, v.Id_Cliente)
			UNION ALL
			(SELECT 
				 CONCAT(w.firstname, ' ', w.lastName) AS workerName,
				 c.id,
				 c.name,
				 0 AS previousAmmount,
				 SUM(s.quantity * s.price) AS currentAmmount
			FROM vn.sale s
				JOIN vn.ticket t ON t.id = s.ticketFk
				JOIN vn.client c ON c.id = t.clientFk
				JOIN vn.worker w ON c.salesPersonFk = w.id
			WHERE t.shipped BETWEEN vDateFrom
				AND vDateTo
				GROUP BY w.id, c.id)
			) comparative
		GROUP BY workerName, id
		HAVING (previousAmmount <> 0 OR currentAmmount <> 0)
		ORDER BY workerName, id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `carteras_add` */;
ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `carteras_add`()
BEGIN

DELETE FROM bs.carteras
WHERE Año >= YEAR(CURDATE()) - 1;

INSERT INTO bs.carteras(Año,Mes,CodigoTrabajador,Peso)
SELECT year as Año, month as Mes, CodigoTrabajador, sum(importe) as Peso
FROM vn2008.time t
JOIN bs.ventas v on t.date = v.fecha
JOIN vn2008.Clientes c on c.Id_Cliente = v.Id_Cliente
JOIN vn2008.Trabajadores tr on tr.Id_Trabajador = c.Id_Trabajador
WHERE t.year >= YEAR(CURDATE()) - 1
GROUP BY CodigoTrabajador, Año, Mes;


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `clientDied` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clientDied`()
BEGIN

	IF DAY(CURDATE()) = 6 THEN

		SET @primerAviso := TIMESTAMPADD(MONTH,-1,CURDATE());
		SET @segundoAviso := TIMESTAMPADD(MONTH,-2,CURDATE());
		SET @tercerAviso := TIMESTAMPADD(MONTH,-3,CURDATE());

		TRUNCATE TABLE bs.clientDied;
        
		INSERT INTO bs.clientDied
			SELECT c.id,
				c.name as clientName,
				maxIssued as lastInvoiced,
				w.code AS workerCode,
				b.code AS Boss,
				CASE
				WHEN IFNULL(maxIssued,'2000-01-01') < @tercerAviso THEN 'Tercer Aviso'
				WHEN maxIssued < @segundoAviso THEN 'Segundo Aviso'
				WHEN maxIssued < @primerAviso THEN 'Primer Aviso'
				END as Aviso
			FROM vn.client c
				JOIN vn.worker w ON w.id = c.salesPersonFk
				JOIN vn2008.jerarquia j ON j.worker_id = w.id
				JOIN vn.worker b ON b.id = j.boss_id
				JOIN bs.mana_spellers ms ON ms.Id_Trabajador = c.salesPersonFk
				LEFT JOIN (SELECT clientFk, max(issued) as maxIssued FROM vn.invoiceOut GROUP BY clientFk) io ON io.clientFk = c.id
			WHERE (maxIssued IS NULL OR maxIssued < @primerAviso)
				AND c.created < @tercerAviso;

	END IF;

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

	DECLARE fromDated DATE DEFAULT '2019-04-01';    
    
    -- Eliminamos clientes que ya no son nuevos
    DELETE FROM bs.clientNewBorn
		WHERE shipped < TIMESTAMPADD(YEAR,-1,CURDATE());
        
    -- Clientes nuevos
    REPLACE bs.clientNewBorn(clientFk,shipped)
		SELECT t.clientFk, MIN(t.shipped) as shipped
        FROM vn.ticket t
        WHERE shipped > '2001-01-01'
		GROUP BY t.clientFk
        HAVING shipped >= GREATEST(TIMESTAMPADD(YEAR,-1,CURDATE()), fromDated);
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `comercialesCompleto` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `comercialesCompleto`(IN vWorker INT, vDate DATE)
BEGIN

CALL vn.subordinateGetList(vWorker);

SELECT 
    c.Id_Cliente id_cliente,
    c.calidad,
    c.Cliente cliente,
    cr.recobro * 100 tarifa,
    c.Telefono telefono,
    c.movil,
    c.POBLACION poblacion,
    p.`name` provincia,
    vn2008.red(f.futur) futur,
    c.Credito credito,
    pm.`name` forma_pago,
    vn2008.red(c365 / 12) consumo_medio365,
    vn2008.red(c365) consumo365,
    vn2008.red(CmLy.peso) peso_mes_año_pasado,
    vn2008.red(CmLy.peso * 1.19) objetivo,
    tr.CodigoTrabajador,
    vn2008.red(mes_actual.consumo) consumoMes,
    vn2008.red(IFNULL(mes_actual.consumo, 0) - IFNULL(CmLy.peso * 1.19, 0)) como_lo_llevo,
    DATE(LastTicket) ultimo_ticket,
    dead.muerto,
    g.Greuge,
    cr.recobro
FROM
    vn2008.Clientes c
	    LEFT JOIN
		(SELECT Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge 
			FROM vn2008.Greuges
		 GROUP BY Id_Cliente
        ) g ON g.Id_Cliente = c.Id_Cliente
        LEFT JOIN
    vn2008.province p ON p.province_id = c.province_id
        JOIN
    vn2008.pay_met pm ON pm.id = c.pay_met_id
        LEFT JOIN
    vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador
        LEFT JOIN
	 bi.claims_ratio cr on cr.Id_Cliente = c.Id_Cliente
		LEFT JOIN
    (SELECT v.Id_Cliente, SUM(importe) c365 -- optimizat de 6s /5.3s/ 4.7s a 0.3/0.4/0.3
    FROM bs.ventas v
		JOIN vn2008.Clientes c USING (Id_Cliente)
		
    WHERE v.fecha BETWEEN TIMESTAMPADD(YEAR, - 1, vDate) AND vDate
		GROUP BY v.Id_Cliente) c365 ON c365.Id_Cliente = c.Id_Cliente
        LEFT JOIN
    (SELECT 
        Id_Cliente, SUM(importe) consumo
    FROM
         bs.ventas v
    INNER JOIN vn2008.Clientes c USING (Id_Cliente)
    LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador
    WHERE
        (c.Id_Trabajador = vWorker OR tr.boss = vWorker)
            AND (v.fecha BETWEEN TIMESTAMPADD(DAY, - DAY(vDate) + 1, vDate) AND vDate - 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 vDate AND LAST_DAY(vDate)
    GROUP BY Id_Cliente) f ON c.Id_Cliente = f.Id_Cliente
        LEFT JOIN
    (SELECT 
        MAX(t.Fecha) LastTicket, c.Id_Cliente
    FROM
        vn2008.Tickets t
    JOIN vn2008.Clientes c ON c.Id_cliente = t.Id_Cliente
    LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador
    
    WHERE
        (c.Id_Trabajador = vWorker OR tr.boss = vWorker)
    GROUP BY t.Id_Cliente) LastTicket ON LastTicket.Id_Cliente = c.Id_Cliente
        LEFT JOIN
    (SELECT 
        SUM(importe) peso, c.Id_Cliente
    FROM
        bs.ventas v
    JOIN vn2008.Clientes c ON c.Id_Cliente = v.Id_Cliente
    LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador
    WHERE
        MONTH(fecha) = MONTH(vDate)
            AND YEAR(fecha) = YEAR(vDate) - 1
            AND (c.Id_Trabajador = vWorker OR tr.boss = vWorker)
    GROUP BY c.Id_Cliente) CmLy ON CmLy.Id_Cliente = c.Id_Cliente
        LEFT JOIN
    (SELECT 
        c.Id_Cliente,
            IF(MAX(Fecha) < DATE_FORMAT(TIMESTAMPADD(MONTH, - 1, vDate), '%Y- %m-01'), TRUE, FALSE) muerto
    FROM
        vn2008.Facturas f
    JOIN vn2008.Clientes c ON c.Id_cliente = f.Id_Cliente
    
    LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador
    WHERE
        (c.Id_Trabajador = vWorker OR tr.boss = vWorker)
    GROUP BY Id_Cliente) dead ON dead.Id_Cliente = c.Id_Cliente
    JOIN tmp.subordinate s ON s.workerFk = c.Id_Trabajador;

DROP TEMPORARY TABLE tmp.subordinate;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `compradores_add` */;
ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `compradores_add`(IN intYEAR INT, IN intWEEK_START INT, IN intWEEK_END INT)
BEGIN

REPLACE bs.compradores

SELECT tp.Id_Trabajador
     , intYEAR as año
     , tm.week as semana
     , sum(importe) as importe
     , 0 as comision
     
FROM bs.ventas v
JOIN vn2008.time tm on tm.date = v.fecha
JOIN vn2008.Tipos tp using(tipo_id)
WHERE tm.year = intYEAR and tm.week between intWEEK_START and intWEEK_END
AND reino_id != 6
GROUP BY tp.Id_Trabajador, tm.week;




END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `compradores_add_launcher` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `compradores_add_launcher`()
BEGIN

	DECLARE vYear INT;
    DECLARE vWeek INT;
    DECLARE done BOOL DEFAULT FALSE;
	  
	DECLARE rs CURSOR FOR
		SELECT year, week
			FROM vn.time
            WHERE (year = vYear AND week >= vWeek)
				OR year > vYear;
                
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
  
    SELECT MAX(año) INTO vYear 
		FROM compradores;
        
	SELECT MAX(semana) INTO vWeek
		FROM compradores 
        WHERE año = vYear; 

	OPEN rs;

	FETCH rs INTO vYear, vWeek;

	WHILE NOT done DO

		CALL compradores_add(vYear, vWeek, vWeek);
		
		FETCH rs INTO vYear, vWeek;

	END WHILE;

	CLOSE rs;

	CALL compradores_evolution_add;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `compradores_evolution_add` */;
ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `compradores_evolution_add`()
BEGIN
/*

Inserta en la tabla compradores_evolution las ventas acumuladas en los ultimos 365 dias

*/

DECLARE datFEC DATE;


SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.compradores_evolution;

		WHILE datFEC < CURDATE() DO
        
					SELECT datFEC;

					REPLACE bs.compradores_evolution(  Id_Trabajador
                                                     , fecha
                                                     , importe)

					SELECT Id_Trabajador
                         , datFEC as fecha
                         , sum(importe) as importe
                         
                    FROM
                    (

							SELECT Id_Trabajador
								 , importe
							FROM bs.compradores_evolution
							WHERE fecha = TIMESTAMPADD(DAY,-1,datFEC)  -- las ventas acumuladas del dia anterior
			
							UNION ALL
							
							SELECT Id_Trabajador
								 , importe * IF(v.fecha < datFEC,-1,1)  -- se restan las ventas del año anterior y se suman las del actual
							FROM bs.ventas v
							JOIN vn2008.Tipos tp using(tipo_id)
							WHERE fecha IN (datFEC, TIMESTAMPADD(DAY,-365,datFEC))
							AND reino_id != 6
                            
					)sub 
                    GROUP BY Id_Trabajador;
						
                        
                        
                        
					SET datFEC = TIMESTAMPADD(DAY,1,datFEC);

		END WHILE;


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `fondo_evolution_add` */;
ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `fondo_evolution_add`()
BEGIN
/*

Inserta en la tabla fondo_maniobra los saldos acumulados en los ultimos 365 dias

*/

DECLARE datFEC DATE DEFAULT '2015-01-01';


SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.fondo_maniobra;

		WHILE datFEC < CURDATE() DO
        
					-- esto solo sirve para no aburrirse mientras esperamos...
                    
					IF day(datFEC) mod 28 = 0 then 
                       SELECT datFEC;
					end if;
                    
                    
					REPLACE bs.fondo_maniobra(Fecha, clientes_facturas, clientes_cobros,proveedores_facturas,proveedores_pagos, fondo)
					SELECT datFEC as Fecha, Facturas, Cobros,Recibidas,Pagos, Facturas + Cobros + Recibidas + Pagos
					FROM
					(
					SELECT Sum(Facturas.Importe) AS Facturas
					FROM vn2008.Facturas 
					INNER JOIN vn2008.Clientes ON Facturas.Id_Cliente = Clientes.Id_cliente
					WHERE Clientes.`real`
					AND empresa_id <>1381 
					AND Fecha between '2011-01-01' and datFEC) fac
					JOIN
					(
					SELECT - Sum(Entregado) AS Cobros
					FROM vn2008.Recibos 
					INNER JOIN vn2008.Clientes ON Recibos.Id_Cliente = Clientes.Id_cliente
					WHERE Clientes.`real`
					AND empresa_id <> 1381
					AND Fechacobro Between '2011-01-01' and datFEC) cob
					JOIN
					(
					SELECT - Sum(cantidad) AS Recibidas
					FROM vn2008.recibida 
					INNER JOIN vn2008.recibida_vencimiento ON recibida.id = recibida_vencimiento.recibida_id
					WHERE empresa_id <> 1381
					AND recibida.fecha Between '2015-01-01' and datFEC) rec
					JOIN
					(
					SELECT Sum(importe) AS Pagos
					FROM vn2008.pago
					WHERE empresa_id <>1381 AND pago.fecha Between '2015-01-01' and datFEC) pag;

                     
                     
					UPDATE bs.fondo_maniobra
                    JOIN
                    (SELECT avg(fondo) as media
                    FROM bs.fondo_maniobra
                    WHERE fecha <= datFEC) sub
                    SET fondo_medio = media
                    WHERE fecha = datFEC;
                    
                    
					SET datFEC = TIMESTAMPADD(DAY,1,datFEC);

		END WHILE;


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `indicatorsUpdate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `indicatorsUpdate`(vDated DATE)
BEGIN

	DECLARE oneYearBefore DATE DEFAULT TIMESTAMPADD(YEAR,-1,vDated);
    DECLARE twoMonthsBefore DATE DEFAULT TIMESTAMPADD(DAY,-60,vDated);
	DECLARE oneMonthBefore DATE DEFAULT TIMESTAMPADD(DAY,-30,vDated);
    DECLARE vWeek INT;
    
    REPLACE indicators(updated)
		VALUES(vDated);
    
    -- Ventas totales del ultimo año
	UPDATE indicators
		SET  lastYearSales = 
			(
				SELECT SUM(importe + recargo)
					FROM bs.ventas v
						JOIN vn2008.empresa e ON e.id = v.empresa_id
						JOIN vn2008.empresa_grupo eg ON eg.empresa_grupo_id = e.empresa_grupo
					WHERE fecha BETWEEN oneYearBefore AND vDated
						AND eg.grupo = 'Verdnatura'
			) 
		WHERE updated = vDated;
   
    -- Greuge total acumulado
	UPDATE indicators
		SET  totalGreuge = 
			(
				SELECT SUM(amount)
					FROM vn.greuge
                    WHERE shipped <= vDated
			) 
		WHERE updated = vDated;
     
   
    -- Tasa de morosidad con respecto a las ventas del último mes
	UPDATE indicators
		SET  latePaymentRate = 
			(SELECT  SUM(amount) FROM bi.defaulters WHERE date = vDated and amount > 0)
            /
            ( SELECT SUM(importe + recargo) FROM bs.ventas WHERE fecha BETWEEN oneMonthBefore AND vDated)
		WHERE updated = vDated;
        
	-- Número de trabajadores activos
    UPDATE indicators
		SET  countEmployee = 
			( SELECT  CAST(SUM(hours_week) / 40 AS DECIMAL (10 , 2 ))
				 FROM
				  postgresql.business AS b
					JOIN postgresql.profile p ON p.profile_id = b.provider_id
					JOIN postgresql.person pe ON pe.person_id = p.person_id
				   LEFT JOIN
				  postgresql.business_labour AS bl ON bl.business_id = b.business_id
				   LEFT JOIN
				  postgresql.calendar_labour_type AS cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id
				 WHERE
                   (vDated BETWEEN b.date_start AND b.date_end OR (b.date_end IS NULL AND b.date_start <= vDated))
				   AND pe.name = 'VERDNATURA LEVANTE SL'
			)
		WHERE updated = vDated;

	-- Maná medio acumulado por comercial
    UPDATE indicators
		SET  averageMana = 
			(SELECT avg(used)
				FROM bs.mana_spellers
			)
		WHERE updated = vDated;
        
	-- Número de clientes que han comprado en los últimos 30 dias
    UPDATE indicators
		SET  lastMonthActiveClients = 
			(SELECT COUNT(DISTINCT t.clientFk)
				FROM vn.ticket t
					WHERE t.shipped BETWEEN oneMonthBefore AND vDated
			)
		WHERE updated = vDated;        
     
     -- Número de clientes que no han comprado en los últimos 30 dias, pero compraron en los 30 anteriores
    UPDATE indicators
		SET  lastMonthLostClients = 
			(SELECT COUNT(lm.clientFk)
				FROM 
					(
					SELECT DISTINCT t.clientFk
						FROM vn.ticket t
						WHERE t.shipped BETWEEN oneMonthBefore AND vDated
					) cm
					RIGHT JOIN
					(
					SELECT DISTINCT t.clientFk
						FROM vn.ticket t
						WHERE t.shipped >= twoMonthsBefore
							AND t.shipped < oneMonthBefore
					) lm ON lm.clientFk = cm.clientFk
					WHERE cm.clientFk IS NULL
			)
		WHERE updated = vDated;     
        
         -- Número de clientes que han comprado en los últimos 30 dias, pero no compraron en los 30 anteriores
    UPDATE indicators
		SET  lastMonthNewClients = 
			(SELECT COUNT(cm.clientFk)
				FROM 
					(
					SELECT DISTINCT t.clientFk
						FROM vn.ticket t
						WHERE t.shipped BETWEEN oneMonthBefore AND vDated
					) cm
					LEFT JOIN
					(
					SELECT DISTINCT t.clientFk
						FROM vn.ticket t
						WHERE t.shipped >= twoMonthsBefore
							AND t.shipped < oneMonthBefore
					) lm ON lm.clientFk = cm.clientFk
					WHERE lm.clientFk IS NULL
			)
		WHERE updated = vDated;     
        
        -- Porcentaje de autopedidos sobre los pedidos totales
    UPDATE indicators
		SET  lastMonthWebBuyingRate = 
			(  SELECT (SUM(source_app != '') - SUM(source_app = 'TPV')) /  SUM(source_app != '') 
					FROM hedera.`order` 
                    WHERE date_send BETWEEN oneMonthBefore AND vDated
			)
		WHERE updated = vDated;        
        
	-- Indicadores de producción
	UPDATE indicators i
		JOIN productionIndicators pi ON pi.dated = i.updated
        SET i.productionHours = pi.productionHours,
			i.dailyWorkersCost = pi.dailyWorkersCost,
            i.volumeM3 = pi.volumeM3,
            i.salesValue = pi.salesValue,
            i.valueM3 = pi.valueM3,
            i.hoursM3 = pi.hoursM3,
            i.workerCostM3 = pi.workerCostM3,
            i.salesWorkersCostRate  = pi.salesWorkersCostRate
        WHERE updated BETWEEN oneMonthBefore AND vDated;
        
     -- CAP Para el calculo de las ventas agrupado por semanas
     
        SELECT week 
		FROM vn.time 
		WHERE dated=vDated INTO vWeek;
	
		TRUNCATE `bs`.`salesByWeek`;
       
        INSERT INTO `bs`.`salesByWeek` (week,year,sales)
			SELECT 	`t`.`week` AS `week`,`t`.`year` AS `year`, SUM(`v`.`importe` + `v`.`recargo`) AS `sales`
				FROM `bs`.`ventas` `v`
					LEFT JOIN `vn`.`time` `t` ON `t`.`dated` = fecha
			GROUP BY `t`.`week` , `t`.`year`
			ORDER BY `t`.`week` , `t`.`year`;
                
	 -- CAP Indicador Ventas semana actual
        UPDATE indicators i 
			JOIN `bs`.`salesByWeek` s ON s.week= vWeek  AND s.year = YEAR(vDated)
		SET i.thisWeekSales = s.sales
		WHERE updated = vDated;   
        
     -- CAP indicador ventas semana actual en el año pasado 
        UPDATE indicators i 
			JOIN `bs`.`salesByWeek` s ON s.week= vWeek  AND s.year = YEAR(vDated)-1
		SET i.lastYearWeekSales = s.sales
		WHERE updated = vDated;

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

	DECLARE vDated DATE;

	SELECT IFNULL(TIMESTAMPADD(DAY,1,MAX(updated)), '2018-04-01')
		INTO vDated
		FROM bs.indicators;
		
	WHILE vDated < CURDATE() DO
    
		CALL indicatorsUpdate(vDated);
    
		SELECT TIMESTAMPADD(DAY,1,MAX(updated))
		INTO vDated
		FROM bs.indicators;
        
    END WHILE;

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

	DECLARE datSTART DATE;
    DECLARE datEND DATE;
   
    SELECT TIMESTAMPADD(WEEK, -1,MAX(fecha)) INTO datSTART
		FROM bs.m3;
        
	SET datEND = TIMESTAMPADD(DAY,-1,CURDATE());
        
	DELETE FROM bs.m3 
    WHERE fecha >= datSTART;
   
	INSERT INTO bs.m3 (fecha, provinceFk, warehouseFk, m3, year, month, week, day, dayName, euros)
		SELECT v.fecha, a.provinceFk, t.warehouseFk, sum(i.compression * s.quantity * r.cm3) / 1000000 AS m3,
				tm.year, tm.month, tm.week, tm.day, dayname(v.fecha), sum(importe)
		FROM vn.ticket t
			JOIN vn.sale s ON s.ticketFk = t.id
            JOIN vn.item i ON i.id = s.itemFk
            JOIN vn.itemType it ON it.id = i.typeFk
			JOIN bs.ventas v ON v.Id_Movimiento = s.id -- Filtra solo por ventas "buenas"
            JOIN vn.time tm ON tm.dated = v.fecha
			JOIN bi.rotacion r ON r.Id_Article = s.itemFk AND r.warehouse_id = t.warehouseFk
			JOIN vn.address a ON a.id = t.addressFk
		WHERE v.fecha BETWEEN datSTART AND datEND
		AND s.quantity > 0 -- evita abonos
		AND t.companyFk = 442 -- Verdnatura
		GROUP BY t.warehouseFk, v.fecha, a.provinceFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `manaCustomerUpdate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `manaCustomerUpdate`()
BEGIN
DECLARE vToDated DATE;
	DECLARE vFromDated DATE;
	DECLARE vForDeleteDated DATE;
	DECLARE vManaId INT DEFAULT 37;
	DECLARE vManaAutoId INT DEFAULT 39;
	DECLARE vManaBankId INT DEFAULT 66;
	DECLARE vManaGreugeTypeId INT DEFAULT 3;

	SELECT IFNULL(max(dated), '2016-01-01')
            INTO vFromDated 
        FROM bs.manaCustomer;
	
    DELETE 
		FROM bs.manaCustomer 
		WHERE dated = vFromDated;

	SELECT IFNULL(max(dated), '2016-01-01')
            INTO vFromDated 
        FROM bs.manaCustomer;

    WHILE timestampadd(DAY,30,vFromDated) < CURDATE() DO

        SELECT
                timestampadd(DAY,30,vFromDated),
                timestampadd(DAY,-90,vFromDated) 
            INTO 
                vToDated,
                vForDeleteDated;
            
        DELETE FROM bs.manaCustomer 
            WHERE dated <= vForDeleteDated;


        INSERT INTO bs.manaCustomer(Id_Cliente, Mana, dated)

            SELECT 
                    Id_Cliente,
                    cast(sum(mana) as decimal(10,2)) as mana,
                    vToDated as dated 
                FROM 

                (
                    SELECT cs.Id_Cliente, Cantidad * Valor as mana
                        FROM vn2008.Tickets t
                            JOIN vn2008.Consignatarios cs using(Id_Consigna)
                            JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket
                            JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento
                        WHERE Id_Componente IN (vManaAutoId, vManaId)
                            AND t.Fecha > vFromDated 
                            AND date(t.Fecha) <= vToDated
                    

                    UNION ALL

                    SELECT r.Id_Cliente, - Entregado
                        FROM vn2008.Recibos r
                        WHERE Id_Banco = vManaBankId
                            AND Fechacobro > vFromDated 
                            AND Fechacobro <= vToDated
                    
                    UNION ALL
                    
                    SELECT g.Id_Cliente, g.Importe
                        FROM vn2008.Greuges g
                        WHERE Greuges_type_id = vManaGreugeTypeId
                            AND Fecha > vFromDated 
                            AND Fecha <= vToDated
                    
                    UNION ALL
                    
                    SELECT Id_Cliente, mana
                        FROM bs.manaCustomer
                        WHERE dated = vFromDated    
                ) sub

                GROUP BY Id_Cliente
                HAVING Id_Cliente;

        SET vFromDated = vToDated;
               
    END WHILE;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `mana_price_modifier_update`()
BEGIN
	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))) ;
		
	-- pak 20/11/18   Petición expresa de Miriam. Quiere un 1% mínimo
	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())
		AND Id_Trabajador = 24 -- Miriam
		) ultimo_año_de_ventas using(Id_Trabajador)
	SET prices_modifier_rate =  GREATEST(0.01,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 `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;

	SET max_sp_recursion_depth=3;
	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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nocturnEvent_Tickets_Bionizar`()
BEGIN
/*

 DECLARE vDone INT DEFAULT FALSE;
 DECLARE vId BIGINT;
 DECLARE vMaxSaleComponent DATE ;
 DECLARE rs CURSOR FOR 
	SELECT sub.id
		FROM (SELECT t.id as ticket,s.id, s.price *(1-(s.discount/100)) as price, SUM(sc.value) AS total, (s.price *(1-(s.discount/100)))- SUM(sc.value) as totales
					FROM vn.ticket t 
						JOIN vn.sale s 
							ON s.ticketFk=t.id 
						JOIN vn.item i 
							ON i.id=s.itemFk 
						JOIN vn.itemType it 
							ON i.typeFk=it.id 
						LEFT JOIN vn.saleComponent sc 
							ON s.id=sc.saleFk 
						JOIN vn.warehouse w ON w.id=t.warehouseFk 
				    WHERE t.shipped>=DATE_ADD(CURDATE(), INTERVAL -7 DAY)
						AND it.categoryFk<6 
						AND t.companyFk=442
                        AND w.name!='Inventario'
					GROUP BY s.id 
					HAVING ABS(price-IFNULL(total,0))>0.01 ) AS sub;

 DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

 OPEN rs;

 read_loop: LOOP
	FETCH rs INTO vId;

 IF vDone THEN
		LEAVE read_loop;
 END IF;
	
	CALL vn2008.bionic_calc_movement(vId);
	
 END LOOP;
 CLOSE rs;


*/


/*

 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;
*/
/* PAK 12/03/2018  No cal rebionitzar. Anem a intentar que els tickets es facen tots correctament.

SET MyDate = timestampadd(week,-1,curdate());

WHILE MyDate < CURDATE() DO

	CALL `vn2008`.`bionic_tickets_range_bionizar`(MyDate, MyDate);

	SET MyDate = timestampadd(DAY,1,MyDate);

	SELECT MyDate;

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 `payMethodClientAdd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `payMethodClientAdd`()
BEGIN
	INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk)  
		SELECT  CURDATE(), c.payMethodFk, c.id
			FROM vn.client c    
				JOIN vn.payMethod p ON c.payMethodFk = p.id;
	
    TRUNCATE  `bs`.`payMethodClientEvolution` ;
     
    INSERT INTO  `bs`.`payMethodClientEvolution` (dated, payMethodName, amountClient, amount, equalizationTax)
		SELECT p.dated, pm.name, COUNT(p.clientFk), SUM(sub.importe) , SUM(sub.recargo) 
			 FROM bs.payMethodClient p
			 JOIN  (SELECT SUM(v.importe) AS importe, SUM(v.recargo) as recargo, v.fecha, v.Id_cliente 
				 FROM bs.ventas v
				 WHERE v.fecha>= (SELECT MIN(dated) FROM bs. payMethodClient)
				 GROUP BY v.Id_cliente, v.fecha) sub ON sub.fecha = p.dated AND sub.Id_cliente = p.ClientFk
			 JOIN vn.payMethod pm ON p.payMethodFk = pm.id
		GROUP BY dated,payMethodFk;    			
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `productivityAdd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `productivityAdd`(vDate DATE)
BEGIN

	DECLARE vDateStart DATETIME DEFAULT DATE(vDate);
	DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate);
        
    DROP TEMPORARY TABLE IF EXISTS tmp.productivity;
    
    CREATE TEMPORARY TABLE tmp.productivity
		ENGINE = MEMORY
        SELECT 	hh, 
				mm, 
				000.00 as m3, 
				0 as workers, 
				000.00 as wCost,
				0 as numCoordinadores,
				000.00 as costCoordinacion,
				0 as numSacadores,
				000.00 as costSacado,
				0 as numEncajadores,
				000.00 as costEncajado,
				0 as numPaletizadores,
				000.00 as costPaletizado,
                0 as numCamareros,
                000.00 as costCamara,
                0 as numComplementos,
                000.00 as costComplementos
			FROM vn.dayMinute;
    
-- Trabajadores
    CALL vn.dayMinuteWorker(vDateStart,vDateEnd); -- Genera la tabla tmp.dayMinuteWorker
	CALL vn.workerDepartmentByDate(vDate);
    
    -- General
    UPDATE tmp.productivity p
		JOIN 
			(SELECT Hora, Minuto,  count(*) as workers, sum(wdd.costeHora) / 60 as Bruto
				FROM tmp.dayMinuteWorker dmw
					JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk
                WHERE Almacen IN (1,44)
					AND wdd.production
				GROUP BY Hora, Minuto
			) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto
		SET p.workers = sub.workers, p.wCost = sub.Bruto;
   
   -- Coordinadores
   UPDATE tmp.productivity p
		JOIN 
			(SELECT Hora, Minuto,  count(*) as workers, sum(wdd.costeHora) / 60 as Bruto
				FROM tmp.dayMinuteWorker dmw
					JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk
                WHERE Almacen IN (1,44)
					AND wdd.department = 'COORDINACION'
				GROUP BY Hora, Minuto
			) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto
		SET p.numCoordinadores = sub.workers, p.costCoordinacion = sub.Bruto;
        
	 -- Sacado
   UPDATE tmp.productivity p
		JOIN 
			(SELECT Hora, Minuto,  count(*) as workers, sum(wdd.costeHora) / 60 as Bruto
				FROM tmp.dayMinuteWorker dmw
					JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk
                WHERE Almacen IN (1,44)
					AND wdd.department = 'SACADO'
				GROUP BY Hora, Minuto
			) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto
		SET p.numSacadores = sub.workers, p.costSacado = sub.Bruto;
        
	 -- Encajado
   UPDATE tmp.productivity p
		JOIN 
			(SELECT Hora, Minuto,  count(*) as workers, sum(wdd.costeHora) / 60 as Bruto
				FROM tmp.dayMinuteWorker dmw
					JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk
                WHERE Almacen IN (1,44)
					AND wdd.department = 'ENCAJADO'
				GROUP BY Hora, Minuto
			) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto
		SET p.numEncajadores = sub.workers, p.costEncajado = sub.Bruto;
        
	 -- Paletizado
   UPDATE tmp.productivity p
		JOIN 
			(SELECT Hora, Minuto,  count(*) as workers, sum(wdd.costeHora) / 60 as Bruto
				FROM tmp.dayMinuteWorker dmw
					JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk
                WHERE Almacen IN (1,44)
					AND wdd.department = 'PALETIZADO'
				GROUP BY Hora, Minuto
			) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto
		SET p.numPaletizadores = sub.workers, p.costPaletizado = sub.Bruto;
        
		 -- Cámara
   UPDATE tmp.productivity p
		JOIN 
			(SELECT Hora, Minuto,  count(*) as workers, sum(wdd.costeHora) / 60 as Bruto
				FROM tmp.dayMinuteWorker dmw
					JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk
                WHERE Almacen IN (1,44)
					AND wdd.department = 'CAMARA'
				GROUP BY Hora, Minuto
			) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto
		SET p.numCamareros = sub.workers, p.costCamara = sub.Bruto;
        
        -- Complementos
   UPDATE tmp.productivity p
		JOIN 
			(SELECT Hora, Minuto,  count(*) as workers, sum(wdd.costeHora) / 60 as Bruto
				FROM tmp.dayMinuteWorker dmw
					JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk
                WHERE Almacen IN (1,44)
					AND wdd.department = 'COMPLEMENTOS'
				GROUP BY Hora, Minuto
			) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto
		SET p.numComplementos = sub.workers, p.costComplementos = sub.Bruto;
   
	-- m3
    CALL vn.ticketBuiltTime(vDate); -- Genera la tabla tmp.ticketBuiltTime(ticketFk,builtTime)
    CALL vn.ticketVolumeByDate(vDate); -- Genera la tabla tmp.ticketVolumeByDate(ticketFk,m3)
    
    UPDATE tmp.productivity p
		JOIN 
			(SELECT HOUR(builtTime) hh, MINUTE(builtTime) mm, sum(m3) as m3
				FROM tmp.ticketBuiltTime tbt
                JOIN tmp.ticketVolumeByDate tvd ON tvd.ticketFk = tbt.ticketFk
                JOIN vn.ticket t ON t.id = tbt.ticketFk
                WHERE t.warehouseFk IN (1,44)
                GROUP BY hh,mm
			) v ON v.hh = p.hh AND v.mm = p.mm
		SET p.m3 = v.m3;
	
    DELETE FROM bs.productivity 
		WHERE dated = vDate;
        
	INSERT INTO bs.productivity(dated, 
								hh, 
								mm, 
								m3, 
								workers, 
								wCost, 
								numCoordinadores,
								costCoordinacion,
								numSacadores,
								costSacado,
								numEncajadores,
								costEncajado,
								numPaletizadores,
								costPaletizado,
                                numCamareros,
                                costCamara,
                                numComplementos,
                                costComplementos)
		SELECT 	vDate, 
				hh, 
				mm, 
				m3, 
				workers, 
				wCost, 
				numCoordinadores,
				costCoordinacion,
				numSacadores,
				costSacado,
				numEncajadores,
				costEncajado,
				numPaletizadores,
				costPaletizado,
                numCamareros,
                costCamara,
                numComplementos,
                costComplementos
			FROM tmp.productivity p;
    
    -- Productivity Evolution
	REPLACE bs.productivity_evolution(dated, m3productionCost) 
		SELECT CURDATE(), sum(wCost) / sum(m3)
			FROM bs.productivity
            WHERE dated BETWEEN TIMESTAMPADD(YEAR,-1,CURDATE()) AND CURDATE();
            
    DROP TEMPORARY TABLE tmp.dayMinuteWorker;
    DROP TEMPORARY TABLE tmp.productivity;
    DROP TEMPORARY TABLE tmp.ticketBuiltTime;
    DROP TEMPORARY TABLE tmp.ticketVolumeByDate;
	DROP TEMPORARY TABLE tmp.workerDepartmentByDate;
    

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `productivityDepartmentAdd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `productivityDepartmentAdd`(IN vDateStartPeriod DATETIME, IN vDateEndPeriod DATETIME, IN vDateStart DATETIME)
BEGIN

	DECLARE vEndingDate DATETIME;

	SET vEndingDate = vDateStart;

	WHILE vEndingDate <= vDateEndPeriod DO
		REPLACE INTO bs.productivityDepartment
		SELECT vEndingDate,
			   CAST(((productivityCoordinacionLastYear - productivityCoordinacion) / 2) * m3 AS DECIMAL (10,2)) AS amountCoordinacion,
			   CAST(((productivitySacadoLastYear - productivitySacado) / 2) * m3 AS DECIMAL (10,2)) AS amountSacado,
			   CAST(((productivityEncajadoLastYear - productivityEncajado) / 2) * m3 AS DECIMAL (10,2)) AS amountEncajado,
			   CAST(((productivityPaletizadoLastYear - productivityPaletizado) / 2) * m3 AS DECIMAL (10,2)) AS amountPaletizado,
               CAST(((productivityCamaraLastYear - productivityCamara) / 2) * m3 AS DECIMAL (10,2)) AS amountCamara,
               CAST(((productivityComplementosLastYear - productivityComplementos) / 2) * m3 AS DECIMAL (10,2)) AS amountComplementos
		FROM
			(SELECT 
				SUM(p.m3) AS m3,
					SUM(p.costCoordinacion) / SUM(p.m3) AS productivityCoordinacion,
					SUM(p.costSacado) / SUM(p.m3) AS productivitySacado,
					SUM(p.costEncajado) / SUM(p.m3) AS productivityEncajado,
					SUM(p.costPaletizado) / SUM(p.m3) AS productivityPaletizado,
                    SUM(p.costCamara) / SUM(p.m3) AS productivityCamara,
                    SUM(p.costComplementos) / SUM(p.m3) AS productivityComplementos
			FROM
				bs.productivity p
			WHERE
				p.dated BETWEEN vDateStartPeriod AND vEndingDate) sub
				JOIN
			(SELECT 
				SUM(p.costCoordinacion) / SUM(p.m3) AS productivityCoordinacionLastYear,
					SUM(p.costSacado) / SUM(p.m3) AS productivitySacadoLastYear,
					SUM(p.costEncajado) / SUM(p.m3) AS productivityEncajadoLastYear,
					SUM(p.costPaletizado) / SUM(p.m3) AS productivityPaletizadoLastYear,
                    SUM(p.costCamara) / SUM(p.m3) AS productivityCamaraLastYear,
                    SUM(p.costComplementos) / SUM(p.m3) AS productivityComplementosLastYear
			FROM
				bs.productivity p
			WHERE
				p.dated BETWEEN DATE_ADD(vDateStartPeriod, INTERVAL - 1 YEAR) AND DATE_ADD(vEndingDate, INTERVAL - 1 YEAR)) sub1;
			
			SET vEndingDate = TIMESTAMPADD(DAY,1, vEndingDate);
	  END WHILE;
  END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `productivityDepartmentLauncher` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `productivityDepartmentLauncher`()
BEGIN
	CALL bs.productivityDepartmentAdd('2018-11-01', CURDATE(),DATE_SUB(CURDATE(), INTERVAL 2 WEEK));
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `productivityLauncher` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `productivityLauncher`()
BEGIN

	DECLARE vDateFrom DATE DEFAULT TIMESTAMPADD(MONTH, -1, CURDATE());
    
    WHILE CURDATE() > vDateFrom DO
    	CALL bs.productivityAdd(vDateFrom);
		SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom);
    END WHILE;
    
    SET vDateFrom = TIMESTAMPADD(MONTH, -13, CURDATE());
    
    WHILE TIMESTAMPADD(MONTH, -12, CURDATE()) > vDateFrom DO
    	CALL bs.productivityAdd(vDateFrom);
		SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom);
    END WHILE;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `pruebas` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `pruebas`(IN vDateStart DATE, IN vDateEnd DATE)
BEGIN

WHILE vDateStart <> vDateEnd
DO
 UPDATE indicators
   SET  countEmployee = 
    ( SELECT  CAST(SUM(hours_week) / 40 AS DECIMAL (10 , 2 ))
				 FROM
				  postgresql.business AS b
					JOIN postgresql.profile p ON p.profile_id = b.provider_id
					JOIN postgresql.person pe ON pe.person_id = p.person_id
				   LEFT JOIN
				  postgresql.business_labour AS bl ON bl.business_id = b.business_id
				   LEFT JOIN
				  postgresql.calendar_labour_type AS cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id
				 WHERE
                   (vDateStart BETWEEN b.date_start AND b.date_end OR (b.date_end IS NULL AND b.date_start <= vDateStart))
				   AND pe.name = 'VERDNATURA LEVANTE SL'
        )
   WHERE updated = vDateStart;
 SET vDateStart = DATE_ADD(vDateStart, INTERVAL 1 DAY);
    
END WHILE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `salePersonEvolutionAdd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `salePersonEvolutionAdd`(IN vDateStart DATETIME)
BEGIN
	DELETE FROM bs.salePersonEvolution 
				WHERE  dated <=  DATE_SUB(CURDATE(), INTERVAL 1 YEAR);
    
    
    INSERT INTO bs.salePersonEvolution (dated, amount, equalizationTax, salesPersonFk)
		SELECT fecha dated, 
				CAST(SUM(importe) AS DECIMAL(10,2) ) amount, 
				CAST(SUM(recargo) AS DECIMAL(10,2) ) equalizationTax ,
				IFNULL(salesPersonFk,0) salesPersonFk
			FROM bs.ventas v
				JOIN vn.client c ON v.Id_Cliente = c.id 
				JOIN vn.company co ON co.id = v.empresa_id
			WHERE co.code = "VNL" AND fecha >= vDateStart
		 GROUP BY v.fecha,c.salesPersonFk
		 ORDER BY salesPersonFk,dated ASC;    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `userSundayRole` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `userSundayRole`()
BEGIN
	-- 4996 Fran Natek Echevarria
	DECLARE vDay INT;
	SET vDay := (SELECT DAYOFWEEK(CURDATE()));
    IF vDay = 1 THEN
		UPDATE account.user u
			JOIN  account.role r 
        SET u.role = r.id 
		WHERE u.id = 4996 AND  r.name = "salesAssistant";
	ELSE
		UPDATE account.user u
			JOIN  account.role r 
        SET u.role = r.id 
		WHERE u.id = 4996 AND  r.name = "salesPerson";
	END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `vendedores_add` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_add`(IN intYEAR INT, IN intMONTH INT)
BEGIN

	DECLARE comisionRate DOUBLE DEFAULT 0.029;

	REPLACE vendedores
	SELECT c.Id_Trabajador
		 , intYEAR
		 , intMONTH
		 , sum(importe) as importe
		 , sum(importe) * 0.029 as comision
		 , 0 as comisionCedida
		 , 0 as comisionArrendada
		 , 0 as comisionNuevos
		 
		FROM ventas v
			JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente
			JOIN vn2008.time 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 nuevas

	UPDATE vendedores
		JOIN
		(
		SELECT c.Id_Trabajador
			 , sum(importe) * 0.029 as comisionNueva
		FROM ventas v
			JOIN bs.clientNewBorn cnb on v.Id_Cliente = cnb.clientFk
            JOIN vn2008.Clientes c ON c.Id_Cliente = v.Id_Cliente
			JOIN vn2008.time 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
		) sub using(Id_Trabajador)
		SET comisionNuevos = sub.comisionNueva, comision = comision - sub.comisionNueva
		WHERE año = intYEAR and mes = intMONTH;

-- Ventas cedidas

UPDATE vendedores
JOIN
(
SELECT cc.Id_Trabajador_old as Id_Trabajador
     , sum(importe) * 0.029 * comision_old as cedido
     , sum(importe) * 0.029 * comision_new as arrendada
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 - arrendada
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
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 = util.dayEnd(datEND);
	SET vStartingDate = GREATEST('2015-10-01',datSTART);
	SET vEndingDate = vn2008.dayend(vStartingDate);

	DELETE 
		FROM ventas 
		WHERE fecha between vStartingDate and datEND;

	WHILE vEndingDate <= datEND DO
												
		REPLACE ventas(Id_Movimiento, importe, recargo, fecha, tipo_id, Id_Cliente, empresa_id)
			SELECT 	Id_Movimiento,
					sum(  IF(base, Cantidad * Valor, 0)  ) as importe,
                    sum(  IF(base, 0, Cantidad * Valor)  ) as recargo,
                    vStartingDate,
                    a.tipo_id,
                    cs.Id_Cliente,
                    t.empresa_id
			FROM vn2008.Movimientos_componentes mc
				JOIN bi.tarifa_componentes tc using(Id_Componente)
				JOIN bi.tarifa_componentes_series tcs using(tarifa_componentes_series_id)
				JOIN vn2008.Movimientos m using(Id_Movimiento)
				JOIN vn2008.Articles a using(Id_Article)
				JOIN vn2008.Tipos tp using(tipo_id)
				JOIN vn2008.reinos r on r.id = tp.reino_id
				JOIN vn2008.Tickets t using(Id_Ticket)
				JOIN vn2008.Consignatarios cs using(Id_Consigna)
				JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente
				-- 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 m.Cantidad <> 0
				AND a.tipo_id != TIPO_PATRIMONIAL
				AND c.Id_Trabajador IS NOT NULL
				AND m.Descuento <> 100
				AND (m.Id_Article = 98 or m.Id_Article = 95 or r.mercancia != 0)
			GROUP BY mc.Id_Movimiento
			HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0;

		SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate);
		SET vEndingDate = util.dayEnd(vStartingDate);

	END WHILE;

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

SET @datSTART = TIMESTAMPADD(YEAR,-2,CURDATE());
SET @datEND = TIMESTAMPADD(DAY,-DAY(CURDATE()),CURDATE());

DROP TEMPORARY TABLE IF EXISTS tmp.VivosMuertos;

CREATE TEMPORARY TABLE tmp.VivosMuertos
SELECT c.Id_Cliente, tm.yearMonth, f.Compra, 0 as Nuevo, 0 as Muerto
FROM vn2008.Clientes c
JOIN (SELECT DISTINCT yearMonth FROM vn2008.time WHERE date BETWEEN @datSTART AND @datEND ) tm
LEFT JOIN
	(SELECT DISTINCT tm.yearMonth, f.Id_Cliente , 1 as Compra
		FROM vn2008.Facturas f
        JOIN vn2008.time tm ON tm.date = f.Fecha
		WHERE Fecha BETWEEN @datSTART AND @datEND) f ON f.yearMonth = tm.yearMonth AND f.Id_Cliente = c.Id_Cliente;
        
UPDATE tmp.VivosMuertos vm
JOIN (
  SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente 
		FROM vn2008.Facturas f
        JOIN vn2008.time tm ON tm.date = f.Fecha
		WHERE Fecha BETWEEN @datSTART AND @datEND
        GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth  AND fm.Id_Cliente = vm.Id_Cliente
SET Nuevo = 1;
  
SELECT max(yearMonth) INTO @lastYearMonth FROM tmp.VivosMuertos;
 
UPDATE tmp.VivosMuertos vm
JOIN (
  SELECT MAX(tm.yearMonth) firstMonth, f.Id_Cliente 
		FROM vn2008.Facturas f
        JOIN vn2008.time tm ON tm.date = f.Fecha
		WHERE Fecha BETWEEN @datSTART AND @datEND
        GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth  AND fm.Id_Cliente = vm.Id_Cliente
SET Muerto = 1
WHERE yearMonth < @lastYearMonth;
  
  SELECT * FROM tmp.VivosMuertos;

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

	REPLACE bs.warehouseProduction(fecha, warehouse_id, m3)
		SELECT  v.fecha, 
				t.warehouseFk, 
				cast(sum( s.quantity * r.cm3) / 1000000  as decimal(10,0)) as m3 
			FROM vn.ticket t
				JOIN vn.sale s ON s.ticketFk = t.id
				JOIN bs.ventas v ON v.Id_Movimiento = s.id
				JOIN bi.rotacion r on s.itemFk = r.Id_Article AND t.warehouseFk = r.warehouse_id 
			WHERE v.fecha BETWEEN TIMESTAMPADD(MONTH, -1, CURDATE()) AND util.yesterday()
			GROUP BY v.fecha, 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 */ ;

--
-- 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,
  UNIQUE KEY `calc_id` (`item_id`,`calc_id`) USING HASH,
  KEY `calc_id_4` (`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 `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=13 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=337624 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` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `valid` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MEMORY AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!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 `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,
  UNIQUE KEY `item_id` (`item_id`,`warehouse_id`) USING HASH,
  KEY `buy_id` (`buy_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` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `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,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=764562 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,
  UNIQUE KEY `warehouse_id` (`warehouse_id`,`item_id`) USING HASH,
  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 `ticketShipping`
--

DROP TABLE IF EXISTS `ticketShipping`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketShipping` (
  `calc_id` int(11) NOT NULL,
  `ticketFk` int(11) unsigned NOT NULL,
  `shippingHour` int(3) NOT NULL,
  `shippingMinute` int(3) NOT NULL,
  PRIMARY KEY (`calc_id`,`ticketFk`),
  KEY `ticketShipping` (`ticketFk`)
) ENGINE=InnoDB 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,
  UNIQUE KEY `calc_id` (`calc_id`,`item_id`) USING HASH,
  KEY `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 `weeklySales`
--

DROP TABLE IF EXISTS `weeklySales`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `weeklySales` (
  `week` int(10) unsigned NOT NULL,
  `itemFk` int(10) unsigned NOT NULL,
  `warehouseFk` smallint(5) unsigned NOT NULL,
  `amount` int(11) NOT NULL,
  `price` double NOT NULL,
  UNIQUE KEY `week_2` (`week`,`itemFk`,`warehouseFk`),
  KEY `week` (`week`) USING BTREE
) ENGINE=InnoDB 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 `cacheCalc_clean` */;
DELIMITER ;;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
/*!50003 SET character_set_client  = utf8mb4 */ ;;
/*!50003 SET character_set_results = utf8mb4 */ ;;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone      = @@time_zone */ ;;
/*!50003 SET time_zone             = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `cacheCalc_clean` ON SCHEDULE EVERY 30 MINUTE STARTS '2017-01-23 13:15:58' ON COMPLETION NOT PRESERVE ENABLE DO CALL cacheCalc_clean */ ;;
/*!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 `cache_clean` */;;
DELIMITER ;;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
/*!50003 SET character_set_client  = utf8mb4 */ ;;
/*!50003 SET character_set_results = utf8mb4 */ ;;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone      = @@time_zone */ ;;
/*!50003 SET time_zone             = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`z-developer`@`%`*/ /*!50106 EVENT `cache_clean` ON SCHEDULE EVERY 5 MINUTE STARTS '2019-04-29 13:06:16' ON COMPLETION NOT PRESERVE ENABLE DO CALL cache_clean */ ;;
/*!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 'cache'
--
/*!50003 DROP FUNCTION IF EXISTS `ticketShippingCalcIdGet` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketShippingCalcIdGet`(vWarehouseFk INT) RETURNS int(11)
BEGIN
	-- OBSOLETO usar CALL ticketShippingRefresh(vCalcFk,FALSE,vWarehouseFk)
    -- JGF 2019-02-05
	DECLARE vCalcFk INT;

	CALL ticketShippingRefresh(vCalcFk,FALSE,vWarehouseFk);
    
	RETURN vCalcFk;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`z-developer`@`%` PROCEDURE `available_clean`()
BEGIN
	DROP TEMPORARY TABLE IF EXISTS tCalc;
	CREATE TEMPORARY TABLE tCalc
		(INDEX (id))
		ENGINE = MEMORY
		SELECT id FROM cache_calc;

	DELETE a
		FROM available a
			LEFT JOIN tCalc c ON c.id = a.calc_id
		WHERE c.id IS NULL;
		
	DROP TEMPORARY TABLE tCalc;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `available_refresh`(OUT `vCalc` INT, IN `vRefresh` INT, IN `vWarehouse` INT, IN `vDate` DATE)
proc: BEGIN
	DECLARE vStartDate DATE;
	DECLARE vEndDate DATETIME;
	DECLARE vReserveDate DATETIME;
	DECLARE vParams CHAR(100);
	DECLARE vInventoryDate DATE;

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

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

	CALL vn2008.item_stock (vWarehouse, vDate, NULL);

	SET vParams = CONCAT_WS('/', vWarehouse, vDate);
	CALL cache_calc_start (vCalc, vRefresh, 'available', vParams);

	IF !vRefresh THEN
		LEAVE proc;
	END IF;

	-- Calcula algunos parámetros necesarios

	SET vStartDate = TIMESTAMP(vDate, '00:00:00');
	SET vEndDate = TIMESTAMP(TIMESTAMPADD(DAY, 4, vDate), '23:59:59');

	SELECT FechaInventario INTO vInventoryDate FROM vn2008.tblContadores;

	SELECT SUBTIME(NOW(), reserveTime) INTO vReserveDate
		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 vInventoryDate AND vStartDate
					AND t.warehouse_id = vWarehouse
					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 >= vStartDate OR date_end IS NULL;

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

	INSERT INTO available (calc_id, item_id, available)
	SELECT vCalc, 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, vDate) 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 >= vStartDate
						AND (ir.date_end IS NULL OR i.dat <= ir.date_end)
						AND i.warehouse_id = vWarehouse
				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 >= vStartDate
						AND (ir.date_end IS NULL OR i.dat <= ir.date_end)
						AND i.warehouse_id = vWarehouse
				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 >= vStartDate 
						AND (ir.date_end IS NULL OR i.dat <= ir.date_end)
						AND i.warehouse_id = vWarehouse
				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 >= vStartDate
						AND (ir.date_end IS NULL OR r.shipment <= ir.date_end)
						AND r.warehouse_id = vWarehouse
						AND r.created >= vReserveDate
						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 (vCalc);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cacheCalc_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `cacheCalc_clean`()
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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_end`(IN `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;

	IF v_cache_name IS NOT NULL THEN
		DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, '')));
	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 `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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_start`(OUT `v_calc` INT, INOUT `v_refresh` INT, IN `v_cache_name` VARCHAR(50), IN `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
		IF v_lock_id IS NOT NULL THEN
			DO RELEASE_LOCK(v_lock_id);
        END IF;

		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` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_unlock`(IN `v_calc` INT)
proc: BEGIN
	DECLARE v_cache_name VARCHAR(50);
	DECLARE v_params VARCHAR(100);

	IF v_calc IS NULL THEN
		LEAVE proc;
	END IF;

	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;

	IF v_cache_name IS NOT NULL THEN
		DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, '')));
	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 `cache_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`z-developer`@`%` PROCEDURE `cache_clean`()
    NO SQL
BEGIN
	CALL available_clean;
	CALL visible_clean;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clean`()
BEGIN
  
    DECLARE vDateShort DATETIME; 

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

    DELETE FROM cache.departure_limit WHERE Fecha < vDateShort;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 `last_buy_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 `last_buy_refresh`(vRefresh 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 vRefresh %TRUE para forzar el recálculo de la cache
 **/
	DECLARE vCalc INT;
    DECLARE started DATE;
    DECLARE ended DATE;
    DECLARE vLastRefresh DATE;

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

    CALL cache_calc_start (vCalc, vRefresh, 'last_buy', NULL);

    IF !vRefresh
    THEN
		LEAVE proc;
	END IF;

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

	CALL vn.buyUltimateFromInterval(NULL, started, ended);

	DELETE FROM last_buy;

	INSERT INTO last_buy (item_id, warehouse_id, buy_id, landing)
		SELECT itemFk, warehouseFk, buyFk, landed
			FROM tmp.buyUltimateFromInterval;

	DROP TEMPORARY TABLE tmp.buyUltimateFromInterval;

    CALL cache_calc_end (vCalc);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!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 `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 AND isVirtualStock is FALSE
		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 `ticketShippingRefresh` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketShippingRefresh`(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, 'ticketShipping', v_warehouse);

	IF !v_refresh
	THEN
		LEAVE proc;
	END IF;

    -- Limpia las caches antiguas
	DELETE FROM ticketShipping WHERE calc_id NOT IN (
		SELECT cc.id
			FROM `cache` c
				JOIN cache_calc cc ON c.id = cc.cache_id
			WHERE c.`name` = 'ticketShipping')
		;
                    
	-- Iniciamos la tabla temporal con los valores que tienen los tickets actualmente en el campo Fecha
    DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer;
	CREATE TEMPORARY TABLE tmp.production_buffer
		ENGINE = MEMORY
		SELECT t.id as ticket
			, am.agencyFk as agency_id
			, t.warehouseFk as warehouse_id
			, a.provinceFk as province_id
			, Hour(t.shipped) as Hora
            , Hour(t.shipped) as Departure
            , Minute(t.shipped) as Minuto
			FROM vn.ticket t
			JOIN vn.agencyMode am on am.id = t.agencyModeFk
			JOIN vn.address a on a.id = t.addressFk
			WHERE t.shipped BETWEEN CURDATE() AND util.dayend(CURDATE());
			 
	CALL vn2008.production_buffer_set_priority;
	
    REPLACE ticketShipping(calc_id, ticketFk, shippingHour, shippingMinute)
		SELECT v_calc, ticket, Hora, Minuto
			FROM tmp.production_buffer;
            
	DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer;
    
    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_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `visible_clean`()
BEGIN
	DROP TEMPORARY TABLE IF EXISTS tCalc;
	CREATE TEMPORARY TABLE tCalc
		(INDEX (id))
		ENGINE = MEMORY
		SELECT id FROM cache_calc;
				
	DELETE v
		FROM visible v
			LEFT JOIN tCalc c ON c.id = v.calc_id
		WHERE c.id IS NULL;
		
	DROP TEMPORARY TABLE tCalc;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `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;
	
	-- 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 */ ;
/*!50003 DROP PROCEDURE IF EXISTS `weeklySales_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `weeklySales_refresh`(IN `v_refresh` INT)
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 weeklySales (itemFk, week, warehouseFk, 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 */ ;

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

DROP TABLE IF EXISTS `VMPSettings`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `VMPSettings` (
  `VMPID` int(11) NOT NULL,
  `MessageID` int(11) NOT NULL,
  PRIMARY KEY (`VMPID`)
) 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=478514 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`),
  KEY `fgbSupplyResponse_idx` (`supplyResponseID`),
  KEY `fgbSupplyResponse_idx2` (`FirstOrderDateTime`),
  KEY `fgbSupplyResponse_idx3` (`LatestOrderDateTime`),
  CONSTRAINT `fgbSupplyResponse` FOREIGN KEY (`supplyResponseID`) REFERENCES `supplyResponse` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=18264966 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `ekt`
--

DROP TABLE IF EXISTS `ekt`;
/*!50001 DROP VIEW IF EXISTS `ekt`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ekt` AS SELECT 
 1 AS `id`,
 1 AS `barcode`,
 1 AS `entry_year`,
 1 AS `delivery_number`,
 1 AS `fec`,
 1 AS `hor`,
 1 AS `now`,
 1 AS `ptj`,
 1 AS `ref`,
 1 AS `item`,
 1 AS `pac`,
 1 AS `qty`,
 1 AS `ori`,
 1 AS `cat`,
 1 AS `agj`,
 1 AS `kop`,
 1 AS `ptd`,
 1 AS `sub`,
 1 AS `pro`,
 1 AS `pri`,
 1 AS `package`,
 1 AS `auction`,
 1 AS `klo`,
 1 AS `k01`,
 1 AS `k02`,
 1 AS `k03`,
 1 AS `k04`,
 1 AS `s1`,
 1 AS `s2`,
 1 AS `s3`,
 1 AS `s4`,
 1 AS `s5`,
 1 AS `s6`,
 1 AS `ok`,
 1 AS `trolley_id`,
 1 AS `scanned`*/;
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) unsigned 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`),
  CONSTRAINT `item_fk1` FOREIGN KEY (`group_id`) REFERENCES `item_group` (`group_code`) ON DELETE CASCADE ON UPDATE CASCADE
) 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 `marketPlace`
--

DROP TABLE IF EXISTS `marketPlace`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `marketPlace` (
  `id` varchar(13) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `supplierFk` int(11) NOT NULL DEFAULT '1433',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB 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(10) unsigned NOT NULL AUTO_INCREMENT,
  `sender_id` int(10) unsigned DEFAULT NULL,
  `mail_id` varchar(100) COLLATE utf8_unicode_ci DEFAULT 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=503105 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=27 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,
  `supplyResponseID` int(11) DEFAULT NULL,
  `orderTradelineItemID` int(11) DEFAULT NULL COMMENT 'ticketFk or EntryFk?',
  `OrderTradeLineDateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'fecha de creacion en la tabla',
  `quantity` int(11) DEFAULT NULL,
  `EndUserPartyID` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `EndUserPartyGLN` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL,
  `OrderStatus` int(11) DEFAULT '0' COMMENT '1 pending\n2 confirmed\n3 canceled',
  `isOrderProcessed` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `orderTradelineItemID_UNIQUE` (`orderTradelineItemID`)
) ENGINE=InnoDB AUTO_INCREMENT=10 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 `edi`.`putOrder_BEFORE_INSERT` BEFORE INSERT ON `putOrder` FOR EACH ROW
BEGIN

	DECLARE nextID INT;
    
	SELECT 1 + MAX(id) INTO nextID FROM putOrder ;
    
    SET NEW.orderTradelineItemID  = nextID;

END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `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) COLLATE utf8_unicode_ci 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 */;

--
-- Temporary table structure for view `supplyOffer`
--

DROP TABLE IF EXISTS `supplyOffer`;
/*!50001 DROP VIEW IF EXISTS `supplyOffer`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `supplyOffer` AS SELECT 
 1 AS `diId`,
 1 AS `srId`,
 1 AS `Item_ArticleCode`,
 1 AS `product_name`,
 1 AS `company_name`,
 1 AS `Price`,
 1 AS `Quality`,
 1 AS `s1`,
 1 AS `s2`,
 1 AS `s3`,
 1 AS `s4`,
 1 AS `s5`,
 1 AS `s6`,
 1 AS `NumberOfUnits`,
 1 AS `EmbalageCode`,
 1 AS `LatestDeliveryDateTime`,
 1 AS `EarliestDespatchDateTime`,
 1 AS `FirstOrderDateTime`,
 1 AS `LatestOrderDateTime`,
 1 AS `NumberOfItemsPerCask`,
 1 AS `NumberOfLayersPerTrolley`,
 1 AS `MinimumNumberToOrder`,
 1 AS `MaximumNumberToOrder`,
 1 AS `IncrementalOrderableQuantity`,
 1 AS `PackingPrice`,
 1 AS `MarketPlaceID`,
 1 AS `PictureReference`,
 1 AS `marketPlace`,
 1 AS `OrderUnit`,
 1 AS `IncrementalOrderUnit`*/;
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` int(11) 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,
  `Quality` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `s1` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `s2` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `s3` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `s4` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `s5` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `s6` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ExaminiationCode1` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ExaminiationCode2` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `OrderUnitType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `EmbalageCode` int(11) 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,
  `PackingPriceQuantityType` 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,
  `MarketFormCode` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '"002" Standard Sales\n"005" Catalogue (optional)\n"001" Committed (optional)\n"003" Buffer (optional, Clock Pre Sales) ',
  PRIMARY KEY (`ID`),
  UNIQUE KEY `ID_UNIQUE` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=6038803 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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `batchNew`(IN `vMessage` INT, IN `vItem` VARCHAR(255), IN `vType` MEDIUMINT, IN `vDeliveryNumber` BIGINT, IN `vDate` DATE, IN `vHour` TIME, IN `vRef` INT, IN `vAgj` INT, IN `vCat` VARCHAR(2), IN `vPac` INT, IN `vSub` MEDIUMINT, IN `vKop` INT, IN `vPtd` VARCHAR(6), IN `vPro` MEDIUMINT, IN `vOrigin` VARCHAR(3), IN `vPtj` MEDIUMINT, IN `vQuantiy` INT, IN `vPrice` DOUBLE, IN `vClock` SMALLINT, IN `vS1` VARCHAR(3), IN `vS2` VARCHAR(3), IN `vS3` VARCHAR(3), IN `vS4` VARCHAR(4), IN `vS5` VARCHAR(3), IN `vS6` VARCHAR(3), IN `vK1` SMALLINT, IN `vK2` SMALLINT, IN `vP1` TINYINT, IN `vP2` TINYINT, IN `vAuction` SMALLINT, IN `vPackage` INT, IN `vPutOrderFk` 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
        ,putOrderFk = vPutOrderFk;


	-- 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 e.entry_year = YEAR(vDate)
				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
            ,putOrderFk = vPutOrderFk
		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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ediLoad`(IN `vEdi` INT)
BEGIN
	DECLARE vRef INT;
	DECLARE vBuy INT;
	DECLARE vItem INT;
	DECLARE vQty INT;
	DECLARE vPackage INT;
	DECLARE vIsLot BOOLEAN;
    DECLARE vForceToPacking INT DEFAULT 2;

	-- 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)
		,vForceToPacking
		,@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: `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=InnoDB 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',
  `defaultForm` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Form loaded at web login',
  `restUri` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The URI  for rest service',
  `testRestUri` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The URI  for test rest service',
  `guestUser` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Guest user name',
  `testDomain` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The address for beta website',
  `productionDomain` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The address for production website',
  `pdfsDir` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Directory where PDFs are allocated',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB 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=10 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=InnoDB 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,
  `collectionFk` 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` (`collectionFk`,`file`),
  CONSTRAINT `imageFile_ibfk_1` FOREIGN KEY (`collectionFk`) 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=InnoDB 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=InnoDB 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=InnoDB 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 `mainAccount`
--

DROP TABLE IF EXISTS `mainAccount`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mainAccount` (
  `accountFk` mediumint(8) unsigned NOT NULL,
  PRIMARY KEY (`accountFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `mainAccountBank`
--

DROP TABLE IF EXISTS `mainAccountBank`;
/*!50001 DROP VIEW IF EXISTS `mainAccountBank`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `mainAccountBank` AS SELECT 
 1 AS `name`,
 1 AS `iban`*/;
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=InnoDB 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=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

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

--
-- Temporary table structure for view `myBasket`
--

DROP TABLE IF EXISTS `myBasket`;
/*!50001 DROP VIEW IF EXISTS `myBasket`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `myBasket` AS SELECT 
 1 AS `id`,
 1 AS `made`,
 1 AS `sent`,
 1 AS `clientFk`,
 1 AS `deliveryMethodFk`,
 1 AS `agencyModeFk`,
 1 AS `addressFk`,
 1 AS `companyFk`,
 1 AS `notes`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `myBasketDefaults`
--

DROP TABLE IF EXISTS `myBasketDefaults`;
/*!50001 DROP VIEW IF EXISTS `myBasketDefaults`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `myBasketDefaults` AS SELECT 
 1 AS `deliveryMethod`,
 1 AS `agencyModeFk`,
 1 AS `addressFk`,
 1 AS `defaultAgencyFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `myBasketItem`
--

DROP TABLE IF EXISTS `myBasketItem`;
/*!50001 DROP VIEW IF EXISTS `myBasketItem`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `myBasketItem` AS SELECT 
 1 AS `id`,
 1 AS `orderFk`,
 1 AS `warehouseFk`,
 1 AS `itemFk`,
 1 AS `amount`,
 1 AS `price`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `myClient`
--

DROP TABLE IF EXISTS `myClient`;
/*!50001 DROP VIEW IF EXISTS `myClient`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `myClient` AS SELECT 
 1 AS `id`,
 1 AS `isToBeMailed`,
 1 AS `defaultAddressFk`,
 1 AS `credit`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `myInvoice`
--

DROP TABLE IF EXISTS `myInvoice`;
/*!50001 DROP VIEW IF EXISTS `myInvoice`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `myInvoice` AS SELECT 
 1 AS `id`,
 1 AS `ref`,
 1 AS `issued`,
 1 AS `amount`,
 1 AS `pdf`*/;
SET character_set_client = @saved_cs_client;

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

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

--
-- Temporary table structure for view `myOrder`
--

DROP TABLE IF EXISTS `myOrder`;
/*!50001 DROP VIEW IF EXISTS `myOrder`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `myOrder` AS SELECT 
 1 AS `id`,
 1 AS `landed`,
 1 AS `clientFk`,
 1 AS `deliveryMethodFk`,
 1 AS `agencyModeFk`,
 1 AS `addressFk`,
 1 AS `companyFk`,
 1 AS `note`,
 1 AS `sourceApp`,
 1 AS `isConfirmed`,
 1 AS `created`,
 1 AS `firstRowStamp`,
 1 AS `confirmed`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `myOrderMyTicket`
--

DROP TABLE IF EXISTS `myOrderMyTicket`;
/*!50001 DROP VIEW IF EXISTS `myOrderMyTicket`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `myOrderMyTicket` AS SELECT 
 1 AS `orderFk`,
 1 AS `ticketFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `myOrderRow`
--

DROP TABLE IF EXISTS `myOrderRow`;
/*!50001 DROP VIEW IF EXISTS `myOrderRow`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `myOrderRow` AS SELECT 
 1 AS `id`,
 1 AS `Fk`,
 1 AS `itemFk`,
 1 AS `warehouseFk`,
 1 AS `shipped`,
 1 AS `amount`,
 1 AS `price`,
 1 AS `rate`,
 1 AS `created`,
 1 AS `saleFk`*/;
SET character_set_client = @saved_cs_client;

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

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

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

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

--
-- Temporary table structure for view `myTicketState`
--

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

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

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

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

DROP TABLE IF EXISTS `news`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `news` (
  `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(150) COLLATE utf8_unicode_ci NOT NULL,
  `text` text COLLATE utf8_unicode_ci NOT NULL,
  `image` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `userFk` int(10) unsigned NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `priority` tinyint(3) unsigned NOT NULL DEFAULT '3',
  `tag` varchar(15) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'new',
  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=13068 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','SALIX','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=1917144 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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`order_afterUpdate`
	AFTER UPDATE ON `order`
    FOR EACH ROW
BEGIN
	CALL stock.log_add('order', OLD.id, NEW.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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`order_beforeDelete`
	BEFORE DELETE ON `order`
    FOR EACH ROW
BEGIN
	DELETE FROM orderRow WHERE orderFk = OLD.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 */ ;

--
-- 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,
  `defaultAgencyFk` int(11) DEFAULT 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`),
  KEY `defaultAgencyFk` (`defaultAgencyFk`),
  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,
  CONSTRAINT `orderConfig_ibfk_4` FOREIGN KEY (`defaultAgencyFk`) REFERENCES `vn2008`.`Agencias` (`Id_Agencia`)
) 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 NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=11602292 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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `orderRow_beforeInsert`
	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 */ ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`orderRow_afterInsert`
	AFTER INSERT ON `orderRow`
    FOR EACH ROW
BEGIN
	CALL stock.log_add('orderRow', NULL, NEW.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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`orderRow_afterUpdate`
	AFTER UPDATE ON `orderRow`
	FOR EACH ROW
BEGIN
	CALL stock.log_add('orderRow', OLD.id, NEW.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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`orderRow_afterDelete`
	AFTER DELETE ON `orderRow`
	FOR EACH ROW
BEGIN
	CALL stock.log_add('orderRow', OLD.id, 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 */ ;

--
-- Table structure for table `orderRowComponent`
--

DROP TABLE IF EXISTS `orderRowComponent`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `orderRowComponent` (
  `rowFk` int(10) unsigned NOT NULL,
  `componentFk` int(11) NOT NULL,
  `price` decimal(12,4) NOT NULL,
  PRIMARY KEY (`rowFk`,`componentFk`),
  KEY `component_id` (`componentFk`),
  CONSTRAINT `orderRowComponent_ibfk_1` FOREIGN KEY (`rowFk`) REFERENCES `orderRow` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `orderTicket`
--

DROP TABLE IF EXISTS `orderTicket`;
/*!50001 DROP VIEW IF EXISTS `orderTicket`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `orderTicket` AS SELECT 
 1 AS `orderFk`,
 1 AS `ticketFk`*/;
SET character_set_client = @saved_cs_client;

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

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

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

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

--
-- 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=InnoDB 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=312517 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 NOT 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=1771677 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=3877888 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=2376206 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=3442690 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 `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 `myBasket_getId` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `MYBASKET_GETID`() RETURNS int(11)
    DETERMINISTIC
BEGIN
	DECLARE vOrder INT;
    
    SELECT orderFk INTO vOrder FROM basketOrder
		WHERE clientFk = account.myUserGetId();

	RETURN 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 `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              = 'IGNORE_SPACE,STRICT_TRANS_TABLES,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);

DROP TEMPORARY TABLE IF EXISTS tmp.order;
CREATE TEMPORARY TABLE tmp.order
ENGINE = MEMORY
SELECT vOrder orderFk;

CALL orderGetTotal;

SELECT total INTO vTotal FROM tmp.orderTotal;

DROP TEMPORARY TABLE
tmp.order,
tmp.orderTotal;

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 `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.myUserHasRoleId (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 `bionicCalcWithDate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `bionicCalcWithDate`(vDate DATE)
BEGIN
    DECLARE vMyAddressFk INTEGER;
    DECLARE vMyAgencyModeFk INTEGER;
    
	SELECT id, agencyModeFk INTO vMyAddressFk, vMyAgencyModeFk 
		FROM myAddress 
        WHERE isDefaultAddress;
      
	CALL vn2008.bionic_calc(vDate, vMyAddressFk, vMyAgencyModeFk);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 vDate DATE;
	DECLARE vAddress INT;
	DECLARE vAgencyMode INT;
    
    SELECT sent, addressFk, agencyModeFk
    INTO vDate, vAddress, vAgencyMode
		FROM myBasket;

	CALL vn2008.bionic_calc(vDate, vAddress, vAgencyMode);

	IF account.myUserGetName() = '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_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              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `bionic_from_item`(vItem INT)
BEGIN
	DECLARE vDate DATE;
	DECLARE vAddress INT;
	DECLARE vAgencyMode INT;
    
    SELECT sent, addressFk, agencyModeFk
    INTO vDate, vAddress, vAgencyMode
		FROM myBasket;

	CALL vn2008.bionic_from_item(vDate, vAddress, vAgencyMode, 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 */ ;
/*!50003 DROP PROCEDURE IF EXISTS `catalog_getTags` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `catalog_getTags`(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 `catalog_getTagValues` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `catalog_getTagValues`(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 `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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemGetAvailable`()
BEGIN
/**
 * Gets the available items list.
 *
 * @table tmp.itemAvailable
 */  
	DECLARE vDelivery DATE;
	DECLARE vAddress INT;
	DECLARE vAgency INT;
    
    SELECT sent, addressFk, agencyModeFk
    INTO vDelivery, vAddress, vAgency
		FROM myBasket;
  
	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 `itemGetAvailableOrder` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemGetAvailableOrder`(vOrder INT)
BEGIN
/**
 * Gets the available items list with an order params.
 *
 * @table tmp.itemAvailable
 */  
	DECLARE vDelivery DATE;
	DECLARE vAddress INT;
	DECLARE vAgency INT;
    
    SELECT landed, addressFk, agencyModeFk
    INTO vDelivery, vAddress, vAgency
		FROM myOrder
		WHERE id = vOrder;
  
	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_getList` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `item_getList`(IN `vWarehouse` SMALLINT, IN `vShipping` DATE, IN `vCategory` INT, IN `vRate` TINYINT)
BEGIN
	DECLARE vCalc INT;

	CALL cache.available_refresh(vCalc, FALSE, vWarehouse, vShipping);
	CALL vn2008.item_last_buy_(vWarehouse, vShipping);

	SELECT a.id, a.`name`, a.category, a.size, a.stems, a.inkFk, a.typeFk, a.image,
			c.available, o.`name` origin, t.`name` `type`,
			CASE b.groupingMode
				WHEN 0 THEN 1
				WHEN 2 THEN b.packing
				ELSE b.`grouping`
			END AS `grouping`,
			CASE vRate
				WHEN 1 THEN b.price1
				WHEN 2 THEN b.price2
				WHEN 3 THEN b.price3
				ELSE NULL
			END AS price
		FROM cache.available c
			JOIN vn.item a ON a.id = c.item_id
			JOIN vn.itemType t ON t.id = a.typeFk
			JOIN vn.itemCategory r ON r.id = t.categoryFk
			LEFT JOIN vn.origin o ON o.id = a.originFk
			JOIN vn2008.t_item_last_buy l ON l.item_id = a.id
			JOIN vn.buy b ON b.id = l.buy_id
		WHERE c.calc_id = vCalc
			AND c.available > 0
			AND a.id != 90
			AND r.display
			AND (vCategory IS NULL OR vCategory = r.id)
		ORDER BY a.typeFk, a.`name`, a.size;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_getVisible` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `item_getVisible`(IN `vWh` TINYINT, IN `vDate` DATE, IN `vType` INT, IN `vPrefix` VARCHAR(255))
BEGIN
/**
 * Gets visible items of the specified type at specified date.
 *
 * @param vWh The warehouse id
 * @param vDate The visible date
 * @param vType The type id
 * @param vPrefix The article prefix to filter or %NULL for all
 * @return tmp.itemVisible Visible items
 */
	DECLARE vPrefixLen SMALLINT;
	DECLARE vFilter VARCHAR(255) DEFAULT NULL;
	DECLARE vDateInv DATE DEFAULT vn2008.date_inv();

	SET vPrefixLen = IFNULL(LENGTH(vPrefix), 0) + 1;

	IF vPrefixLen > 1 THEN
		SET vFilter = CONCAT(vPrefix, '%');
	END IF;

	DROP TEMPORARY TABLE IF EXISTS filter;
	CREATE TEMPORARY TABLE filter
		(INDEX (itemFk))
		ENGINE = MEMORY
		SELECT id itemFk FROM vn.item
			WHERE typeFk = vType
				AND (vFilter IS NULL OR `name` LIKE vFilter);

	DROP TEMPORARY TABLE IF EXISTS currentStock;
	CREATE TEMPORARY TABLE currentStock
		(INDEX (itemFk))
		ENGINE = MEMORY
		SELECT itemFk, SUM(quantity) quantity
			FROM (
				SELECT b.itemFk, b.quantity
					FROM vn.buy b
						JOIN vn.entry e ON e.id = b.entryFk
						JOIN vn.travel t ON t.id = e.travelFk
					WHERE t.landed BETWEEN vDateInv AND vDate
						AND t.warehouseInFk = vWh
						AND NOT e.isRaid
				UNION ALL
				SELECT b.itemFk, -b.quantity
					FROM vn.buy b
						JOIN vn.entry e ON e.id = b.entryFk
						JOIN vn.travel t ON t.id = e.travelFk
					WHERE t.shipped BETWEEN vDateInv AND CURDATE()
						AND t.warehouseOutFk = vWh
						AND NOT e.isRaid
						AND t.isDelivered
				UNION ALL
				SELECT m.itemFk, -m.quantity
					FROM vn.sale m
						JOIN vn.ticket t ON t.id = m.ticketFk
						JOIN vn.ticketState s ON s.ticket = t.id
					WHERE t.shipped BETWEEN vDateInv AND CURDATE()
						AND t.warehouseFk = vWh
						AND s.alertLevel = 3
			) t
			GROUP BY itemFk
				HAVING quantity > 0;

	DROP TEMPORARY TABLE IF EXISTS tmp;
	CREATE TEMPORARY TABLE tmp
		(INDEX (itemFk))
		ENGINE = MEMORY
		SELECT *
			FROM (
				SELECT b.itemFk, b.packageFk, b.packing
					FROM vn.buy b
						JOIN vn.entry e ON e.id = b.entryFk
						JOIN vn.travel t ON t.id = e.travelFk
					WHERE t.landed BETWEEN vDateInv AND vDate
						AND NOT b.isIgnored
						AND b.price2 >= 0
						AND b.packageFk IS NOT NULL
					ORDER BY t.warehouseInFk = 1 DESC, t.landed DESC
			) t GROUP BY itemFk;

	DROP TEMPORARY TABLE IF EXISTS tmp.itemVisible;
	CREATE TEMPORARY TABLE tmp.itemVisible
		ENGINE = MEMORY
		SELECT i.id Id_Article,
				SUBSTRING(i.`name`, vPrefixLen) Article,
				t.packing, p.id Id_Cubo,
				IF(p.depth > 0, p.depth, 0) z, p.width x, p.height y,
				CEIL(s.quantity / t.packing) etiquetas
			FROM vn.item i
				JOIN filter f ON f.itemFk = i.id 
				JOIN currentStock s ON s.itemFk = i.id
				LEFT JOIN tmp t ON t.itemFk = i.id
				LEFT JOIN vn.packaging p ON p.id = t.packageFk
			WHERE CEIL(s.quantity / t.packing) > 0
				-- FIXME: Column Cubos.box not included in view vn.packaging
				/* AND p.box */;

	DROP TEMPORARY TABLE
		filter,
		currentStock,
		tmp;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_listAllocation` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `item_listAllocation`(IN `vWh` TINYINT, IN `vDate` DATE, IN `vType` INT, IN `vPrefix` VARCHAR(255), IN `vUseIds` BOOLEAN)
BEGIN
/**
 * Lists visible items and it's box sizes of the specified
 * type at specified date.
 *
 * @param vWh The warehouse id
 * @param vDate The visible date
 * @param vType The type id
 * @param vPrefix The article prefix to filter or %NULL for all
 * @param vUseIds Whether to order the result by item id
 * @select List of visible items with it's box sizes
 */
	CALL item_getVisible(vWh, vDate, vType, vPrefix);

	IF vUseIds
	THEN
		SELECT * FROM tmp.itemVisible
			ORDER BY Id_Article;
	ELSE
		SELECT * FROM tmp.itemVisible
			ORDER BY Article, packing;
	END IF;

	DROP TEMPORARY TABLE tmp.itemVisible;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myBasket_addItem` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myBasket_addItem`(
	vWarehouse INT,
    vItem INT,
    vAmount INT)
BEGIN
	CALL order_addItem(myBasket_getId(), vWarehouse, vItem, vAmount);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myBasket_check` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myBasket_check`()
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 vSelf 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, made
		INTO vSelf, vCreated
		FROM myBasket;

	IF vStatus = 'OK'
	THEN
		CALL orderCheckConfig(vSelf);
		
		IF vStatus = 'OK' AND vCreated < TIMESTAMPADD(DAY, -1, NOW())
		THEN
			CALL order_update(vSelf);
			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 `myBasket_configure` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myBasket_configure`(
	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 vSelf INT;
    DECLARE vCompany INT;
	DECLARE vDeliveryMethodId INT;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vSelf = 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 vSelf = myBasket_getId();

	IF vSelf 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 vSelf = LAST_INSERT_ID();
        
        INSERT INTO basketOrder SET
			clientFk = account.userGetId(),
            orderFk = vSelf;
	ELSE
		UPDATE `order`
			SET
				date_send = vDelivery,
				delivery_method_id = vDeliveryMethodId,
				agency_id = vAgency,
				address_id = vAddress
			WHERE
				id = vSelf;
                
		CALL order_update(vSelf);
	END IF;

	CALL orderCheckConfig(vSelf);

	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 `myBasket_configureForGuest` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myBasket_configureForGuest`()
BEGIN
    DECLARE vMethod VARCHAR(45);
    DECLARE vAgency INT;
    
    SELECT guestMethod, guestAgencyFk
		INTO vMethod, vAgency
        FROM orderConfig
        LIMIT 1;
    
    CALL myBasket_configure(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 `myBasket_confirm` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myBasket_confirm`()
BEGIN
	DECLARE vSelf INT DEFAULT myBasket_getId();

	IF vSelf IS NOT NULL THEN
		CALL order_confirm(vSelf);
		
		DELETE FROM basketOrder
			WHERE orderFk = vSelf;
	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 `myBasket_getTax` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myBasket_getTax`()
    READS SQL DATA
BEGIN
/**
 * Returns the taxes for the current client basket.
 *
 * @treturn tmp.orderTax
 */
	DROP TEMPORARY TABLE IF EXISTS tmp.order;
	CREATE TEMPORARY TABLE tmp.`order`
		ENGINE = MEMORY
		SELECT myBasket_getId() orderFk;
        
	CALL orderGetTax();
    
    DROP TEMPORARY TABLE IF EXISTS tmp.`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 `myItemGetAvailable` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myItemGetAvailable`(vDelivery DATE, vAddress INT)
BEGIN
/**
 * Gets the available items list.
 *
 * @vDelivery Delivery date
 * @vAddress Id Address
 */  
    DECLARE vAgencyMode INT;
    
	SELECT a.agencyModeFk
			INTO vAgencyMode
		FROM myClient c
			JOIN vn.address a ON a.clientFk = c.id
		WHERE a.id = vAddress;      

	CALL vn2008.bionic_available_ (vDelivery, vAddress, vAgencyMode);

	DROP TEMPORARY TABLE IF EXISTS tmp.item;
	CREATE TEMPORARY TABLE tmp.item
		(INDEX (itemFk))
        ENGINE = MEMORY
		SELECT c.item_id itemFk
			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;
 
	CALL vn.ticketCalculate(vDelivery, vAddress, vAgencyMode);
-- -------------------
	/*SELECT b.itemFk, b.item, b.available, b.price
		FROM tmp.ticketCalculateItem b
			JOIN vn.item i ON i.id = b.itemFk
		WHERE b.available > 0
		ORDER BY i.relevancy DESC, i.name, i.size;
        
    select * from tmp.ticketComponentPrice;*/
-- -------------------
	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 `myItemGetAvailableFromDate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myItemGetAvailableFromDate`(vDelivery DATE)
BEGIN
/**
 * Gets the available items list.
 *
 * @vDelivery Delivery date
 */  
	DECLARE vAddress INT;
	DECLARE vAgencyMode INT;
        
	SELECT a.agencyModeFk, a.id 
			INTO vAgencyMode, vAddress
		FROM myClient c
			JOIN vn.address a ON a.id = c.defaultAddressFk;    
  
	CALL vn2008.bionic_available_ (vDelivery, vAddress, vAgencyMode);

	DROP TEMPORARY TABLE IF EXISTS tmp.item;
	CREATE TEMPORARY TABLE tmp.item
		(INDEX (itemFk))
        ENGINE = MEMORY
		SELECT c.item_id itemFk
			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;
 
	CALL vn.ticketCalculate(vDelivery, vAddress, vAgencyMode);
-- -------------------
	/*SELECT b.itemFk, b.item, b.available, b.price
		FROM tmp.ticketCalculateItem b
			JOIN vn.item i ON i.id = b.itemFk
		WHERE b.available > 0
		ORDER BY i.relevancy DESC, i.name, i.size;
        
    select * from tmp.ticketComponentPrice;*/
-- -------------------
	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 `myOrderAddItem` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myOrderAddItem`(
	vSelf INT,
    vWarehouse INT,
    vItem INT,
    vAmount INT)
BEGIN
	DECLARE isMine BOOL;

	SELECT COUNT(*) INTO isMine
		FROM myOrder
		WHERE id = vSelf;
		
	IF isMine THEN
		CALL order_addItem(vSelf, vWarehouse, vItem, vAmount);
	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 `myOrderConfirm` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myOrderConfirm`(vSelf INT)
BEGIN
	DECLARE isMine BOOL;
    
    SELECT COUNT(*) INTO isMine 
		FROM myOrder
        WHERE id = vSelf;
        
	IF isMine THEN
		CALL order_confirm(vSelf);
	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 `myOrderNewFromDate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myOrderNewFromDate`(
	OUT vOrder INT,
    vLandingDate DATE)
BEGIN
/**
 * Crea una nueva Order a partir de una fecha de llegada
 *
 * @param vOrder Id de la nueva orden
 * @param vLandingDate Fecha de entrega
 */
    DECLARE vCompany INT;
	DECLARE vDeliveryMethodId INT;
    DECLARE vAgencyMode INT;
    DECLARE vAddress INT;

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

	START TRANSACTION;

	SELECT a.agencyModeFk, a.id 
				INTO vAgencyMode, vAddress
			FROM myClient c
				JOIN vn.address a ON a.id = c.defaultAddressFk;
                
	SELECT deliveryMethodFk INTO vDeliveryMethodId
		FROM vn.agencyMode am
		WHERE am.id = vAgencyMode;
            
	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 = vLandingDate,
			delivery_method_id = vDeliveryMethodId,
			agency_id = vAgencyMode,
			address_id = vAddress,
			source_app = 'WEB',
			company_id = vCompany;

	SET vOrder = LAST_INSERT_ID();
     
	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 `myTicket_get` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myTicket_get`(vSelf INT)
BEGIN
/**
 * Returns a current user ticket header.
 *
 * @param vSelf 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 = vSelf;

	CALL vn.ticketGetTax;

	SELECT IFNULL(SUM(taxableBase), 0.0), IFNULL(SUM(tax), 0.0)
		INTO vTaxBase, vTax
		FROM tmp.ticketAmount;

	SELECT t.id, t.landed, t.shipped, t.refFk, ag.description agency, m.code method,
			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.deliveryMethod m ON m.id = ag.deliveryMethodFk
			LEFT JOIN vn.province p ON p.id = a.provinceFk
		WHERE t.id = vSelf;

	DROP TEMPORARY TABLE
		tmp.ticket,
		tmp.ticketTax,
		tmp.ticketAmount;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myTicket_getPackages` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myTicket_getPackages`(vSelf INT)
BEGIN
/**
 * Returns a current user ticket packages.
 *
 * @param vSelf 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.packaging p ON p.id = tp.packagingFk
			JOIN vn.item i ON i.id = p.itemFk
		WHERE t.id = vSelf;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myTicket_getRows` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myTicket_getRows`(vSelf INT)
BEGIN
	SELECT r.itemFk, r.quantity, r.concept, r.price, r.discount,
			i.image, i.category, i.size, i.stems, i.inkFk,
			i.tag5, i.value5, i.tag6, i.value6, i.tag7, i.value7
		FROM myTicketRow r
			JOIN vn.item i ON i.id = r.itemFk
		WHERE r.ticketFk = vSelf
		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 `myTicket_list` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myTicket_list`(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 = v.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 `myTicket_logAccess` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myTicket_logAccess`(vSelf INT)
BEGIN
/**
 * Logs an access to a ticket.
 *
 * @param vSelf The ticket identifier
 */
	INSERT INTO vn.ticketLog
		(originFk, userFk, `action`, description)
		SELECT vSelf, account.userGetId(), 'select', 'Accede a ticket'
			FROM myTicket t
			WHERE t.id = vSelf;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myTpvTransaction_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myTpvTransaction_end`(vSelf 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 vSelf 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 = vSelf 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 `myTpvTransaction_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myTpvTransaction_start`(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 vSelf 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 vSelf = LAST_INSERT_ID();

	SELECT
		 vAmount amount
		,vSelf 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 `orderAddItem` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `orderAddItem`(
	vSelf INT,
    vWarehouse INT,
    vItem INT,
    vAmount INT)
BEGIN
/**
 * @deprecated Use order_addItem();
 */ 
	CALL order_addItem(vSelf, vWarehouse, vItem, vAmount);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 `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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `orderConfirm`(vSelf INT)
BEGIN
/**
 * @deprecated Use order_confirm();
 */
	CALL order_confirm(vSelf);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `orderConfirmWithUser` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `orderConfirmWithUser`(vSelf INT, vUserId INT)
BEGIN
/**
 * @deprecated Use order_confirmWithUser()
 */
	CALL order_confirmWithUser(vSelf, 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 `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              = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `orderGetTax`()
    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
 */
    DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany;
    CREATE TEMPORARY TABLE tmp.addressCompany
        (INDEX (addressFk, companyFk))
        ENGINE = MEMORY 
        SELECT DISTINCT o.address_id addressFk, o.company_id companyFk
            FROM tmp.order tmpOrder
                JOIN hedera.order o ON o.id = tmpOrder.orderFk;

    CALL vn.addressTaxArea ();

	-- Calcula el IVA y el recargo desglosado.
	DROP TEMPORARY TABLE IF EXISTS tmp.orderTax;
	CREATE TEMPORARY TABLE tmp.orderTax
		(INDEX (orderFk))
		ENGINE = MEMORY
				SELECT o.id orderFk,
						tc.code,
						SUM(m.amount * m.price) taxableBase,
                        pgc.rate
                    FROM tmp.order tmpOrder
                    JOIN `order` o ON o.id = tmpOrder.orderFk
						JOIN orderRow m ON m.orderFk = o.id
						JOIN vn.item i ON i.id = m.itemFk
						JOIN vn.client c ON c.id = o.customer_id
						JOIN vn.supplier s ON s.id = o.company_id
						JOIN tmp.addressTaxArea ata
                    ON ata.addressFk = o.address_id AND ata.companyFk = o.company_id
                JOIN vn.itemTaxCountry itc
                    ON itc.itemFk = i.id AND itc.countryFk = s.countryFk
                JOIN vn.bookingPlanner bp
                    ON bp.countryFk = s.countryFk
                        AND bp.taxAreaFk = ata.areaFk
                        AND bp.taxClassFk = itc.taxClassFk
                JOIN vn.pgc ON pgc.code = bp.pgcFk
                JOIN vn.taxClass tc ON tc.id = bp.taxClassFk
            GROUP BY tmpOrder.orderFk, pgc.code,pgc.rate
            HAVING taxableBase != 0;
                    
    DROP TEMPORARY TABLE IF EXISTS tmp.orderAmount;
    CREATE TEMPORARY TABLE tmp.orderAmount
        (INDEX (orderFk))
        ENGINE = MEMORY
        SELECT orderFk, taxableBase, SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax,code
            FROM tmp.orderTax
            GROUP BY orderFk, code;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE 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`@`%` PROCEDURE `orderGetTotal`()
BEGIN
/**
* Calcula el total con IVA para un conjunto de orders.
*
* @table tmp.order(orderFk) Identificadores de las ordenes a calcular
* @return tmp.orderTotal Total para cada order
*/
	CALL orderGetTax;

	DROP TEMPORARY TABLE IF EXISTS tmp.orderTotal;
	CREATE TEMPORARY TABLE tmp.orderTotal
		(INDEX (orderFk))
		ENGINE = MEMORY
		SELECT o.orderFk, IFNULL(SUM(ot.taxableBase + ot.tax), 0.0) AS total
			FROM tmp.order o
				LEFT JOIN tmp.orderAmount ot ON o.orderFk = ot.orderFk
				GROUP BY orderFk;

	DROP TEMPORARY TABLE IF EXISTS 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 `order_addItem` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `order_addItem`(
	vSelf INT,
    vWarehouse INT,
    vItem INT,
    vAmount INT)
BEGIN
	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 vDate DATE;
	DECLARE vAddress INT;
	DECLARE vAgencyMode INT;
	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;

	SELECT date_send, address_id, agency_id
		INTO vDate, vAddress, vAgencyMode
		FROM `order`
		WHERE id = vSelf;

	CALL vn2008.bionic_from_item(vDate, vAddress, vAgencyMode, vItem);

	START TRANSACTION;

	SELECT shipped INTO vShipment
		FROM tmp.travel_tree
		WHERE warehouseFk = vWarehouse;

	SELECT available INTO vAvailable
		FROM tmp.bionic_lot
		WHERE warehouse_id = vWarehouse
			AND item_id = vItem;

	IF vAmount > IFNULL(vAvailable, 0)
	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 = vSelf,
			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;

	IF vAmount > 0
	THEN
		CALL util.throw ('AMOUNT_NOT_MATCH_GROUPING');
	END IF;
				
	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 `order_confirm` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `order_confirm`(vSelf INT)
BEGIN
/**
 * Confirms an order, creating each of its tickets on
 * the corresponding date and store.
 *
 * @param vSelf The order identifier
 */
	CALL order_confirmWithUser(vSelf, account.userGetId());
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_confirmWithUser` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `order_confirmWithUser`(IN `vOrder` INT, IN `vUserId` INT)
BEGIN
/**
 * Confirms an order, creating each of its tickets on the corresponding
 * date, store and user.
 *
 * @param vOrder The order identifier
 * @param vUser The user 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 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 ah.shipped, r.warehouse_id
			FROM `order` o
				JOIN order_row r ON r.order_id = o.id
				LEFT JOIN tmp.agencyHourGetShipped ah
					ON ah.warehouseFk = 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 vn.agencyHourGetShipped (vDelivery, vAddress, vAgency);

	-- Trabajador que realiza la acción

	IF vUserId IS NULL THEN
		SELECT employeeFk INTO vUserId 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

		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.ticketCreateWithUser(
				vClientId,
				IFNULL(vShipment, CURDATE()),
				vWarehouse,
				vCompanyId,
				vAddress,
				vAgencyModeId,
				NULL,
				vDelivery,
				vUserId,
				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 SET
					Id_Ticket = vTicket,
					observation_type_id = 4 /* salesperson */,
					`text` = 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 coste

		DROP TEMPORARY TABLE IF EXISTS tComponents;
		CREATE TEMPORARY TABLE tComponents
			(INDEX (saleFk))
			ENGINE = MEMORY
			SELECT SUM(mc.Valor) valueSum, mc.Id_Movimiento saleFk
				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;

		UPDATE vn2008.Movimientos m
			JOIN tComponents mc ON mc.saleFk = m.Id_Movimiento
			SET m.CostFixat = valueSum;

		DROP TEMPORARY TABLE tComponents;
	END LOOP;

	CLOSE cDates;

	DELETE FROM basketOrder WHERE orderFk = 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 `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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `order_confirm_bionic`(vSelf INT)
BEGIN
/**
 * @deprecated Use order_confirm()
 */
	CALL order_confirm(vSelf);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `order_update`(vSelf INT)
proc: BEGIN
/**
 * Actualiza la líneas de un pedido.
 *
 * @param vSelf 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 = vSelf;

	IF vNRows > 0
	THEN
		SELECT date_send, address_id, agency_id
			INTO vDate, vAddress, vAgency
			FROM `order`
			WHERE id = vSelf;

		CALL vn2008.bionic_from_order (vDate, vAddress, vAgency, vSelf);

		DELETE c
			FROM order_row r
				JOIN order_component c ON c.order_row_id = r.id
				WHERE r.order_id = vSelf;
				
		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.warehouseFk = 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.shipped
			WHERE r.order_id = vSelf;

		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 = vSelf;
	END IF;

	UPDATE `order` SET date_make = NOW()
		WHERE id = vSelf;

	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 `survey_vote` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `survey_vote`(vAnswer INT)
BEGIN
	DECLARE vSurvey INT;
	DECLARE vCount TINYINT;
	DECLARE EXIT HANDLER FOR 1062
		CALL util.throw('You cannot vote twice to the same survey');

	SELECT durveyFk INTO vSurvey
		FROM surveyAnswer WHERE id = vAnswer;

	INSERT INTO surveyVote SET
		surveyFk = vSurvey,
        userFk = account.userGetId();

	UPDATE surveyAnswer 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 `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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `tpvTransactionConfirmById`(vSelf INT)
BEGIN
/**
 * @deprecated Use tpvTransaction_confirmById()
 */
	CALL tpvTransaction_confirmById(vSelf);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `tpvTransactionUndo`(vSelf INT)
BEGIN
/**
 * @deprecated Use tpvTransaction_undo()
 */
	CALL tpvTransaction_undo(vSelf);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `tpvTransaction_confirm` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `tpvTransaction_confirm`(
	 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 `tpvTransaction_confirmAll` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `tpvTransaction_confirmAll`(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 tpvTransaction_confirmById (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 `tpvTransaction_confirmById` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `tpvTransaction_confirmById`(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 tpvTransaction_confirm(
		 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 `tpvTransaction_undo` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `tpvTransaction_undo`(vSelf 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 = vSelf
		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 = vSelf;

	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 `visitUser_new` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `visitUser_new`(
	 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 `visit_register` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `visit_register`(
	 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 `__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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `__bionic_from_basket`()
BEGIN
	DECLARE vOrder INT;
	DECLARE vDate DATE;
	DECLARE vAddress INT;
	DECLARE vAgencyMode INT;
    
    SELECT id, sent, addressFk, agencyModeFk
		INTO vOrder, vDate, vAddress, vAgencyMode
		FROM myBasket;
        
	CALL vn2008.bionic_from_order(vDate, vAddress, vAgencyMode, 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 `__catalog_getAvailable` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `__catalog_getAvailable`()
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 `__catalog_getItems` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `__catalog_getItems`()
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 `__myTicketSetDelivered` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `__myTicketSetDelivered`(vTicketFk INT)
BEGIN
	
	UPDATE `vn2008`.`agency_hour` SET `subtract_day` = '0' WHERE (`agency_hour_id` = '1061');
	UPDATE `vn2008`.`agency_hour` SET `subtract_day` = '0' WHERE (`agency_hour_id` = '1121');
	UPDATE `vn2008`.`agency_hour` SET `subtract_day` = '0' WHERE (`agency_hour_id` = '1134');
	UPDATE `vn2008`.`agency_hour` SET `subtract_day` = '0' WHERE (`agency_hour_id` = '1148');
	UPDATE `vn2008`.`agency_hour` SET `subtract_day` = '0' WHERE (`agency_hour_id` = '1920');
    
    IF vTicketFk is null THEN
		call util.throw ('AGENCIA ACTUALIZADA');
	END IF;
    
	INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador)
		SELECT s.id, vTicketFk, vn.getWorker()
			FROM vn.state s
				JOIN myTicket m ON m.id = vTicketFk
			WHERE `code` = 'DELIVERED' AND m.id = vTicketFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `__orderDelete` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `__orderDelete`(vSelf INT)
BEGIN
	DELETE FROM `order` where id = vSelf;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `__orderUpdate`(vSelf INT)
BEGIN
/**
 * @deprecated Use order_update()
 */
	CALL order_update(vSelf);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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: `nst`
--

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

USE `nst`;

--
-- Table structure for table `balance`
--

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

--
-- Table structure for table `geo`
--

DROP TABLE IF EXISTS `geo`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `geo` (
  `id` int(11) NOT NULL,
  `lft` int(11) DEFAULT NULL,
  `rgt` int(11) DEFAULT NULL,
  `depth` int(11) DEFAULT NULL,
  `sons` int(11) DEFAULT NULL,
  `item` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `lft_UNIQUE` (`lft`),
  UNIQUE KEY `rgt_UNIQUE` (`rgt`),
  CONSTRAINT `nst_geo_id` FOREIGN KEY (`id`) REFERENCES `nst` (`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 `labourTree`
--

DROP TABLE IF EXISTS `labourTree`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `labourTree` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `lft` int(11) NOT NULL,
  `rgt` int(11) NOT NULL,
  `depth` int(11) NOT NULL DEFAULT '0',
  `sons` int(11) NOT NULL DEFAULT '0',
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=92 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `nst`
--

DROP TABLE IF EXISTS `nst`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `nst` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `lft` int(11) NOT NULL,
  `rgt` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `lft_UNIQUE` (`lft`),
  UNIQUE KEY `rgt_UNIQUE` (`rgt`)
) ENGINE=InnoDB AUTO_INCREMENT=6681 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping events for database 'nst'
--

--
-- Dumping routines for database 'nst'
--
/*!50003 DROP PROCEDURE IF EXISTS `nodeAdd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nodeAdd`(IN `vScheme` VARCHAR(45), IN `vTable` VARCHAR(45), IN `vParentFk` INT, IN `vChild` VARCHAR(100))
BEGIN
	DECLARE vSql TEXT;
	DECLARE vTableClone VARCHAR(45);

	SET vTableClone = CONCAT(vTable, 'Clone');
   
	CALL util.exec(CONCAT('DROP TEMPORARY TABLE IF EXISTS tmp.', vTableClone));
	CALL util.exec(CONCAT(
		'CREATE TEMPORARY TABLE tmp.', vTableClone,
		'	ENGINE = MEMORY',
		'	SELECT * FROM ', vScheme, '.', vTable
  	));
    
    CALL util.exec(CONCAT(
		'SELECT COUNT(c.id) INTO @childs',
		'	FROM ', vScheme, '.', vTable, ' p',
		'		LEFT JOIN tmp.', vTableClone, ' c ON c.lft',
		'			BETWEEN p.lft AND p.rgt AND c.id != ', vParentFk,
		'	WHERE p.id = ', vParentFk
  	));
    
    IF @childs = 0 THEN
		CALL util.exec(CONCAT(
			'SELECT lft INTO @vLeft',
			'	FROM ', vScheme, '.', vTable, 
            '   WHERE id = ', vParentFk
		));
    ELSE      
        CALL util.exec(CONCAT(
			'SELECT c.rgt INTO @vLeft',
			'	FROM ', vScheme, '.', vTable, ' p',
			'		JOIN tmp.', vTableClone, ' c ON c.lft BETWEEN p.lft AND p.rgt',
			'	WHERE p.id = ', vParentFk,
			'	ORDER BY c.lft',
			'	DESC LIMIT 1'
		));
    END IF;
    
    CALL util.exec(CONCAT(
		'UPDATE ', vScheme, '.', vTable, ' SET rgt = rgt + 2',
		'	WHERE rgt > @vLeft',
        '   ORDER BY rgt DESC'
	));
    CALL util.exec(CONCAT(
		'UPDATE ', vScheme, '.', vTable, ' SET lft = lft + 2',
		'	WHERE lft > @vLeft',
        '   ORDER BY lft DESC'
	));
    
    SET vChild = REPLACE(vChild, "'", "\\'");
    
    CALL util.exec(CONCAT(
		'INSERT INTO ', vScheme, '.', vTable, ' (name, lft, rgt)',
		'	VALUES ("', vChild, '", @vLeft + 1, @vLeft + 2)'
	));
    
    CALL util.exec(CONCAT(
		'SELECT id, name, lft, rgt, depth, sons',
		'	FROM ', vScheme, '.', vTable,
		'	WHERE id = LAST_INSERT_ID()'
	));
  
   CALL util.exec(CONCAT('DROP TEMPORARY TABLE tmp.', vTableClone));
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `nodeDelete` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nodeDelete`(IN `vScheme` VARCHAR(45), IN `vTable` VARCHAR(45), IN `vNodeId` INT)
BEGIN
	DECLARE vMyRight INT;
	DECLARE vMyLeft INT;
	DECLARE vMyWidth INT;

     	CALL util.exec(CONCAT(
			'SELECT t.rgt, t.lft,  t.rgt - t.lft + 1',
			'		INTO @vMyRight, @vMyLeft, @vMyWidth',
			'	FROM ', vScheme, '.', vTable, ' t',
			'	WHERE t.id = ', vNodeId
		));

		CALL util.exec(CONCAT(
			'DELETE FROM ', vScheme, '.', vTable, 
			'	WHERE lft BETWEEN @vMyLeft AND @vMyRight'
		));

		CALL util.exec(CONCAT(
			'UPDATE ', vScheme, '.', vTable, ' SET rgt = rgt - @vMyWidth'
			'	WHERE rgt > @vMyRight ORDER BY rgt'
		));

		CALL util.exec(CONCAT(
			'UPDATE ', vScheme, '.', vTable, ' SET lft = lft - @vMyWidth'
			'	WHERE lft > @vMyRight ORDER BY lft'
		));
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `nodeMove` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nodeMove`(IN `vScheme` VARCHAR(45), IN `vTable` VARCHAR(45), IN `vNodeId` INT, IN `vFatherId` INT)
BEGIN
	-- Averiguamos el ancho de la rama 
	CALL util.exec (sql_printf (
		'SELECT t.rgt - t.lft +1 INTO @vMyWidth FROM %t.%t t WHERE t.id = %v'
        ,vScheme
        ,vTable
		,vNodeId
	));

	-- Averiguamos la posicion del nuevo padre

	CALL util.exec (sql_printf (
		'SELECT  t.rgt,  t.lft INTO @vFatherRight , @vFatherLeft FROM %t.%t t WHERE t.id = %v'
        ,vScheme
		,vTable
		,vFatherId
	));

	-- 1º Incrementamos los valores de todos los nodos a la derecha del punto de inserción (vFatherRight) , para hacer sitio

	CALL util.exec (sql_printf (
		'UPDATE %t.%t SET rgt = rgt + @vMyWidth WHERE rgt >= @vFatherRight ORDER BY rgt DESC'
        ,vScheme
		,vTable
	));  

	CALL util.exec (sql_printf (
		'UPDATE %t.%t SET lft = lft + @vMyWidth WHERE lft >= @vFatherRight ORDER BY lft DESC'
		,vScheme
		,vTable
	));  

	-- Es preciso recalcular los valores del nodo en el caso de que estuviera a la derecha del nuevo padre

	CALL util.exec (sql_printf (
		'SELECT  t.rgt, t.lft, @vFatherRight - t.lft INTO @vMyRight, @vMyLeft, @vGap FROM %t.%t t WHERE t.id = %v'
		,vScheme
		,vTable
		,vNodeId
	));
	-- 2º Incrementamos el valor de todos los nodos a trasladar hasta alcanzar su nueva posicion

	CALL util.exec (sql_printf (
		'UPDATE %t.%t SET lft = lft + @vGap WHERE lft BETWEEN @vMyLeft AND @vMyRight ORDER BY lft DESC'
		,vScheme
		,vTable
	));       
	CALL util.exec (sql_printf (
		'UPDATE %t.%t SET rgt = rgt + @vGap WHERE rgt BETWEEN @vMyLeft AND @vMyRight ORDER BY rgt DESC'
		,vScheme
		,vTable
	));

	-- 3º Restaremos a todos los nodos resultantes, a la derecha de la posicion arrancada el ancho de la rama escindida

	CALL util.exec (sql_printf (
		'UPDATE %t.%t SET lft = lft - @vMyWidth WHERE lft > @vMyLeft ORDER BY lft'
		,vScheme
		,vTable
	));
	CALL util.exec (sql_printf (
		'UPDATE %t.%t SET rgt = rgt - @vMyWidth WHERE rgt > @vMyRight ORDER BY rgt'
		,vScheme
		,vTable
	));

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `nodeRecalc` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nodeRecalc`(IN `vScheme` VARCHAR(45), IN `vTable` VARCHAR(45))
BEGIN
	CALL util.exec(CONCAT (
		'UPDATE ', vScheme, '.', vTable, ' d',
		'	JOIN (SELECT',
		'			node.id,',
		'			COUNT(parent.id) - 1 as depth,',
		'			cast((node.rgt - node.lft - 1) / 2 as DECIMAL) as sons',
		'		FROM ',
		'			', vScheme, '.', vTable, ' AS node,',
		'			', vScheme, '.', vTable, ' AS parent',
		'		WHERE node.lft BETWEEN parent.lft AND parent.rgt',
		'		GROUP BY node.id',
		'		ORDER BY node.lft) n ON n.id = d.id ',
		'	SET d.`depth` = n.depth, d.sons = n.sons'
	));
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `nodeTree` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nodeTree`(IN `vScheme` VARCHAR(45), IN `vTable` VARCHAR(45), IN `vGap` INT, IN `vShouldShow` BOOLEAN)
BEGIN

	DROP TEMPORARY TABLE IF EXISTS tmp.nest;
	CALL util.exec (sql_printf (
		'CREATE TEMPORARY TABLE tmp.nest
			SELECT node.id
					,CONCAT( REPEAT(REPEAT(" ",%v), COUNT(parent.id) - 1), node.name) AS name
					,node.lft
					,node.rgt
					,COUNT(parent.id) - 1 as 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'
        ,vGap
        ,vScheme
		,vTable
        ,vScheme
		,vTable
	));

	IF vShouldShow THEN
		SELECT * FROM tmp.nest;
	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 `nodeTree_pako` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nodeTree_pako`(IN `vScheme` VARCHAR(45), IN `vTable` VARCHAR(45), IN `vGap` INT, IN `vShouldShow` BOOLEAN)
BEGIN

	DROP TEMPORARY TABLE IF EXISTS tmp.nest;
	CALL util.exec (sql_printf (
		'CREATE TEMPORARY TABLE tmp.nest
			SELECT node.id
					,CONCAT( REPEAT(REPEAT(" ",%v), COUNT(parent.id) - 1), node.name) AS name
					,node.lft
					,node.rgt
					,COUNT(parent.id) - 1 as depth
					,cast((node.rgt - node.lft - 1) / 2 as DECIMAL) as sons
                    ,node.isSelected
				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'
        ,vGap
        ,vScheme
		,vTable
        ,vScheme
		,vTable
	));

	IF vShouldShow THEN
		SELECT * FROM tmp.nest;
	END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;

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

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

USE `pbx`;

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

DROP TABLE IF EXISTS `blacklist`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `blacklist` (
  `phone` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`phone`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Hangup input calls from this list';
/*!40101 SET character_set_client = @saved_cs_client */;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`blacklistBeforeInsert`
BEFORE INSERT ON `blacklist` FOR EACH ROW
BEGIN
	CALL phoneIsValid (NEW.phone);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`blacklistBerforeUpdate`
BEFORE UPDATE ON `blacklist` FOR EACH ROW
BEGIN
	CALL phoneIsValid (NEW.phone);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;

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

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

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

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

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

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

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

DROP TABLE IF EXISTS `followme`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `followme` (
  `extension` varchar(128) CHARACTER SET utf8 NOT NULL,
  `phone` varchar(20) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`extension`),
  CONSTRAINT `followme_ibfk_1` FOREIGN KEY (`extension`) REFERENCES `sip` (`extension`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`followmeBeforeInsert`
BEFORE INSERT ON `followme` FOR EACH ROW
BEGIN
	CALL pbx.phoneIsValid (NEW.phone);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`followmeBeforeUpdate`
BEFORE UPDATE ON `followme` FOR EACH ROW
BEGIN
	CALL pbx.phoneIsValid (NEW.phone);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

DROP TABLE IF EXISTS `queueMemberConf`;
/*!50001 DROP VIEW IF EXISTS `queueMemberConf`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `queueMemberConf` AS SELECT 
 1 AS `uniqueid`,
 1 AS `queue_name`,
 1 AS `interface`,
 1 AS `paused`*/;
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,
  `queue` varchar(128) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`),
  KEY `queue` (`queue`),
  CONSTRAINT `schedule_ibfk_1` FOREIGN KEY (`queue`) REFERENCES `queue` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

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

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

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

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

DROP TABLE IF EXISTS `sipConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sipConfig` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `host` varchar(40) CHARACTER SET utf8 DEFAULT NULL,
  `deny` varchar(95) CHARACTER SET utf8 NOT NULL,
  `permit` varchar(95) CHARACTER SET utf8 NOT NULL,
  `type` enum('user','peer','friend') CHARACTER SET utf8 NOT NULL,
  `context` varchar(80) CHARACTER SET utf8 NOT NULL,
  `incomingLimit` varchar(10) CHARACTER SET utf8 NOT NULL,
  `pickupGroup` varchar(10) CHARACTER SET utf8 NOT NULL,
  `careInvite` varchar(10) CHARACTER SET utf8 NOT NULL,
  `insecure` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `transport` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `avpf` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `icesupport` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `encryption` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `dtlsenable` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `dtlverify` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `dtlscertfile` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `dtlsprivatekey` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `dtlssetup` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 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(45) CHARACTER SET utf8 DEFAULT NULL,
  `regSeconds` bigint(20) 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: `postgresql`
--

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

USE `postgresql`;

--
-- Table structure for table `address`
--

DROP TABLE IF EXISTS `address`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `address` (
  `address_id` int(11) NOT NULL AUTO_INCREMENT,
  `town_id` int(11) NOT NULL,
  `address_type_id` int(11) NOT NULL,
  `name` varchar(40) DEFAULT NULL,
  `address1` varchar(255) DEFAULT NULL,
  `number` int(11) DEFAULT NULL,
  `address2` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`address_id`),
  KEY `address_address_type_id_idx` (`address_type_id`),
  KEY `address_town_id_idx` (`town_id`),
  CONSTRAINT `address_ibfk_1` FOREIGN KEY (`address_type_id`) REFERENCES `address_type` (`address_type_id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `address_ibfk_2` FOREIGN KEY (`town_id`) REFERENCES `town` (`town_id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=803 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `address_type`
--

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

--
-- Table structure for table `bank_account`
--

DROP TABLE IF EXISTS `bank_account`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bank_account` (
  `bank_account_id` int(11) NOT NULL AUTO_INCREMENT,
  `client_id` int(11) DEFAULT NULL,
  `account` char(50) DEFAULT NULL,
  `bic` char(20) DEFAULT NULL,
  `bank_account_type_id` int(11) DEFAULT NULL,
  `nation_id` int(11) DEFAULT NULL,
  `sortcode` char(50) DEFAULT NULL,
  `bank_name` char(30) DEFAULT NULL,
  `bank_adress` char(125) DEFAULT NULL,
  `bank_city` char(50) DEFAULT NULL,
  `bank_account_link_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`bank_account_id`),
  KEY `fki_bank_account_client_pk` (`client_id`),
  KEY `fki_bank_profile` (`client_id`),
  KEY `fki_business_account_fk` (`client_id`),
  KEY `fki_person_account_fk` (`client_id`),
  KEY `bank_account_bank_account_type_id_fkey` (`bank_account_type_id`),
  KEY `bank_account_nation_id_fkey` (`nation_id`),
  CONSTRAINT `bank_account_bank_account_type_id_fkey` FOREIGN KEY (`bank_account_type_id`) REFERENCES `bank_account_type` (`bank_account_type_id`) ON UPDATE CASCADE,
  CONSTRAINT `bank_account_nation_id_fkey` FOREIGN KEY (`nation_id`) REFERENCES `nation` (`nation_id`) ON UPDATE CASCADE,
  CONSTRAINT `bank_profile` FOREIGN KEY (`client_id`) REFERENCES `profile` (`profile_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=799 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `bank_account_type`
--

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

--
-- Table structure for table `bank_bic`
--

DROP TABLE IF EXISTS `bank_bic`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bank_bic` (
  `nrbe` int(11) NOT NULL,
  `denominacion` varchar(255) DEFAULT NULL,
  `bic` char(11) DEFAULT NULL,
  `referenciaFTH` varchar(35) DEFAULT NULL,
  `referenciaVNL` varchar(35) DEFAULT NULL,
  PRIMARY KEY (`nrbe`),
  KEY `bankbic_ikey1` (`bic`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `business`
--

DROP TABLE IF EXISTS `business`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `business` (
  `business_id` int(11) NOT NULL AUTO_INCREMENT,
  `client_id` int(11) DEFAULT NULL,
  `provider_id` int(11) DEFAULT NULL,
  `date_start` date DEFAULT NULL,
  `date_end` date DEFAULT NULL,
  `workerBusiness` longtext,
  `reasonEndFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`business_id`),
  KEY `business_client` (`client_id`),
  KEY `bussiness_provider` (`provider_id`),
  CONSTRAINT `business_client` FOREIGN KEY (`client_id`) REFERENCES `profile` (`profile_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `bussiness_provider` FOREIGN KEY (`provider_id`) REFERENCES `profile` (`profile_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2481 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `business_labour`
--

DROP TABLE IF EXISTS `business_labour`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `business_labour` (
  `business_id` int(11) NOT NULL,
  `notes` longtext,
  `department_id` int(11) DEFAULT '2',
  `professional_category_id` int(11) DEFAULT '0',
  `incentivo` double DEFAULT '0',
  `calendar_labour_type_id` int(11) DEFAULT '1',
  `porhoras` smallint(6) NOT NULL DEFAULT '0',
  `labour_agreement_id` int(11) DEFAULT NULL,
  `workcenter_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`business_id`),
  KEY `fki_business_labour_agreement` (`labour_agreement_id`),
  KEY `fki_workcenter_labour` (`workcenter_id`),
  KEY `horario_tipo` (`calendar_labour_type_id`),
  KEY `business_labour_department_idx` (`department_id`),
  CONSTRAINT `bus_restriction` FOREIGN KEY (`business_id`) REFERENCES `business` (`business_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `business_labour_agreement` FOREIGN KEY (`labour_agreement_id`) REFERENCES `labour_agreement` (`labour_agreement_id`) ON UPDATE CASCADE,
  CONSTRAINT `business_labour_department` FOREIGN KEY (`department_id`) REFERENCES `vn2008`.`department` (`department_id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `horario_tipo` FOREIGN KEY (`calendar_labour_type_id`) REFERENCES `calendar_labour_type` (`calendar_labour_type_id`) ON UPDATE CASCADE,
  CONSTRAINT `workcenter_labour` FOREIGN KEY (`workcenter_id`) REFERENCES `workcenter` (`workcenter_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `business_labour_payroll`
--

DROP TABLE IF EXISTS `business_labour_payroll`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `business_labour_payroll` (
  `business_id` int(11) NOT NULL,
  `cod_tarifa` int(11) DEFAULT NULL,
  `cod_categoria` int(11) DEFAULT NULL,
  `cod_contrato` int(11) DEFAULT NULL,
  `importepactado` decimal(10,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`business_id`),
  CONSTRAINT `business_labour_payroll_fk1` FOREIGN KEY (`business_id`) REFERENCES `business` (`business_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 `calendar_employee`
--

DROP TABLE IF EXISTS `calendar_employee`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `calendar_employee` (
  `business_id` int(11) NOT NULL,
  `calendar_state_id` int(11) NOT NULL,
  `date` date NOT NULL,
  PRIMARY KEY (`business_id`,`date`),
  KEY `calendar_employee_business_labour_id_idx` (`business_id`),
  KEY `calendar_employee_calendar_state_calendar_state_id_idx` (`calendar_state_id`),
  CONSTRAINT `calendar_employee_state_id` FOREIGN KEY (`calendar_state_id`) REFERENCES `calendar_state` (`calendar_state_id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `calendar_free`
--

DROP TABLE IF EXISTS `calendar_free`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `calendar_free` (
  `calendar_free_id` int(11) NOT NULL AUTO_INCREMENT,
  `type` varchar(20) NOT NULL,
  `rgb` varchar(7) DEFAULT NULL,
  PRIMARY KEY (`calendar_free_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `calendar_labour`
--

DROP TABLE IF EXISTS `calendar_labour`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `calendar_labour` (
  `calendar_free_id` int(11) NOT NULL,
  `person_id` int(11) NOT NULL,
  `day` date NOT NULL,
  `calendar_labour_legend_id` int(11) DEFAULT NULL,
  `workcenter_id` int(11) NOT NULL,
  `calendar_id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`calendar_id`),
  UNIQUE KEY `person_id_UNIQUE` (`person_id`,`day`,`workcenter_id`),
  KEY `calendar_labour_calendar_free_id_idx` (`calendar_free_id`),
  KEY `fki_calendar_labour_legend_id` (`calendar_labour_legend_id`),
  KEY `fki_calendar_labour_person_day` (`person_id`,`day`),
  KEY `fki_workcenter_calendar` (`workcenter_id`),
  CONSTRAINT `fk_calendar_labour_calendar_free1` FOREIGN KEY (`calendar_free_id`) REFERENCES `calendar_free` (`calendar_free_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_calendar_labour_legend_id` FOREIGN KEY (`calendar_labour_legend_id`) REFERENCES `calendar_labour_legend` (`calendar_labour_legend_id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `workcenter_calendar` FOREIGN KEY (`workcenter_id`) REFERENCES `workcenter` (`workcenter_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=534 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `calendar_labour_legend`
--

DROP TABLE IF EXISTS `calendar_labour_legend`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `calendar_labour_legend` (
  `calendar_labour_legend_id` int(11) NOT NULL AUTO_INCREMENT,
  `descripcion` longtext,
  PRIMARY KEY (`calendar_labour_legend_id`),
  UNIQUE KEY `calendar_labour_legend_calendar_labour_legend_id_key` (`calendar_labour_legend_id`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `calendar_labour_type`
--

DROP TABLE IF EXISTS `calendar_labour_type`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `calendar_labour_type` (
  `calendar_labour_type_id` int(11) NOT NULL AUTO_INCREMENT,
  `descripcion` varchar(50) DEFAULT NULL,
  `pausa_remunerada` time DEFAULT NULL,
  `hours_week` smallint(6) DEFAULT NULL,
  PRIMARY KEY (`calendar_labour_type_id`),
  UNIQUE KEY `hours_labour_hours_labour_id_key` (`calendar_labour_type_id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `calendar_state`
--

DROP TABLE IF EXISTS `calendar_state`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `calendar_state` (
  `calendar_state_id` int(11) NOT NULL AUTO_INCREMENT,
  `type` varchar(30) NOT NULL,
  `rgb` varchar(7) NOT NULL,
  `color` bigint(20) DEFAULT '0',
  PRIMARY KEY (`calendar_state_id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `currency`
--

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

--
-- Temporary table structure for view `currentWorkersStats`
--

DROP TABLE IF EXISTS `currentWorkersStats`;
/*!50001 DROP VIEW IF EXISTS `currentWorkersStats`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `currentWorkersStats` AS SELECT 
 1 AS `business_id`,
 1 AS `sex`,
 1 AS `name`,
 1 AS `firstname`,
 1 AS `department`,
 1 AS `category_name`,
 1 AS `level_name`,
 1 AS `salarioMedio`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `income_employee`
--

DROP TABLE IF EXISTS `income_employee`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `income_employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `debe` decimal(10,2) DEFAULT NULL,
  `haber` decimal(10,2) DEFAULT '0.00',
  `id_incomeType` int(11) DEFAULT NULL,
  `odbc_date` date DEFAULT NULL,
  `person_id` int(11) DEFAULT NULL,
  `concepto` longtext,
  PRIMARY KEY (`id`),
  KEY `fincometype_id` (`id_incomeType`),
  KEY `fperson_id` (`person_id`),
  CONSTRAINT `fincometype_id` FOREIGN KEY (`id_incomeType`) REFERENCES `incometype_employee` (`id_incometype`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fperson_id` FOREIGN KEY (`person_id`) REFERENCES `person` (`person_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=63753 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `incometype_employee`
--

DROP TABLE IF EXISTS `incometype_employee`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `incometype_employee` (
  `id_incometype` int(11) NOT NULL,
  `descripcion` varchar(255) DEFAULT NULL,
  `nomina` smallint(6) DEFAULT '0',
  PRIMARY KEY (`id_incometype`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `journey`
--

DROP TABLE IF EXISTS `journey`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `journey` (
  `journey_id` int(11) NOT NULL AUTO_INCREMENT,
  `day_id` smallint(6) NOT NULL DEFAULT '1' COMMENT 'Lunes = 1 \nDomingo = 7',
  `start` time DEFAULT NULL,
  `end` time DEFAULT NULL,
  `business_id` int(11) NOT NULL,
  PRIMARY KEY (`journey_id`),
  KEY `fki_business_journey` (`business_id`),
  CONSTRAINT `business_journey` FOREIGN KEY (`business_id`) REFERENCES `business_labour` (`business_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1505 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `labour_agreement`
--

DROP TABLE IF EXISTS `labour_agreement`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `labour_agreement` (
  `labour_agreement_id` int(11) NOT NULL AUTO_INCREMENT,
  `month_hollidays` double DEFAULT NULL,
  `year_hours` int(11) DEFAULT NULL,
  `name` char(50) DEFAULT NULL,
  `date_START` date DEFAULT NULL,
  `date_END` date DEFAULT NULL,
  PRIMARY KEY (`labour_agreement_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `media`
--

DROP TABLE IF EXISTS `media`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `media` (
  `media_id` int(11) NOT NULL AUTO_INCREMENT,
  `media_type_id` int(11) NOT NULL,
  `value` varchar(55) NOT NULL,
  `sort` int(11) DEFAULT NULL,
  PRIMARY KEY (`media_id`),
  KEY `media_media_type_id_idx` (`media_type_id`),
  CONSTRAINT `media_ibfk_1` FOREIGN KEY (`media_type_id`) REFERENCES `media_type` (`media_type_id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=998 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `media_type`
--

DROP TABLE IF EXISTS `media_type`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `media_type` (
  `media_type_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(15) NOT NULL,
  PRIMARY KEY (`media_type_id`),
  UNIQUE KEY `media_type_name_key` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `nation`
--

DROP TABLE IF EXISTS `nation`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `nation` (
  `nation_id` int(11) NOT NULL AUTO_INCREMENT,
  `currency_id` int(11) NOT NULL DEFAULT '1',
  `name` varchar(20) NOT NULL,
  `brief` char(3) NOT NULL,
  `flag` longblob,
  PRIMARY KEY (`nation_id`),
  UNIQUE KEY `nation_name_key` (`name`),
  KEY `nation_currency_id_idx` (`currency_id`),
  CONSTRAINT `nation_ibfk_1` FOREIGN KEY (`currency_id`) REFERENCES `currency` (`currency_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `periodos`
--

DROP TABLE IF EXISTS `periodos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `periodos` (
  `fecha` date NOT NULL,
  `periodo` int(11) DEFAULT NULL,
  PRIMARY KEY (`fecha`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!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` (
  `person_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(60) NOT NULL,
  `nickname` varchar(15) DEFAULT NULL,
  `nif` varchar(15) DEFAULT NULL,
  `birth` date DEFAULT NULL,
  `firstname` varchar(20) DEFAULT NULL,
  `p2` longtext,
  `nis` int(11) DEFAULT NULL,
  `id_trabajador` int(11) DEFAULT NULL,
  `isDisable` smallint(6) NOT NULL DEFAULT '0',
  `isFreelance` smallint(6) NOT NULL DEFAULT '0' COMMENT 'M Male\nF Female',
  `isSsDiscounted` smallint(6) NOT NULL DEFAULT '0',
  `sex` enum('M','F') NOT NULL DEFAULT 'F' COMMENT 'M Masculino  F Femenino',
  PRIMARY KEY (`person_id`),
  UNIQUE KEY `person_nis` (`person_id`),
  UNIQUE KEY `Index_unique_nif` (`nif`),
  UNIQUE KEY `person_nif_key` (`nif`),
  UNIQUE KEY `nis_UNIQUE` (`nis`),
  KEY `index1` (`person_id`,`name`,`nickname`,`firstname`),
  KEY `person_worker` (`id_trabajador`)
) ENGINE=InnoDB AUTO_INCREMENT=1033 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `professional_category`
--

DROP TABLE IF EXISTS `professional_category`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `professional_category` (
  `professional_category_id` int(11) NOT NULL AUTO_INCREMENT,
  `category_name` varchar(50) NOT NULL,
  `professional_levels_id` int(11) DEFAULT NULL,
  `fichajes` tinyint(4) NOT NULL DEFAULT '1',
  `holiday_days` decimal(3,1) DEFAULT NULL,
  PRIMARY KEY (`professional_category_id`),
  UNIQUE KEY `professional_category_name_category_key` (`category_name`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `professional_levels`
--

DROP TABLE IF EXISTS `professional_levels`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `professional_levels` (
  `professional_levels_id` int(11) NOT NULL AUTO_INCREMENT,
  `level_name` varchar(5) DEFAULT NULL,
  `price_overtime` double DEFAULT NULL,
  PRIMARY KEY (`professional_levels_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
/*!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` (
  `profile_id` int(11) NOT NULL AUTO_INCREMENT,
  `person_id` int(11) NOT NULL,
  `profile_type_id` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`profile_id`),
  KEY `profile_person_id_idx` (`person_id`),
  KEY `profile_profile_type_id_idx` (`profile_type_id`),
  CONSTRAINT `person_fk` FOREIGN KEY (`person_id`) REFERENCES `person` (`person_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=912 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `profile_address`
--

DROP TABLE IF EXISTS `profile_address`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `profile_address` (
  `profile_address_id` int(11) NOT NULL AUTO_INCREMENT,
  `profile_id` int(11) NOT NULL,
  `address_id` int(11) NOT NULL,
  PRIMARY KEY (`profile_address_id`),
  KEY `profile_address_address_id_idx` (`address_id`),
  KEY `profile_address_profile_id_idx` (`profile_id`)
) ENGINE=InnoDB AUTO_INCREMENT=140 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `profile_media`
--

DROP TABLE IF EXISTS `profile_media`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `profile_media` (
  `profile_media_id` int(11) NOT NULL AUTO_INCREMENT,
  `profile_id` int(11) NOT NULL,
  `media_id` int(11) NOT NULL,
  PRIMARY KEY (`profile_media_id`),
  KEY `profile_media_media_id_idx` (`media_id`),
  KEY `profile_media_profile_id_idx` (`profile_id`),
  CONSTRAINT `fk_profile_media_media1` FOREIGN KEY (`media_id`) REFERENCES `media` (`media_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `media_ibfk_20` FOREIGN KEY (`profile_id`) REFERENCES `profile` (`profile_id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1150 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `profile_type`
--

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

--
-- Table structure for table `province`
--

DROP TABLE IF EXISTS `province`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `province` (
  `province_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(15) NOT NULL,
  `nation_id` int(11) NOT NULL,
  PRIMARY KEY (`province_id`),
  UNIQUE KEY `province_name_key` (`name`),
  KEY `province_nation_id_idx` (`nation_id`),
  CONSTRAINT `fk_province_nation1` FOREIGN KEY (`nation_id`) REFERENCES `nation` (`nation_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=162 DEFAULT CHARSET=utf8;
/*!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` (
  `town_id` int(11) NOT NULL AUTO_INCREMENT,
  `province_id` int(11) NOT NULL,
  `name` varchar(30) NOT NULL,
  `postal_code` varchar(8) NOT NULL,
  PRIMARY KEY (`town_id`),
  KEY `town_province_id_idx` (`province_id`),
  CONSTRAINT `town_ibfk_1` FOREIGN KEY (`province_id`) REFERENCES `province` (`province_id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3673 DEFAULT CHARSET=utf8;
/*!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` (
  `workcenter_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` longtext,
  `center_id` int(11) DEFAULT NULL,
  `counter` bigint(20) DEFAULT NULL,
  `warehouseFk` smallint(6) DEFAULT NULL,
  PRIMARY KEY (`workcenter_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workerTimeControlConfig`
--

DROP TABLE IF EXISTS `workerTimeControlConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerTimeControlConfig` (
  `id` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `warehouseFk` smallint(6) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `warehouseFk_1_idx` (`warehouseFk`),
  CONSTRAINT `warehouseFk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `vn2008`.`warehouse` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping events for database 'postgresql'
--

--
-- Dumping routines for database 'postgresql'
--

--
-- 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` set('READ','WRITE','*') COLLATE utf8_unicode_ci DEFAULT 'READ',
  `permission` set('DENY','ALLOW') COLLATE utf8_unicode_ci DEFAULT 'ALLOW',
  `principalType` set('ROLE','USER') COLLATE utf8_unicode_ci DEFAULT 'ROLE',
  `principalId` varchar(512) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=167 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

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

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

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

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

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

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

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

--
-- Table structure for table `fieldAcl`
--

DROP TABLE IF EXISTS `fieldAcl`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `fieldAcl` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `model` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `property` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `actionType` set('insert','update','*') COLLATE utf8_unicode_ci DEFAULT '*',
  `role` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=65 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 */;

--
-- Table structure for table `userConfigView`
--

DROP TABLE IF EXISTS `userConfigView`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `userConfigView` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userFk` int(10) unsigned NOT NULL,
  `tableCode` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `configuration` text COLLATE utf8_unicode_ci,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uniqueUser_TableCode` (`userFk`,`tableCode`)
) ENGINE=InnoDB AUTO_INCREMENT=18 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: `stock`
--

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

USE `stock`;

--
-- Table structure for table `inbound`
--

DROP TABLE IF EXISTS `inbound`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `inbound` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `tableName` set('buy','sale') NOT NULL,
  `tableId` int(10) unsigned NOT NULL,
  `isSync` tinyint(4) NOT NULL,
  `isPicked` tinyint(4) NOT NULL DEFAULT '0',
  `warehouseFk` int(10) unsigned NOT NULL,
  `itemFk` int(10) unsigned NOT NULL,
  `dated` datetime NOT NULL,
  `expired` datetime DEFAULT NULL,
  `quantity` int(10) unsigned NOT NULL,
  `available` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `source` (`tableName`,`tableId`),
  KEY `warehouseFk` (`warehouseFk`,`itemFk`,`dated`,`expired`,`available`),
  KEY `isSync` (`isSync`)
) ENGINE=InnoDB AUTO_INCREMENT=2048 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
ALTER DATABASE `stock` CHARACTER SET utf8 COLLATE utf8_unicode_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' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `stock`.`inbound_beforeInsert`
	BEFORE INSERT ON `inbound`
    FOR EACH ROW
BEGIN
	SET NEW.isPicked = NEW.isPicked OR NEW.dated < CURDATE();
    
    CALL visible_log(
		NEW.isPicked,
        NEW.warehouseFk,
        NEW.itemFk,
        NEW.quantity
	);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `stock` 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' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `stock`.`inbound_afterDelete`
	AFTER DELETE ON `inbound`
    FOR EACH ROW
BEGIN
	UPDATE outbound o
		JOIN inboundOut ou ON ou.outboundFk = o.id
		SET o.lack = o.lack + ou.quantity,
			o.isSync = FALSE
		WHERE ou.inboundFk = OLD.id;

	DELETE FROM inboundOut
		WHERE inboundFk = OLD.id;

    CALL visible_log(
		OLD.isPicked,
        OLD.warehouseFk,
        OLD.itemFk,
        -OLD.quantity
	);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `inboundOut`
--

DROP TABLE IF EXISTS `inboundOut`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `inboundOut` (
  `inboundFk` int(10) unsigned DEFAULT NULL,
  `outboundFk` int(10) unsigned DEFAULT NULL,
  `quantity` int(11) NOT NULL,
  UNIQUE KEY `buyFk` (`inboundFk`,`outboundFk`),
  KEY `saleFk` (`outboundFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `log`
--

DROP TABLE IF EXISTS `log`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `log` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `operation` set('insert','delete') NOT NULL,
  `tableName` varchar(255) NOT NULL,
  `tableId` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `tableName` (`tableName`,`tableId`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `logLock`
--

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

--
-- Table structure for table `outbound`
--

DROP TABLE IF EXISTS `outbound`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `outbound` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `tableName` set('sale','buy','orderRow') NOT NULL,
  `tableId` int(10) unsigned NOT NULL,
  `isSync` tinyint(3) unsigned NOT NULL,
  `isPicked` tinyint(4) NOT NULL DEFAULT '0',
  `warehouseFk` int(10) unsigned NOT NULL,
  `itemFk` int(10) unsigned NOT NULL,
  `dated` datetime NOT NULL,
  `created` datetime NOT NULL,
  `expired` datetime DEFAULT NULL,
  `quantity` int(10) unsigned NOT NULL,
  `lack` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `source` (`tableName`,`tableId`),
  KEY `warehouseFk` (`warehouseFk`,`itemFk`,`dated`),
  KEY `expired` (`expired`),
  KEY `isSync` (`isSync`)
) ENGINE=InnoDB AUTO_INCREMENT=131071 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
ALTER DATABASE `stock` CHARACTER SET utf8 COLLATE utf8_unicode_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' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `stock`.`outbound_beforeInsert`
	BEFORE INSERT ON `outbound`
	FOR EACH ROW
BEGIN
	SET NEW.lack = NEW.quantity;
	SET NEW.isPicked = NEW.isPicked OR NEW.dated < CURDATE();
    
    CALL visible_log(
		NEW.isPicked,
        NEW.warehouseFk,
        NEW.itemFk,
        -NEW.quantity
	);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `stock` 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' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `stock`.`outbound_afterDelete`
	AFTER DELETE ON `outbound`
    FOR EACH ROW
BEGIN
	UPDATE inbound i
		JOIN inboundOut ou ON ou.inboundFk = i.id
		SET i.available = i.available + ou.quantity,
			i.isSync = FALSE
		WHERE ou.outboundFk = OLD.id;

	DELETE FROM inboundOut
		WHERE outboundFk = OLD.id;

    CALL visible_log(
		OLD.isPicked,
        OLD.warehouseFk,
        OLD.itemFk,
        OLD.quantity
	);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `visible`
--

DROP TABLE IF EXISTS `visible`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `visible` (
  `itemFk` int(10) unsigned NOT NULL,
  `warehouseFk` int(10) unsigned NOT NULL,
  `quantity` int(11) NOT NULL,
  PRIMARY KEY (`itemFk`,`warehouseFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping events for database 'stock'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `log_syncNoWait` */;
DELIMITER ;;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
/*!50003 SET character_set_client  = utf8mb4 */ ;;
/*!50003 SET character_set_results = utf8mb4 */ ;;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone      = @@time_zone */ ;;
/*!50003 SET time_zone             = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `log_syncNoWait` ON SCHEDULE EVERY 5 SECOND STARTS '2017-06-27 17:15:02' ON COMPLETION NOT PRESERVE ENABLE DO CALL log_syncNoWait */ ;;
/*!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 'stock'
--
/*!50003 DROP PROCEDURE IF EXISTS `inboundOut_apply` */;
ALTER DATABASE `stock` CHARACTER SET utf8 COLLATE utf8_unicode_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' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `inboundOut_apply`(
	`vInboundFk` INT,
    `vOutboundFk` INT,
    `vQuantity` INT)
BEGIN
/**
 * Deletes a row.
 *
 * @param vInboundFk The inbound identifier
 * @param vOutboundFk The outbound identifier
 * @param vQuantity The quantity to discount
 */
	UPDATE inbound
		SET available = available - vQuantity
		WHERE id = vInboundFk;

	UPDATE outbound
		SET lack = lack - vQuantity
		WHERE id = vOutboundFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `stock` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `inbound_requestQuantity` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `inbound_requestQuantity`(
	vSelf INT,
    vRequested INT,
    vDated DATETIME,
    OUT vGranted INT)
BEGIN
/**
 * Requests a quantity from an inbound to fulfill an outbound.
 * If the demanded quantity exceeds the available, it also
 * disassociates it's outbounds after the given date until the
 * demanded quantity is satisfied or there is no more available.
 *
 * @param vSelf The inbound reference
 * @param vRequested The requested quantity
 * @param vDate The starting date for the associated outbounds
 * @param vGranted The granted quantity
 */
	DECLARE vQuantity INT;
	DECLARE vAvailable INT;
	DECLARE vOutboundFk INT;
	DECLARE vLinkQuantity INT;
	DECLARE vLinkGranted INT;
	DECLARE vDone BOOL;

	DECLARE cInboundOuts CURSOR FOR
		SELECT ou.outboundFk, ou.quantity
			FROM inboundOut ou
				JOIN outbound o ON o.id = ou.outboundFk
			WHERE ou.inboundFk = vSelf
				AND o.dated > vDated
			ORDER BY o.dated DESC, o.created DESC;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	SELECT quantity, available INTO vQuantity, vAvailable
		FROM inbound
		WHERE id = vSelf;

	SET vGranted = LEAST(vRequested, vAvailable);

	IF vGranted < vRequested AND vAvailable < vQuantity THEN
		OPEN cInboundOuts;

		myLoop: LOOP
			SET vDone = FALSE;
			FETCH cInboundOuts INTO vOutboundFk, vLinkQuantity;

			IF vDone THEN
				LEAVE myLoop;
			END IF;

			SET vLinkGranted = LEAST(vRequested - vGranted, vLinkQuantity);
			SET vGranted = vGranted + vLinkGranted;

			IF vLinkGranted < vLinkQuantity THEN
				UPDATE inboundOut
					SET quantity = quantity - vLinkGranted
					WHERE outboundFk = vOutboundFk AND inboundFk = vSelf;
			ELSE
				DELETE FROM inboundOut
					WHERE outboundFk = vOutboundFk AND inboundFk = vSelf;
			END IF;
            
            UPDATE outbound SET isSync = FALSE
				WHERE id = vOutboundFk;

			CALL inboundOut_apply(vOutboundFk, vSelf, -vLinkGranted);

			IF vGranted >= vRequested THEN
				LEAVE myLoop;
			END IF;
		END LOOP;

		CLOSE cInboundOuts;
	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 `inbound_sync` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `inbound_sync`(vSelf INT)
BEGIN
/**
 * Associates a inbound with their possible outbounds, updating it's available.
 *
 * @param vSelf The inbound identifier
 */
	DECLARE vDated DATETIME;
	DECLARE vExpired DATETIME;
    DECLARE vItem INT;
	DECLARE vWarehouse INT;
	DECLARE vQuantity INT;
	DECLARE vAvailable INT;
	DECLARE vOutboundFk INT;
	DECLARE vGranted INT;
	DECLARE vDone BOOL;

	DECLARE cOutbound CURSOR FOR
		SELECT id
			FROM outbound
			WHERE warehouseFk = vWarehouse
                AND itemFk = vItem
				AND dated >= vDated
				AND (vExpired IS NULL OR dated < vExpired)
			ORDER BY dated, created;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	SELECT warehouseFk, itemFk, available, quantity, expired, dated
		INTO vWarehouse, vItem, vAvailable, vQuantity, vExpired, vDated
		FROM inbound
		WHERE id = vSelf;

	IF vAvailable IS NULL THEN
		SET vAvailable = vQuantity;
        UPDATE inbound SET available = vQuantity
			WHERE id = vSelf;
	END IF;

	OPEN cOutbound;

	myLoop: LOOP
		SET vDone = FALSE;
		FETCH cOutbound INTO vOutboundFk;

		IF vDone THEN
			LEAVE myLoop;
		END IF;

		CALL outbound_requestQuantity(vOutboundFk, vAvailable, vDated, vGranted);
        
        IF vGranted > 0 THEN
			SET vAvailable = vAvailable - vGranted;

			INSERT INTO inboundOut
				SET
					inboundFk = vSelf,
					outboundFk = vOutboundFk,
					quantity = vGranted
				ON DUPLICATE KEY UPDATE
					quantity = quantity + vGranted;

			CALL inboundOut_apply(vSelf, vOutboundFk, vGranted);
		END IF;

		IF vAvailable <= 0 THEN
			LEAVE myLoop;
		END IF;
	END LOOP;

	CLOSE cOutbound;

	UPDATE inbound SET isSync = TRUE
		WHERE id = vSelf;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `log_add` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `log_add`(
	vTableName VARCHAR(255),
    vNewId VARCHAR(255),
    vOldId VARCHAR(255)
)
proc: BEGIN
	-- XXX: Disabled while testing
	-- LEAVE proc;

	IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN
		INSERT IGNORE INTO `log` SET
			tableName = vTableName,
			tableId = vOldId,
			operation = 'delete';
	END IF;

	IF vNewId IS NOT NULL THEN
		INSERT IGNORE INTO `log` SET
			tableName = vTableName,
			tableId = vNewId,
			operation = 'insert';
	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 `log_delete` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `log_delete`(vTableName VARCHAR(255), vTableId INT)
proc: BEGIN
/**
 * Processes orphan transactions.
 */
	IF vTableName NOT IN ('buy', 'sale', 'orderRow') THEN
		LEAVE proc;
	END IF;

	DELETE FROM inbound
		WHERE tableName = vTableName COLLATE utf8_general_ci
			AND tableId = vTableId;

	DELETE FROM outbound
		WHERE tableName = vTableName COLLATE utf8_general_ci
			AND tableId = vTableId;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `log_refreshAll` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `log_refreshAll`()
BEGIN
/**
 * Recalculates the entire cache. It takes a considerable time,
 * please avoid calls to this procedure from commonly used operations.
 */
	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		DO RELEASE_LOCK('stock.log_sync');
		RESIGNAL;
	END;
    
	IF !GET_LOCK('stock.log_sync', 30) THEN
		CALL util.throw('Lock timeout exceeded');
	END IF;

	TRUNCATE TABLE stock.`log`;
	TRUNCATE TABLE stock.`inbound`;
	TRUNCATE TABLE stock.`inboundOut`;
	TRUNCATE TABLE stock.`outbound`;
	TRUNCATE TABLE stock.`visible`;

	CALL log_refreshSale(NULL, NULL);
	CALL log_refreshBuy(NULL, NULL);
	CALL log_refreshOrder(NULL, NULL);

	UPDATE outbound SET isSync = TRUE;
	CALL log_sync(TRUE);

	DO RELEASE_LOCK('stock.log_sync');
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `log_refreshBuy` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `log_refreshBuy`(
    `vTableName` VARCHAR(255),
    `vTableId` INT)
BEGIN
	DROP TEMPORARY TABLE IF EXISTS tValues;
	CREATE TEMPORARY TABLE tValues
		ENGINE = MEMORY
		SELECT
				b.id buyFk,
				e.id entryFk,
				t.id travelFk,
				b.itemFk,
                e.isRaid,
				ADDTIME(t.shipped,
					IFNULL(t.shipmentHour, '00:00:00')) shipped,
				t.warehouseOutFk,
				t.isDelivered,
				ADDTIME(t.landed,
					IFNULL(t.landingHour, '00:00:00')) landed,
				t.warehouseInFk,
				t.isReceived,
				tp.life,
				ABS(b.quantity) quantity,
				b.created,
				b.quantity > 0 isIn,
                t.shipped < vn.getInventoryDate() lessThanInventory
			FROM vn.buy b
				JOIN vn.entry e ON e.id = b.entryFk
				JOIN vn.travel t ON t.id = e.travelFk
				JOIN vn.item i ON i.id = b.itemFk
				JOIN vn.itemType tp ON tp.id = i.typeFk
			WHERE (
					vTableId IS NULL
					OR (vTableName = 'travel' AND t.id = vTableId)
					OR (vTableName = 'entry' AND e.id = vTableId)
					OR (vTableName = 'buy' AND b.id = vTableId)
				)
				AND t.landed >= vn.getInventoryDate()
				AND b.quantity != 0;

	REPLACE INTO inbound (
			tableName, tableId, warehouseFk, dated,
			itemFk, expired, quantity, isPicked
		)
		SELECT 'buy',
				buyFk,
				IF(isIn, warehouseInFk, warehouseOutFk),
				@dated := IF(isIn, landed, shipped),
				itemFk,
				TIMESTAMPADD(DAY, life, @dated),
				quantity,
				IF(isIn, isReceived, isDelivered) AND !isRaid
			FROM tValues
            WHERE isIn OR !lessThanInventory;

	REPLACE INTO outbound (
			tableName, tableId, warehouseFk, dated,
			itemFk, created, quantity, isPicked
		)
		SELECT 'buy',
				buyFk,
				IF(isIn, warehouseOutFk, warehouseInFk),
				IF(isIn, shipped, landed),
				itemFk,
				created,
				quantity,
				IF(isIn, isDelivered, isReceived) AND !isRaid
			FROM tValues
            WHERE !isIn OR !lessThanInventory;

	DROP TEMPORARY TABLE tValues;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `log_refreshOrder` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `log_refreshOrder`(
    `vTableName` VARCHAR(255),
    `vTableId` INT)
BEGIN
	DECLARE vExpireTime INT DEFAULT 10;
	DECLARE vExpired DATETIME DEFAULT TIMESTAMPADD(MINUTE, -vExpireTime, NOW());

	DROP TEMPORARY TABLE IF EXISTS tValues;
    CREATE TEMPORARY TABLE tValues
		ENGINE = MEMORY
		SELECT
				r.id rowFk,
				r.itemFk,
				r.warehouseFk,
				r.shipment shipped,
				r.amount quantity,
				r.created
			FROM hedera.orderRow r
				JOIN hedera.`order` o ON o.id = r.orderFk
			WHERE (
					vTableId IS NULL
					OR (vTableName = 'order' AND o.id = vTableId)
					OR (vTableName = 'orderRow' AND r.id = vTableId)
				)
                AND !o.confirmed
				AND r.created >= vExpired
				AND r.amount != 0;

	REPLACE INTO outbound (
			tableName, tableId, warehouseFk, dated,
            itemFk, created, expired, quantity
		)
        SELECT 'orderRow',
				rowFk,
				warehouseFk,
				shipped,
				itemFk,
				created,
                TIMESTAMPADD(MINUTE, -vExpireTime, created),
				quantity
            FROM tValues;

	DROP TEMPORARY TABLE tValues;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `log_refreshSale` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `log_refreshSale`(
    `vTableName` VARCHAR(255),
    `vTableId` INT)
BEGIN
	DROP TEMPORARY TABLE IF EXISTS tValues;
    CREATE TEMPORARY TABLE tValues
		ENGINE = MEMORY
		SELECT
				m.id saleFk,
				m.ticketFk,
				m.itemFk,
				t.warehouseFk,
				t.shipped,
				ABS(m.quantity) quantity,
				m.created,
                TIMESTAMPADD(DAY, tp.life, t.shipped) expired,
				m.quantity < 0 isIn,
				m.isPicked OR s.alertLevel > 1 isPicked
			FROM vn.sale m
				JOIN vn.ticket t ON t.id = m.ticketFk
				JOIN vn.ticketState s ON s.ticketFk = t.id
				JOIN vn.item i ON i.id = m.itemFk
				JOIN vn.itemType tp ON tp.id = i.typeFk
			WHERE (
					vTableId IS NULL
					OR (vTableName = 'ticket' AND t.id = vTableId)
					OR (vTableName = 'sale' AND m.id = vTableId)
				)
				AND t.shipped >= vn.getInventoryDate()
				AND m.quantity != 0;

	REPLACE INTO inbound (
			tableName, tableId, warehouseFk, dated,
            itemFk, expired, quantity, isPicked
		)
        SELECT 'sale',
				saleFk,
				warehouseFk,
				shipped,
				itemFk,
                expired,
				quantity,
                isPicked
            FROM tValues
            WHERE isIn;

	REPLACE INTO outbound (
			tableName, tableId, warehouseFk, dated,
            itemFk, created, quantity, isPicked
		)
        SELECT 'sale',
				saleFk,
				warehouseFk,
				shipped,
				itemFk,
				created,
				quantity,
                isPicked
            FROM tValues
            WHERE !isIn;

	DROP TEMPORARY TABLE tValues;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `log_sync` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `log_sync`(vSync BOOL)
proc: BEGIN
	DECLARE vDone BOOL;
	DECLARE vLogId INT;
	DECLARE vOperation VARCHAR(255);
	DECLARE vTableName VARCHAR(255);
	DECLARE vTableId VARCHAR(255);
	DECLARE vInboundFk INT;
	DECLARE vOutboundFk INT;

	DECLARE cInbound CURSOR FOR
		SELECT id FROM inbound
			WHERE !isSync
			ORDER BY dated;

	DECLARE cOutbound CURSOR FOR
		SELECT id FROM outbound
			WHERE !isSync
			ORDER BY dated;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

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

	-- Applies changes

	opsLoop: LOOP
		START TRANSACTION;

		SET vDone = FALSE;
		SELECT id, operation, tableName, tableId
			INTO vLogId, vOperation, vTableName, vTableId
			FROM `log`
			ORDER BY id LIMIT 1
			FOR UPDATE;

		IF vDone THEN
			COMMIT;
			LEAVE opsLoop;
		END IF;

		CALL log_delete(vTableName, vTableId);

		IF vOperation = 'insert' THEN
			IF vTableName IN ('travel', 'entry', 'buy') THEN
				CALL log_refreshBuy(vTableName, vTableId);
			ELSEIF vTableName IN ('ticket', 'sale') THEN
				CALL log_refreshSale(vTableName, vTableId);
			ELSEIF vTableName IN ('order', 'orderRow') THEN
				CALL log_refreshOrder(vTableName, vTableId);
			END IF;
		END IF;

		DELETE FROM `log` WHERE id = vLogId;
		SET vSync = TRUE;

		COMMIT;
	END LOOP;
    
    IF !vSync THEN
		LEAVE proc;
	END IF;

	-- Deletes expired outbounds

	DELETE FROM outbound WHERE expired <= NOW();

	-- Attaches desync inbounds

	OPEN cInbound;

	inboundLoop: LOOP
		SET vDone = FALSE;
		FETCH cInbound INTO vInboundFk;

		IF vDone THEN
			LEAVE inboundLoop;
		END IF;

		START TRANSACTION;
		CALL inbound_sync(vInboundFk);
		COMMIT;
	END LOOP;

	CLOSE cInbound;

	-- Attaches desync outbounds

	OPEN cOutbound;

	outboundLoop: LOOP
		SET vDone = FALSE;
		FETCH cOutbound INTO vOutboundFk;

		IF vDone THEN
			LEAVE outboundLoop;
		END IF;

		START TRANSACTION;
		CALL outbound_sync(vOutboundFk);
		COMMIT;
	END LOOP;

	CLOSE cOutbound;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `log_syncNoWait` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`z-developer`@`%` PROCEDURE `log_syncNoWait`()
BEGIN
	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		DO RELEASE_LOCK('stock.log_sync');
		RESIGNAL;
	END;

	IF GET_LOCK('stock.log_sync', 0) THEN
		CALL log_sync(FALSE);
	END IF;

	DO RELEASE_LOCK('stock.log_sync');
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `outbound_requestQuantity` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `outbound_requestQuantity`(
	vSelf INT,
    vRequested INT,
    vDated DATETIME,
    OUT vGranted INT)
BEGIN
/**
 * Requests a quantity from an outbound to fulfill an inbound.
 * If the demanded quantity exceeds the lack, it also
 * disassociates it's inbounds after the given date until the
 * demanded quantity is satisfied or there is no more lack.
 *
 * @param vSelf The outbound reference
 * @param vRequested The requested quantity
 * @param vDate The starting date for the associated inbounds
 * @param vGranted The granted quantity
 */
	DECLARE vQuantity INT;
	DECLARE vLack INT;
	DECLARE vInboundFk INT;
	DECLARE vLinkQuantity INT;
	DECLARE vLinkGranted INT;
	DECLARE vDone BOOL;

	DECLARE cOutboundIns CURSOR FOR
		SELECT ou.inboundFk, ou.quantity
			FROM inboundOut ou
				JOIN inbound i ON i.id = ou.inboundFk
			WHERE ou.outboundFk = vSelf
				AND i.dated > vDated
			ORDER BY i.dated DESC;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	SELECT quantity, lack INTO vQuantity, vLack
		FROM outbound
		WHERE id = vSelf;

	SET vGranted = LEAST(vRequested, vLack);

	IF vLack < vQuantity AND vGranted < vRequested THEN
		OPEN cOutboundIns;

		myLoop: LOOP
			SET vDone = FALSE;
			FETCH cOutboundIns INTO vInboundFk, vLinkQuantity;

			IF vDone THEN
				LEAVE myLoop;
			END IF;

			SET vLinkGranted = LEAST(vRequested - vGranted, vLinkQuantity);
			SET vGranted = vGranted + vLinkGranted;

			IF vLinkGranted < vLinkQuantity THEN
				UPDATE inboundOut
					SET quantity = quantity - vLinkGranted
					WHERE inboundFk = vInboundFk AND outboundFk = vSelf;
			ELSE
				DELETE FROM inboundOut
					WHERE inboundFk = vInboundFk AND outboundFk = vSelf;
			END IF;
            
            UPDATE inbound SET isSync = FALSE
				WHERE id = vInboundFk;

			CALL inboundOut_apply(vInboundFk, vSelf, -vLinkGranted);

			IF vGranted >= vRequested THEN
				LEAVE myLoop;
			END IF;
		END LOOP;

		CLOSE cOutboundIns;
	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 `outbound_sync` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `outbound_sync`(vSelf INT)
BEGIN
/**
 * Attaches a outbound with available inbounds.
 *
 * @param vSelf The outbound reference
 */
	DECLARE vDated DATETIME;
    DECLARE vItem INT;
	DECLARE vWarehouse INT;
	DECLARE vLack INT;
	DECLARE vInboundFk INT;
	DECLARE vAvailable INT;
	DECLARE vGranted INT;
	DECLARE vDone BOOL;

	DECLARE cInbound CURSOR FOR
		SELECT id, available
			FROM inbound
			WHERE warehouseFk = vWarehouse
                AND itemFk = vItem
				AND dated <= vDated
				AND (expired IS NULL OR expired > vDated)
			ORDER BY dated;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	SELECT warehouseFk, itemFk, dated, lack
		INTO vWarehouse, vItem, vDated, vLack
		FROM outbound
		WHERE id = vSelf;

	OPEN cInbound;

	myLoop: LOOP
		SET vDone = FALSE;
		FETCH cInbound INTO vInboundFk, vAvailable;

		IF vDone THEN
			LEAVE myLoop;
		END IF;

		CALL inbound_requestQuantity(vInboundFk, vLack, vDated, vGranted);
        
        IF vGranted > 0 THEN
			SET vLack = vLack - vGranted;

			INSERT INTO inboundOut
				SET
					inboundFk = vInboundFk,
					outboundFk = vSelf,
					quantity = vGranted
				ON DUPLICATE KEY UPDATE
					quantity = quantity + vGranted;

			CALL inboundOut_apply(vInboundFk, vSelf, vGranted);
		END IF;

		IF vLack = 0 THEN
			LEAVE myLoop;
		END IF;
	END LOOP;

	CLOSE cInbound;

	UPDATE outbound SET isSync = TRUE
		WHERE id = vSelf;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_log` */;
ALTER DATABASE `stock` CHARACTER SET utf8 COLLATE utf8_unicode_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' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `visible_log`(
	vIsPicked BOOL,
    vWarehouseFk INT,
    vItemFk INT,
    vQuantity INT
)
proc: BEGIN
	IF !vIsPicked THEN
		LEAVE proc;
	END IF;

    INSERT INTO visible
		SET itemFk = vItemFk,
			warehouseFk = vWarehouseFk,
			quantity = vQuantity
		ON DUPLICATE KEY UPDATE
			quantity = quantity + VALUES(quantity);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `stock` CHARACTER SET utf8 COLLATE utf8_general_ci ;

--
-- Current Database: `util`
--

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

USE `util`;

--
-- 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,
  `dbVersion` char(11) CHARACTER SET utf8 DEFAULT NULL COMMENT 'The current database version',
  `hasTriggersDisabled` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Defines if triggers are disabled',
  `environment` varchar(45) CHARACTER SET utf8 DEFAULT NULL COMMENT 'The current Database environment',
  `lastDump` datetime DEFAULT NULL COMMENT 'Timestamp of the last data dump',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Global configuration table';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `debug`
--

DROP TABLE IF EXISTS `debug`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `debug` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `connectionId` int(10) unsigned DEFAULT NULL,
  `user` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  `host` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  `variable` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  `value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Log de depuración';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping events for database 'util'
--

--
-- Dumping routines for database 'util'
--
/*!50003 DROP FUNCTION IF EXISTS `capitalizeFirst` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `capitalizeFirst`(vString VARCHAR(255)) RETURNS varchar(255) CHARSET utf8
    NO SQL
    DETERMINISTIC
BEGIN
/**
 * Pass the first letter of every word in a string to uppercase.
 *
 * @param vString String to tranform
 * @return Transformed string
 */
	DECLARE vNewString VARCHAR(255) DEFAULT '';
	DECLARE vI INT DEFAULT 1;
	DECLARE vSpaceIni, vWordIni INT;
	DECLARE vLen INT DEFAULT CHAR_LENGTH(vString);

	WHILE vI < vLen
	DO
		SET vSpaceIni = vI;
		
		WHILE MID(vString, vI, 1) REGEXP '[[:space:]]' DO
			SET vI = vI + 1;
		END WHILE;
		
		SET vWordIni = vI;
		SET vI = vWordIni + 1;

		WHILE vI <= vLen AND MID(vString, vI, 1) NOT REGEXP '[[:space:]]' DO
			SET vI = vI + 1;
		END WHILE;

		SET vNewString = CONCAT(vNewString
			,MID(vString, vSpaceIni, vWordIni - vSpaceIni)
			,UPPER(MID(vString, vWordIni, 1))
			,MID(vString, vWordIni + 1, vI - vWordIni - 1)
		);
	END WHILE;

	RETURN vNewString;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `dayEnd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `dayEnd`(vDated DATE) RETURNS datetime
    NO SQL
    DETERMINISTIC
BEGIN
/**
 * Formats a date to the end of the day.
 *
 * @param vDated The date to format
 * @return The formatted date
 */
	RETURN TIMESTAMP(vDated, '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 */ ;
/*!50003 DROP FUNCTION IF EXISTS `firstDayOfMonth` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `firstDayOfMonth`(vDate DATE) RETURNS date
    NO SQL
    DETERMINISTIC
BEGIN
/**
 * Returns the date formatted to the first day of month.
 *
 * @param vDate The date to format
 * @return The formatted date
 */
	RETURN DATE_FORMAT(vDate, '%Y-%m-01');
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `hmacSha2` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `hmacSha2`(`vAlg` SMALLINT, `vMsg` MEDIUMBLOB, `vKey` MEDIUMBLOB) RETURNS varchar(128) CHARSET utf8
    NO SQL
    DETERMINISTIC
BEGIN
/**
 * HMAC function based on SHA2 algorythms.
 */
    DECLARE vHashlen INT UNSIGNED;
    DECLARE vOpad, vIpad TINYBLOB;
    
    CASE vAlg
        WHEN 224 THEN SET vHashlen = 64;
        WHEN 256 THEN SET vHashlen = 64;
        WHEN 384 THEN SET vHashlen = 128;
        WHEN 512 THEN SET vHashlen = 128;
        ELSE CALL throw ('WRONG_ALGORYTHM_IDENTIFICATOR_USED');
    END CASE;
    
    IF LENGTH(vKey) > vHashlen THEN
        SET vKey = UNHEX(SHA2(vKey, vAlg));
    END IF;
    
    SET vKey = RPAD(vKey, vHashlen, 0x00);
    
    SET vIpad = stringXor(vKey, 0x36);
    SET vOpad = stringXor(vKey, 0x5C);
    
    RETURN SHA2(CONCAT(vOpad, UNHEX(SHA2(CONCAT(vIpad, vMsg), vAlg))), vAlg);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `lang` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `lang`() RETURNS char(2) CHARSET utf8
    NO SQL
    DETERMINISTIC
BEGIN
/**
 * Returns the current language code.
 *
 * @return The language code
 */
	RETURN IFNULL(@lang, SUBSTR(@@lc_messages, 1, 2));
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `nextWeek` */;
ALTER DATABASE `util` 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 `nextWeek`(vYearWeek INT) RETURNS int(11)
    DETERMINISTIC
BEGIN
/**
 * A partir de un perido año/semana en formato AAAASS devuelve el siguiente
 * periodo. Esta función trabaja de la misma forma que la función WEEK() en
 * modo 3.
 */
	DECLARE vYear INT DEFAULT FLOOR(vYearWeek / 100);
    
    IF vYearWeek < YEARWEEK(CONCAT(vYear, '-12-31'), 3) THEN
		RETURN vYearWeek + 1;
	ELSE
		RETURN ((vYear + 1) * 100) + 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 */ ;
ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP FUNCTION IF EXISTS `stringXor` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `stringXor`(vString MEDIUMBLOB, vConst TINYINT UNSIGNED) RETURNS mediumblob
    NO SQL
    DETERMINISTIC
BEGIN
/**
 * Returns XOR of binary string and an 8-bit constant.
 */
    DECLARE vLen, vPos INT UNSIGNED;
    DECLARE vResult MEDIUMBLOB;
    
    SET vLen = LENGTH(vString);
    SET vPos = 1;
    SET vResult = '';
    
    WHILE vPos <= vLen DO
        SET vResult = CONCAT(vResult, LPAD(HEX( ORD(SUBSTR(vString, vPos, 1)) ^ vConst), 2, '0'));
        SET vPos = vPos + 1;
    END WHILE;
    
    RETURN UNHEX(vResult);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `today` */;
ALTER DATABASE `util` 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 `today`() RETURNS date
    DETERMINISTIC
BEGIN
/**
 * Devuelve la fecha actual. Usar en lugar de la función nativa
 * CURDATE() en aquellos que se necesite rendimiento ya que la
 * la última no es determinista.
 *
 * @return La fecha actual
 */
	RETURN 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 `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP FUNCTION IF EXISTS `tomorrow` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `tomorrow`() RETURNS date
    DETERMINISTIC
BEGIN
/**
 * Devuelve la fecha de mañana.
 *
 * @return La fecha de mañana
 */
	RETURN TIMESTAMPADD(DAY, 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 FUNCTION IF EXISTS `twoDaysAgo` */;
ALTER DATABASE `util` 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 `twoDaysAgo`() RETURNS date
    DETERMINISTIC
BEGIN
/**
 * Devuelve la fecha de antes de ayer.
 *
 * @return La fecha de antes de ayer
 */
	RETURN TIMESTAMPADD(DAY, -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 `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP FUNCTION IF EXISTS `yearRelativePosition` */;
ALTER DATABASE `util` 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 `yearRelativePosition`(vYear INT) RETURNS varchar(20) CHARSET utf8
    DETERMINISTIC
BEGIN
/**
 * Devuelve la posicion del año relativa al año actual.
 * Se utiliza como cabecera en informes de balances.
 *
 * @param vYear Año a evaluar
 * @return La posicion relativa del año
 */
	DECLARE vCurYear INT DEFAULT YEAR(CURDATE());

	IF vYear = vCurYear THEN
		RETURN 'curYear';
	END IF;
    
	IF vYear = vCurYear - 1 THEN
		RETURN 'lastYear';
	END IF;
	
	IF vYear = vCurYear - 2 THEN
		RETURN 'twoYearsAgo';
	END IF;

	RETURN 'other';
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP FUNCTION IF EXISTS `yesterday` */;
ALTER DATABASE `util` 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 `yesterday`() RETURNS date
    DETERMINISTIC
BEGIN
/**
 * Devuelve la fecha de ayer.
 *
 * @return La fecha de ayer
 */
	RETURN TIMESTAMPADD(DAY, -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 */ ;
ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `debugAdd` */;
ALTER DATABASE `util` 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 `debugAdd`(vVariable VARCHAR(255), vValue VARCHAR(255))
    MODIFIES SQL DATA
BEGIN
/**
 * Añade una entrada de depuración en la tabla @debug.
 *
 * @param vVariable Nombre de variable
 * @param vValue Valor de la variable
 */
	DECLARE vIndex INT DEFAULT INSTR(USER(), '@');
 
	INSERT INTO debug SET
		`connectionId` = CONNECTION_ID(),
        `user` = LEFT(USER(), vIndex - 1),
        `host` = RIGHT(USER(), CHAR_LENGTH(USER()) - vIndex),
        `variable` = vVariable,
        `value` = vValue;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `exec` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `exec`(vSqlQuery TEXT)
BEGIN
/**
 * Executes a string with an SQL query.
 *
 * @param vSqlQuery The SQL string
 */
	SET @sqlQuery = vSqlQuery;

	PREPARE stmt FROM @sqlQuery;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;

    SET @sqlQuery = 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 `findObject` */;
ALTER DATABASE `util` 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 `findObject`(vChain VARCHAR(45))
    READS SQL DATA
BEGIN
/**
 * Devuelve un listado de todos los procedimientos, funciones
 * eventos, disparadores y vistas que inluyen una cadena dada.
 *
 * @param vChain Cadena a buscar
 * @select Listado de objetos
 */
	SET vChain = CONCAT('%', vChain, '%');

	SELECT * FROM
	( 
		SELECT
				`db`,
				`name`,
				`type`,
				`body`,
				`created`,
				`modified`
			FROM `mysql`.`proc`
			WHERE `body` LIKE vChain COLLATE utf8_general_ci
		UNION ALL
		SELECT
				`db`,
				`name`,
				'EVENT',
				`body_utf8`,
				`created`,
				`modified`
			FROM `mysql`.`event`
			WHERE `body_utf8` LIKE vChain COLLATE utf8_general_ci
		UNION ALL
		SELECT
				`EVENT_OBJECT_SCHEMA`,
				`TRIGGER_NAME`,
				'TRIGGER',
				`ACTION_STATEMENT`,
				NULL,
				NULL 
			FROM `information_schema`.`TRIGGERS`
			WHERE `ACTION_STATEMENT` LIKE vChain COLLATE utf8_general_ci
		UNION ALL
		SELECT
				`TABLE_SCHEMA`,
				`TABLE_NAME`,
				'VIEW',
				`VIEW_DEFINITION`,
				NULL,
				NULL 
			FROM `information_schema`.`VIEWS`
			WHERE `VIEW_DEFINITION` LIKE vChain COLLATE utf8_general_ci
	) t
	ORDER BY `db`, `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 `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `throw` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `throw`(vMessage CHAR(35))
BEGIN
/**
 * Throws a user-defined exception.
 *
 * @param vMessage The error message
 */
	SIGNAL SQLSTATE '45000'
		SET MESSAGE_TEXT = vMessage;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `warn` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `warn`(vCode CHAR(35))
BEGIN
	DECLARE w VARCHAR(1) DEFAULT '__';
	SET @warn = 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 */ ;

--
-- Current Database: `vn`
--

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

USE `vn`;

--
-- Temporary table structure for view `absenceType`
--

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

--
-- Temporary table structure for view `accounting`
--

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

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

DROP TABLE IF EXISTS `activeContrat`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `activeContrat` (
  `date` date NOT NULL,
  `business_id` int(11) NOT NULL,
  PRIMARY KEY (`date`,`business_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!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 */;

--
-- Temporary table structure for view `address`
--

DROP TABLE IF EXISTS `address`;
/*!50001 DROP VIEW IF EXISTS `address`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `address` AS SELECT 
 1 AS `id`,
 1 AS `clientFk`,
 1 AS `street`,
 1 AS `city`,
 1 AS `postalCode`,
 1 AS `provinceFk`,
 1 AS `phone`,
 1 AS `mobile`,
 1 AS `nickname`,
 1 AS `isDefaultAddress`,
 1 AS `longitude`,
 1 AS `latitude`,
 1 AS `warehouseFk`,
 1 AS `agencyModeFk`,
 1 AS `isEqualizated`,
 1 AS `isActive`*/;
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 */;

--
-- Temporary table structure for view `addressObservation`
--

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

--
-- Temporary table structure for view `agency`
--

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

--
-- Temporary table structure for view `agencyHour`
--

DROP TABLE IF EXISTS `agencyHour`;
/*!50001 DROP VIEW IF EXISTS `agencyHour`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `agencyHour` AS SELECT 
 1 AS `id`,
 1 AS `agencyFk`,
 1 AS `weekDay`,
 1 AS `warehouseFk`,
 1 AS `provinceFk`,
 1 AS `substractDay`,
 1 AS `maxHour`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `agencyMode`
--

DROP TABLE IF EXISTS `agencyMode`;
/*!50001 DROP VIEW IF EXISTS `agencyMode`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `agencyMode` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `description`,
 1 AS `deliveryMethodFk`,
 1 AS `m3`,
 1 AS `cod71`,
 1 AS `web`,
 1 AS `agencyFk`,
 1 AS `agencyServiceFk`,
 1 AS `inflation`,
 1 AS `isVolumetric`,
 1 AS `reportMail`,
 1 AS `isActive`,
 1 AS `code`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `agencyModeZone`
--

DROP TABLE IF EXISTS `agencyModeZone`;
/*!50001 DROP VIEW IF EXISTS `agencyModeZone`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `agencyModeZone` AS SELECT 
 1 AS `agencyModeFk`,
 1 AS `zone`,
 1 AS `price`,
 1 AS `itemFk`,
 1 AS `warehouseFk`,
 1 AS `minimCost`,
 1 AS `inflation`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `agencyProvince`
--

DROP TABLE IF EXISTS `agencyProvince`;
/*!50001 DROP VIEW IF EXISTS `agencyProvince`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `agencyProvince` AS SELECT 
 1 AS `provinceFk`,
 1 AS `agencyFk`,
 1 AS `zone`,
 1 AS `warehouseFk`,
 1 AS `isVolumetric`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `agencyWarehouse`
--

DROP TABLE IF EXISTS `agencyWarehouse`;
/*!50001 DROP VIEW IF EXISTS `agencyWarehouse`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `agencyWarehouse` AS SELECT 
 1 AS `agencyFk`,
 1 AS `warehouseFk`,
 1 AS `agencyType`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `agencyWeekDayBonus`
--

DROP TABLE IF EXISTS `agencyWeekDayBonus`;
/*!50001 DROP VIEW IF EXISTS `agencyWeekDayBonus`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `agencyWeekDayBonus` AS SELECT 
 1 AS `id`,
 1 AS `warehouseFk`,
 1 AS `agencyFk`,
 1 AS `weekDay`,
 1 AS `zone`,
 1 AS `bonus`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `alertLevel`
--

DROP TABLE IF EXISTS `alertLevel`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `alertLevel` (
  `code` varchar(45) CHARACTER SET utf8 NOT NULL,
  `alertLevel` int(11) NOT NULL,
  PRIMARY KEY (`code`),
  CONSTRAINT `fk_code_1` FOREIGN KEY (`code`) REFERENCES `vn2008`.`state` (`code`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `annualAverageInvoiced`
--

DROP TABLE IF EXISTS `annualAverageInvoiced`;
/*!50001 DROP VIEW IF EXISTS `annualAverageInvoiced`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `annualAverageInvoiced` AS SELECT 
 1 AS `clientFk`,
 1 AS `invoiced`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `assignedTicketToWorker`
--

DROP TABLE IF EXISTS `assignedTicketToWorker`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assignedTicketToWorker` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `idWorker` int(11) DEFAULT NULL,
  `idTicket` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `idWorker_UNIQUE` (`idWorker`),
  UNIQUE KEY `idTicket_UNIQUE` (`idTicket`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla para relacionar un ticket con el sacador del altillo ';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `autoRadioConfig`
--

DROP TABLE IF EXISTS `autoRadioConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `autoRadioConfig` (
  `id` int(11) NOT NULL,
  `password` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `user` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `port` int(11) DEFAULT NULL,
  `url` varchar(75) COLLATE utf8_unicode_ci DEFAULT NULL,
  `login` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `client` int(32) DEFAULT NULL,
  `center` int(32) 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 `autoRadioLogCall`
--

DROP TABLE IF EXISTS `autoRadioLogCall`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `autoRadioLogCall` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ticketFk` int(11) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `response` longtext COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `ticket_idx` (`ticketFk`),
  CONSTRAINT `ticket` FOREIGN KEY (`ticketFk`) REFERENCES `vn2008`.`Tickets` (`Id_Ticket`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=735 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 */;

--
-- Temporary table structure for view `awb`
--

DROP TABLE IF EXISTS `awb`;
/*!50001 DROP VIEW IF EXISTS `awb`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `awb` AS SELECT 
 1 AS `id`,
 1 AS `code`,
 1 AS `package`,
 1 AS `weight`,
 1 AS `created`,
 1 AS `transitoryFk`,
 1 AS `taxFk`,
 1 AS `docFk`,
 1 AS `amount`,
 1 AS `freightFk`,
 1 AS `m3`,
 1 AS `stems`,
 1 AS `flightFk`,
 1 AS `volumeWeight`,
 1 AS `hb`,
 1 AS `rate`,
 1 AS `booked`,
 1 AS `issued`,
 1 AS `operated`,
 1 AS `bookEntried`,
 1 AS `invoiceInFk`,
 1 AS `isChecked`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `bank`
--

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

--
-- Temporary table structure for view `bankEntity`
--

DROP TABLE IF EXISTS `bankEntity`;
/*!50001 DROP VIEW IF EXISTS `bankEntity`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `bankEntity` AS SELECT 
 1 AS `id`,
 1 AS `countryFk`,
 1 AS `name`,
 1 AS `bic`*/;
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) CHARACTER SET utf8 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 `pgcFk_bookingPlanner_idx` (`pgcFk`),
  KEY `taxClassFk` (`taxClassFk`),
  KEY `countryFk` (`countryFk`),
  KEY `bookingPlannerTaxArea` (`taxAreaFk`),
  CONSTRAINT `bookingPlannerTaxArea` FOREIGN KEY (`taxAreaFk`) REFERENCES `taxArea` (`code`) ON UPDATE CASCADE,
  CONSTRAINT `bookingPlanner_ibfk_1` FOREIGN KEY (`pgcFk`) REFERENCES `pgc` (`code`) ON DELETE CASCADE ON UPDATE 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
) ENGINE=InnoDB AUTO_INCREMENT=82 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `botanicExport`
--

DROP TABLE IF EXISTS `botanicExport`;
/*!50001 DROP VIEW IF EXISTS `botanicExport`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `botanicExport` AS SELECT 
 1 AS `id`,
 1 AS `ediGenusFk`,
 1 AS `ediSpecieFk`,
 1 AS `countryFk`,
 1 AS `restriction`,
 1 AS `description`,
 1 AS `isProtectedZone`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `businessReasonEnd`
--

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

--
-- Temporary table structure for view `buy`
--

DROP TABLE IF EXISTS `buy`;
/*!50001 DROP VIEW IF EXISTS `buy`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `buy` AS SELECT 
 1 AS `id`,
 1 AS `entryFk`,
 1 AS `itemFk`,
 1 AS `buyingValue`,
 1 AS `quantity`,
 1 AS `packageFk`,
 1 AS `stickers`,
 1 AS `freightValue`,
 1 AS `packageValue`,
 1 AS `comissionValue`,
 1 AS `packing`,
 1 AS `grouping`,
 1 AS `groupingMode`,
 1 AS `location`,
 1 AS `price1`,
 1 AS `price2`,
 1 AS `price3`,
 1 AS `minPrice`,
 1 AS `producer`,
 1 AS `printedStickers`,
 1 AS `isChecked`,
 1 AS `ektFk`,
 1 AS `created`,
 1 AS `isIgnored`,
 1 AS `isPickedOff`*/;
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 `chain`
--

DROP TABLE IF EXISTS `chain`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `chain` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Grupos de clientes';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `city`
--

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

--
-- Temporary table structure for view `claim`
--

DROP TABLE IF EXISTS `claim`;
/*!50001 DROP VIEW IF EXISTS `claim`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `claim` AS SELECT 
 1 AS `id`,
 1 AS `ticketCreated`,
 1 AS `claimStateFk`,
 1 AS `observation`,
 1 AS `clientFk`,
 1 AS `workerFk`,
 1 AS `responsibility`,
 1 AS `isChargedToMana`,
 1 AS `ticketFk`,
 1 AS `created`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `claimBeginning`
--

DROP TABLE IF EXISTS `claimBeginning`;
/*!50001 DROP VIEW IF EXISTS `claimBeginning`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `claimBeginning` AS SELECT 
 1 AS `id`,
 1 AS `claimFk`,
 1 AS `saleFk`,
 1 AS `quantity`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `claimDestination`
--

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

--
-- Temporary table structure for view `claimDevelopment`
--

DROP TABLE IF EXISTS `claimDevelopment`;
/*!50001 DROP VIEW IF EXISTS `claimDevelopment`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `claimDevelopment` AS SELECT 
 1 AS `id`,
 1 AS `claimFk`,
 1 AS `claimResponsibleFk`,
 1 AS `workerFk`,
 1 AS `claimReasonFk`,
 1 AS `claimResultFk`,
 1 AS `claimRedeliveryFk`,
 1 AS `claimDestinationFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `claimEnd`
--

DROP TABLE IF EXISTS `claimEnd`;
/*!50001 DROP VIEW IF EXISTS `claimEnd`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `claimEnd` AS SELECT 
 1 AS `id`,
 1 AS `saleFk`,
 1 AS `claimFk`,
 1 AS `workerFk`,
 1 AS `claimDestinationFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `claimLog`
--

DROP TABLE IF EXISTS `claimLog`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `claimLog` (
  `id` int(11) NOT NULL,
  `originFk` int(10) unsigned NOT NULL,
  `userFk` int(10) unsigned DEFAULT NULL,
  `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL,
  `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `description` text CHARACTER SET utf8,
  `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `oldInstance` text COLLATE utf8_unicode_ci,
  `newInstance` text COLLATE utf8_unicode_ci,
  `changedModelId` int(11) DEFAULT NULL,
  `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `originFk` (`originFk`),
  KEY `userFk` (`userFk`),
  CONSTRAINT `claimOriginFk` FOREIGN KEY (`originFk`) REFERENCES `vn2008`.`cl_main` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `claimUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `claimRatio`
--

DROP TABLE IF EXISTS `claimRatio`;
/*!50001 DROP VIEW IF EXISTS `claimRatio`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `claimRatio` AS SELECT 
 1 AS `clientFk`,
 1 AS `yearSale`,
 1 AS `claimAmount`,
 1 AS `claimingRate`,
 1 AS `priceIncreasing`,
 1 AS `packingRate`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `claimReason`
--

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

--
-- Temporary table structure for view `claimRedelivery`
--

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

--
-- Temporary table structure for view `claimResponsible`
--

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

--
-- Temporary table structure for view `claimResult`
--

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

--
-- Temporary table structure for view `claimState`
--

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

--
-- Temporary table structure for view `client`
--

DROP TABLE IF EXISTS `client`;
/*!50001 DROP VIEW IF EXISTS `client`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `client` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `fi`,
 1 AS `socialName`,
 1 AS `contact`,
 1 AS `street`,
 1 AS `city`,
 1 AS `postcode`,
 1 AS `phone`,
 1 AS `mobile`,
 1 AS `fax`,
 1 AS `isRelevant`,
 1 AS `email`,
 1 AS `iban`,
 1 AS `dueDay`,
 1 AS `accountingAccount`,
 1 AS `isEqualizated`,
 1 AS `provinceFk`,
 1 AS `hasToInvoice`,
 1 AS `credit`,
 1 AS `countryFk`,
 1 AS `isActive`,
 1 AS `gestdocFk`,
 1 AS `quality`,
 1 AS `payMethodFk`,
 1 AS `created`,
 1 AS `isToBeMailed`,
 1 AS `contactChannelFk`,
 1 AS `hasSepaVnl`,
 1 AS `hasCoreVnl`,
 1 AS `hasCoreVnh`,
 1 AS `hasLcr`,
 1 AS `defaultAddressFk`,
 1 AS `riskCalculated`,
 1 AS `clientTypeFk`,
 1 AS `mailAddress`,
 1 AS `cplusTerIdNifFk`,
 1 AS `hasToInvoiceByAddress`,
 1 AS `isTaxDataChecked`,
 1 AS `isFreezed`,
 1 AS `creditInsurance`,
 1 AS `isCreatedAsServed`,
 1 AS `hasInvoiceSimplified`,
 1 AS `salesPersonFk`,
 1 AS `isVies`,
 1 AS `eypbc`,
 1 AS `bankEntityFk`,
 1 AS `typeFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `clientChain`
--

DROP TABLE IF EXISTS `clientChain`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientChain` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `clientFk` int(11) NOT NULL,
  `chainFk` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `clientChain_fk1_idx` (`clientFk`),
  KEY `clientChain_fk2_idx` (`chainFk`),
  CONSTRAINT `clientChain_fk1` FOREIGN KEY (`clientFk`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `clientChain_fk2` FOREIGN KEY (`chainFk`) REFERENCES `chain` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `clientContact`
--

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

--
-- Temporary table structure for view `clientCredit`
--

DROP TABLE IF EXISTS `clientCredit`;
/*!50001 DROP VIEW IF EXISTS `clientCredit`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `clientCredit` AS SELECT 
 1 AS `id`,
 1 AS `clientFk`,
 1 AS `workerFk`,
 1 AS `amount`,
 1 AS `created`*/;
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 */;

--
-- Temporary table structure for view `clientDefaultCompany`
--

DROP TABLE IF EXISTS `clientDefaultCompany`;
/*!50001 DROP VIEW IF EXISTS `clientDefaultCompany`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `clientDefaultCompany` AS SELECT 
 1 AS `id`,
 1 AS `clientFk`,
 1 AS `companyFk`,
 1 AS `started`,
 1 AS `finished`*/;
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 DEFAULT NULL,
  `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL,
  `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `description` text CHARACTER SET utf8,
  `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `oldInstance` text COLLATE utf8_unicode_ci,
  `newInstance` text COLLATE utf8_unicode_ci,
  `changedModelId` int(11) DEFAULT NULL,
  `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `originFk` (`originFk`),
  KEY `userFk` (`userFk`),
  CONSTRAINT `clientLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `clientLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=209402 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `clientManaCache`
--

DROP TABLE IF EXISTS `clientManaCache`;
/*!50001 DROP VIEW IF EXISTS `clientManaCache`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `clientManaCache` AS SELECT 
 1 AS `clientFk`,
 1 AS `mana`,
 1 AS `dated`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `clientObservation`
--

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

--
-- Table structure for table `clientProtected`
--

DROP TABLE IF EXISTS `clientProtected`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientProtected` (
  `clientFk` int(11) NOT NULL,
  `workerFk` int(11) NOT NULL,
  `isValidated` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`clientFk`),
  KEY `clientProtected_fk2_idx` (`workerFk`),
  CONSTRAINT `clientProtected_fk1` FOREIGN KEY (`clientFk`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `clientProtected_fk2` FOREIGN KEY (`workerFk`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Lista de clientes y comerciales que no se van a ver afectados por las desagsignaciones mensuales automaticas';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `clientRisk`
--

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

--
-- Temporary table structure for view `clientSample`
--

DROP TABLE IF EXISTS `clientSample`;
/*!50001 DROP VIEW IF EXISTS `clientSample`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `clientSample` AS SELECT 
 1 AS `id`,
 1 AS `clientFk`,
 1 AS `typeFk`,
 1 AS `created`,
 1 AS `workerFk`,
 1 AS `userFk`,
 1 AS `companyFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `clientType`
--

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

--
-- Temporary table structure for view `color`
--

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

--
-- Temporary table structure for view `company`
--

DROP TABLE IF EXISTS `company`;
/*!50001 DROP VIEW IF EXISTS `company`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `company` AS SELECT 
 1 AS `id`,
 1 AS `code`,
 1 AS `supplierAccountFk`,
 1 AS `workerManagerFk`,
 1 AS `sage200Company`,
 1 AS `footnotes`,
 1 AS `phytosanitary`,
 1 AS `companyCode`,
 1 AS `isDefaulter`,
 1 AS `expired`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `comparative`
--

DROP TABLE IF EXISTS `comparative`;
/*!50001 DROP VIEW IF EXISTS `comparative`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `comparative` AS SELECT 
 1 AS `timePeriod`,
 1 AS `itemFk`,
 1 AS `warehouseFk`,
 1 AS `quantity`,
 1 AS `price`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `comparativeFilter`
--

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

--
-- Temporary table structure for view `componentRate`
--

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

--
-- Temporary table structure for view `componentTypeRate`
--

DROP TABLE IF EXISTS `componentTypeRate`;
/*!50001 DROP VIEW IF EXISTS `componentTypeRate`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `componentTypeRate` AS SELECT 
 1 AS `id`,
 1 AS `type`,
 1 AS `base`*/;
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',
  `ASIEN` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `contactChannel`
--

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

--
-- Temporary table structure for view `coolerPath`
--

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

--
-- Temporary table structure for view `coolerPathDetail`
--

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

--
-- Temporary table structure for view `country`
--

DROP TABLE IF EXISTS `country`;
/*!50001 DROP VIEW IF EXISTS `country`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `country` AS SELECT 
 1 AS `id`,
 1 AS `country`,
 1 AS `CEE`,
 1 AS `isUeeMember`,
 1 AS `code`,
 1 AS `currencyFk`,
 1 AS `politicalCountryFk`,
 1 AS `geoFk`*/;
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=3130 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=2694 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 ;

--
-- Temporary table structure for view `currency`
--

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

--
-- Table structure for table `dayMinute`
--

DROP TABLE IF EXISTS `dayMinute`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dayMinute` (
  `id` int(10) unsigned NOT NULL,
  `hh` int(10) unsigned NOT NULL,
  `mm` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `dayMinute_ix1` (`hh`),
  KEY `dayMinute_ix2` (`mm`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='sirve de soporte para el calculo presencial de los trabjadores';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `defaulter`
--

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

--
-- Temporary table structure for view `deliveryMethod`
--

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

--
-- Temporary table structure for view `department`
--

DROP TABLE IF EXISTS `department`;
/*!50001 DROP VIEW IF EXISTS `department`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `department` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `fatherFk`,
 1 AS `isProduction`,
 1 AS `lft`,
 1 AS `rgt`,
 1 AS `isSelected`,
 1 AS `depth`,
 1 AS `sons`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `departmentTree`
--

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

--
-- Temporary table structure for view `dms`
--

DROP TABLE IF EXISTS `dms`;
/*!50001 DROP VIEW IF EXISTS `dms`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `dms` AS SELECT 
 1 AS `id`,
 1 AS `dmsTypeFk`,
 1 AS `file`,
 1 AS `workerFk`,
 1 AS `warehouseFk`,
 1 AS `companyFk`,
 1 AS `priority`,
 1 AS `hasFile`,
 1 AS `reference`,
 1 AS `description`,
 1 AS `created`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `dmsType`
--

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

--
-- Temporary table structure for view `doc`
--

DROP TABLE IF EXISTS `doc`;
/*!50001 DROP VIEW IF EXISTS `doc`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `doc` AS SELECT 
 1 AS `id`,
 1 AS `sref`,
 1 AS `brief`,
 1 AS `companyFk`,
 1 AS `order`,
 1 AS `file`,
 1 AS `original`,
 1 AS `workerFk`,
 1 AS `created`,
 1 AS `warehouseFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `dua`
--

DROP TABLE IF EXISTS `dua`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dua` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `code` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `awbFk` smallint(11) unsigned NOT NULL,
  `issued` date DEFAULT NULL,
  `operated` date DEFAULT NULL,
  `booked` date DEFAULT NULL,
  `bookEntried` date DEFAULT NULL,
  `gestdocFk` int(11) DEFAULT NULL,
  `customsValue` decimal(10,2) DEFAULT NULL,
  `companyFk` smallint(5) unsigned NOT NULL DEFAULT '442',
  `ASIEN` double DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_awb_dua_awb_idx` (`awbFk`),
  KEY `fk_dua_gestdoc1_idx` (`gestdocFk`),
  KEY `dua_fk4_idx` (`companyFk`),
  CONSTRAINT `dua_fk1` FOREIGN KEY (`gestdocFk`) REFERENCES `vn2008`.`gestdoc` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `dua_fk2` FOREIGN KEY (`awbFk`) REFERENCES `vn2008`.`awb` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `dua_fk4` FOREIGN KEY (`companyFk`) REFERENCES `vn2008`.`empresa` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3866 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `duaEntry`
--

DROP TABLE IF EXISTS `duaEntry`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `duaEntry` (
  `duaFk` int(11) NOT NULL,
  `entryFk` int(11) NOT NULL,
  `value` decimal(10,2) DEFAULT NULL,
  `customsValue` decimal(10,2) DEFAULT NULL,
  `euroValue` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`duaFk`,`entryFk`),
  KEY `fk_duaEntry_dua1_idx` (`duaFk`),
  KEY `fk_duaEntry_Entradas1_idx` (`entryFk`),
  CONSTRAINT `fk_duaEntry_Entradas1` FOREIGN KEY (`entryFk`) REFERENCES `vn2008`.`Entradas` (`Id_Entrada`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fk_duaEntry_dua1` FOREIGN KEY (`duaFk`) REFERENCES `dua` (`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 `duaIntrastat`
--

DROP TABLE IF EXISTS `duaIntrastat`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `duaIntrastat` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `duaFk` int(11) NOT NULL,
  `intrastatFk` int(8) unsigned NOT NULL,
  `amount` decimal(10,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`id`),
  KEY `duaIntrastat_fk1_idx` (`intrastatFk`),
  KEY `duaIntrastat_fk2_idx` (`duaFk`),
  CONSTRAINT `duaIntrastat_fk1` FOREIGN KEY (`intrastatFk`) REFERENCES `vn2008`.`Intrastat` (`Codintrastat`) ON UPDATE CASCADE,
  CONSTRAINT `duaIntrastat_fk2` FOREIGN KEY (`duaFk`) REFERENCES `dua` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=6058 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `duaInvoiceIn`
--

DROP TABLE IF EXISTS `duaInvoiceIn`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `duaInvoiceIn` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `duaFk` int(11) NOT NULL,
  `invoiceInFk` mediumint(8) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `duaFk_UNIQUE` (`duaFk`,`invoiceInFk`),
  KEY `duaInvoiceIn_fk1_idx` (`duaFk`),
  KEY `duaInvoiceIn_fk2_idx` (`invoiceInFk`),
  CONSTRAINT `duaInvoiceIn_fk1` FOREIGN KEY (`duaFk`) REFERENCES `dua` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `duaInvoiceIn_fk2` FOREIGN KEY (`invoiceInFk`) REFERENCES `vn2008`.`recibida` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4765 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Facturas asociadas a la declaración aduanera, básicamente la del agente transitario';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `duaTax`
--

DROP TABLE IF EXISTS `duaTax`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `duaTax` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `duaFk` int(11) NOT NULL,
  `supplierFk` int(11) NOT NULL,
  `taxClassFk` tinyint(3) unsigned NOT NULL,
  `base` decimal(10,2) NOT NULL,
  `rate` decimal(5,2) NOT NULL,
  `tax` decimal(10,2) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_dua_tax_awb_dua1_idx` (`duaFk`),
  KEY `duaTax_fk2_idx` (`supplierFk`),
  KEY `duaTax_fk3_idx` (`taxClassFk`),
  CONSTRAINT `duaTax_fk1` FOREIGN KEY (`duaFk`) REFERENCES `dua` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `duaTax_fk2` FOREIGN KEY (`supplierFk`) REFERENCES `vn2008`.`Proveedores` (`Id_Proveedor`) ON UPDATE CASCADE,
  CONSTRAINT `duaTax_fk3` FOREIGN KEY (`taxClassFk`) REFERENCES `vn2008`.`iva_group` (`iva_group_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5312 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `ediGenus`
--

DROP TABLE IF EXISTS `ediGenus`;
/*!50001 DROP VIEW IF EXISTS `ediGenus`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ediGenus` AS SELECT 
 1 AS `id`,
 1 AS `latinGenusName`,
 1 AS `entried`,
 1 AS `dued`,
 1 AS `modified`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `ediSpecie`
--

DROP TABLE IF EXISTS `ediSpecie`;
/*!50001 DROP VIEW IF EXISTS `ediSpecie`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ediSpecie` AS SELECT 
 1 AS `id`,
 1 AS `genusFk`,
 1 AS `latinSpeciesName`,
 1 AS `entried`,
 1 AS `dued`,
 1 AS `modified`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `entity`
--

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

--
-- Temporary table structure for view `entry`
--

DROP TABLE IF EXISTS `entry`;
/*!50001 DROP VIEW IF EXISTS `entry`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `entry` AS SELECT 
 1 AS `id`,
 1 AS `supplierFk`,
 1 AS `ref`,
 1 AS `isInventory`,
 1 AS `isConfirmed`,
 1 AS `isOrdered`,
 1 AS `isRaid`,
 1 AS `commission`,
 1 AS `created`,
 1 AS `evaNotes`,
 1 AS `travelFk`,
 1 AS `currencyFk`,
 1 AS `companyFk`,
 1 AS `gestDocFk`,
 1 AS `invoiceInFk`*/;
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 CHARACTER SET utf8,
  PRIMARY KEY (`id`),
  KEY `logEntry_ibfk_1` (`originFk`),
  KEY `entryLog_ibfk_2` (`userFk`),
  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 UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=136785 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `envialiaAgency`
--

DROP TABLE IF EXISTS `envialiaAgency`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `envialiaAgency` (
  `id` varchar(6) COLLATE utf8_unicode_ci NOT NULL,
  `route` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `agencyName` varchar(45) 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 `envialiaCity`
--

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

--
-- Table structure for table `envialiaConfig`
--

DROP TABLE IF EXISTS `envialiaConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `envialiaConfig` (
  `serviceType` varchar(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT '024' COMMENT 'Tipo de servicio en horas. 024 -> servicio las 24h',
  `numBox` varchar(3) COLLATE utf8_unicode_ci DEFAULT '001' COMMENT 'cajas por envio',
  `startRange` bigint(25) DEFAULT NULL COMMENT 'Principio del rango que nos proporciona enviaría',
  `endRange` bigint(25) DEFAULT NULL COMMENT 'limite del rango que nos proporciona enviaría',
  `cargoAgency` varchar(25) COLLATE utf8_unicode_ci DEFAULT '004666' COMMENT 'numero de verdnatura dado por enviaría',
  `actualNumber` bigint(25) DEFAULT NULL COMMENT 'Numero actual de etiquetas imprimidas , comprimido entre startRange y endRange, ',
  `isAlreadyNotified` int(1) NOT NULL DEFAULT '0' COMMENT 'Booleano para que el evento vn.envialiaRangeChecker compruebe si se a enviado una notificación\n',
  `notificationThrehold` int(11) DEFAULT NULL COMMENT 'Umbral para avisar a enviaría de reseetar el startRange y endRange\nSe avisara a enviaría si el umbral + el actualNumber es superior a endRange\n',
  PRIMARY KEY (`serviceType`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `especialPrice`
--

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

--
-- Temporary table structure for view `exchangeInsurance`
--

DROP TABLE IF EXISTS `exchangeInsurance`;
/*!50001 DROP VIEW IF EXISTS `exchangeInsurance`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `exchangeInsurance` AS SELECT 
 1 AS `id`,
 1 AS `amount`,
 1 AS `dated`,
 1 AS `finished`,
 1 AS `entityFk`,
 1 AS `ref`,
 1 AS `rate`,
 1 AS `companyFk`,
 1 AS `financialProductTypefk`,
 1 AS `upperBarrier`,
 1 AS `lowerBarrier`,
 1 AS `strike`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `exchangeInsuranceEntry`
--

DROP TABLE IF EXISTS `exchangeInsuranceEntry`;
/*!50001 DROP VIEW IF EXISTS `exchangeInsuranceEntry`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `exchangeInsuranceEntry` AS SELECT 
 1 AS `dated`,
 1 AS `Dolares`,
 1 AS `rate`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `exchangeInsuranceIn`
--

DROP TABLE IF EXISTS `exchangeInsuranceIn`;
/*!50001 DROP VIEW IF EXISTS `exchangeInsuranceIn`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `exchangeInsuranceIn` AS SELECT 
 1 AS `dated`,
 1 AS `amount`,
 1 AS `rate`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `exchangeInsuranceInPrevious`
--

DROP TABLE IF EXISTS `exchangeInsuranceInPrevious`;
/*!50001 DROP VIEW IF EXISTS `exchangeInsuranceInPrevious`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `exchangeInsuranceInPrevious` AS SELECT 
 1 AS `dated`,
 1 AS `amount`,
 1 AS `rate`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `exchangeInsuranceOut`
--

DROP TABLE IF EXISTS `exchangeInsuranceOut`;
/*!50001 DROP VIEW IF EXISTS `exchangeInsuranceOut`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `exchangeInsuranceOut` AS SELECT 
 1 AS `received`,
 1 AS `divisa`,
 1 AS `rate`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `exchangeReportSource`
--

DROP TABLE IF EXISTS `exchangeReportSource`;
/*!50001 DROP VIEW IF EXISTS `exchangeReportSource`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `exchangeReportSource` AS SELECT 
 1 AS `dated`,
 1 AS `amountIn`,
 1 AS `rateIn`,
 1 AS `amountOut`,
 1 AS `rateOut`,
 1 AS `amountEntry`,
 1 AS `rateEntry`,
 1 AS `rateECB`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `exchangeReportSourcePrevious`
--

DROP TABLE IF EXISTS `exchangeReportSourcePrevious`;
/*!50001 DROP VIEW IF EXISTS `exchangeReportSourcePrevious`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `exchangeReportSourcePrevious` AS SELECT 
 1 AS `dated`,
 1 AS `amountIn`,
 1 AS `rateIn`,
 1 AS `amountOut`,
 1 AS `rateOut`,
 1 AS `amountEntry`,
 1 AS `rateEntry`*/;
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 */;

--
-- Temporary table structure for view `expedition`
--

DROP TABLE IF EXISTS `expedition`;
/*!50001 DROP VIEW IF EXISTS `expedition`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `expedition` AS SELECT 
 1 AS `id`,
 1 AS `agencyModeFk`,
 1 AS `ticketFk`,
 1 AS `isBox`,
 1 AS `created`,
 1 AS `itemFk`,
 1 AS `counter`,
 1 AS `checked`,
 1 AS `workerFk`,
 1 AS `externalId`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `expeditionBoxVol`
--

DROP TABLE IF EXISTS `expeditionBoxVol`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expeditionBoxVol` (
  `boxFk` int(11) NOT NULL,
  `m3` double NOT NULL,
  `ratio` double NOT NULL,
  PRIMARY KEY (`boxFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Establece el volumen de cada servicio para poder comparar el teorico y el real en el control de portes';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `expence`
--

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

--
-- Temporary table structure for view `firstTicketShipped`
--

DROP TABLE IF EXISTS `firstTicketShipped`;
/*!50001 DROP VIEW IF EXISTS `firstTicketShipped`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `firstTicketShipped` AS SELECT 
 1 AS `shipped`,
 1 AS `clientFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `floraHollandBuyedItems`
--

DROP TABLE IF EXISTS `floraHollandBuyedItems`;
/*!50001 DROP VIEW IF EXISTS `floraHollandBuyedItems`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `floraHollandBuyedItems` AS SELECT 
 1 AS `itemFk`,
 1 AS `longName`,
 1 AS `quantity`,
 1 AS `buyingValue`,
 1 AS `landed`,
 1 AS `companyFk`*/;
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 */;

--
-- Temporary table structure for view `grant`
--

DROP TABLE IF EXISTS `grant`;
/*!50001 DROP VIEW IF EXISTS `grant`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `grant` AS SELECT 
 1 AS `group`,
 1 AS `worker`,
 1 AS `company`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `grantGroup`
--

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

--
-- Temporary table structure for view `greuge`
--

DROP TABLE IF EXISTS `greuge`;
/*!50001 DROP VIEW IF EXISTS `greuge`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `greuge` AS SELECT 
 1 AS `id`,
 1 AS `clientFk`,
 1 AS `description`,
 1 AS `amount`,
 1 AS `shipped`,
 1 AS `created`,
 1 AS `greugeTypeFk`,
 1 AS `ticketFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `greugeType`
--

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

--
-- Temporary table structure for view `holiday`
--

DROP TABLE IF EXISTS `holiday`;
/*!50001 DROP VIEW IF EXISTS `holiday`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `holiday` AS SELECT 
 1 AS `holidayDetailFk`,
 1 AS `holidayTypeFk`,
 1 AS `workCenterFk`,
 1 AS `dated`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `holidayDetail`
--

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

--
-- Temporary table structure for view `holidayLegend`
--

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

--
-- Temporary table structure for view `holidayType`
--

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

--
-- Temporary table structure for view `ink`
--

DROP TABLE IF EXISTS `ink`;
/*!50001 DROP VIEW IF EXISTS `ink`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ink` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `picture`,
 1 AS `showOrder`*/;
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 */;

--
-- Temporary table structure for view `inkL10n`
--

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

--
-- Temporary table structure for view `intrastat`
--

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

--
-- Table structure for table `inventoryFailure`
--

DROP TABLE IF EXISTS `inventoryFailure`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `inventoryFailure` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dated` date NOT NULL,
  `itemFk` int(11) NOT NULL,
  `quantity` int(11) NOT NULL,
  `value` decimal(10,2) NOT NULL,
  `warehouseFk` smallint(6) unsigned NOT NULL,
  `throwerFk` int(11) DEFAULT NULL,
  `guiltyFk` int(11) DEFAULT NULL,
  `causeFk` int(11) DEFAULT NULL,
  `explanation` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `inventoryFailure_fk1_idx` (`itemFk`),
  KEY `inventoryFailure_fk2_idx` (`throwerFk`),
  KEY `inventoryFailure_fk_idx` (`guiltyFk`),
  KEY `inventoryFailure_fk4_idx` (`warehouseFk`),
  KEY `inventoryFailure_fk5_idx` (`causeFk`),
  CONSTRAINT `inventoryFailure_fk1` FOREIGN KEY (`itemFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `inventoryFailure_fk2` FOREIGN KEY (`throwerFk`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `inventoryFailure_fk3` FOREIGN KEY (`guiltyFk`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `inventoryFailure_fk4` FOREIGN KEY (`warehouseFk`) REFERENCES `vn2008`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `inventoryFailure_fk5` FOREIGN KEY (`causeFk`) REFERENCES `inventoryFailureCause` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=11720 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `inventoryFailureCause`
--

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

--
-- Temporary table structure for view `invoiceCorrection`
--

DROP TABLE IF EXISTS `invoiceCorrection`;
/*!50001 DROP VIEW IF EXISTS `invoiceCorrection`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `invoiceCorrection` AS SELECT 
 1 AS `correctingFk`,
 1 AS `correctedFk`,
 1 AS `cplusRectificationTypeFk`,
 1 AS `cplusInvoiceType477Fk`,
 1 AS `invoiceCorrectionTypeFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `invoiceCorrectionDataSource`
--

DROP TABLE IF EXISTS `invoiceCorrectionDataSource`;
/*!50001 DROP VIEW IF EXISTS `invoiceCorrectionDataSource`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `invoiceCorrectionDataSource` AS SELECT 
 1 AS `itemFk`,
 1 AS `quantity`,
 1 AS `concept`,
 1 AS `price`,
 1 AS `discount`,
 1 AS `refFk`,
 1 AS `saleFk`,
 1 AS `shipped`*/;
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 */;

--
-- Temporary table structure for view `invoiceIn`
--

DROP TABLE IF EXISTS `invoiceIn`;
/*!50001 DROP VIEW IF EXISTS `invoiceIn`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `invoiceIn` AS SELECT 
 1 AS `id`,
 1 AS `serialNumber`,
 1 AS `serial`,
 1 AS `supplierFk`,
 1 AS `issued`,
 1 AS `supplierRef`,
 1 AS `isBooked`,
 1 AS `currencyFk`,
 1 AS `created`,
 1 AS `companyFk`,
 1 AS `docFk`,
 1 AS `booked`,
 1 AS `operated`,
 1 AS `cplusInvoiceType472Fk`,
 1 AS `cplusRectificationTypeFk`,
 1 AS `cplusSubjectOpFk`,
 1 AS `cplusTaxBreakFk`,
 1 AS `cplusTrascendency472Fk`,
 1 AS `bookEntried`,
 1 AS `isVatDeductible`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `invoiceInAwb`
--

DROP TABLE IF EXISTS `invoiceInAwb`;
/*!50001 DROP VIEW IF EXISTS `invoiceInAwb`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `invoiceInAwb` AS SELECT 
 1 AS `invoiceInFk`,
 1 AS `awbFk`,
 1 AS `dua`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `invoiceInDueDay`
--

DROP TABLE IF EXISTS `invoiceInDueDay`;
/*!50001 DROP VIEW IF EXISTS `invoiceInDueDay`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `invoiceInDueDay` AS SELECT 
 1 AS `id`,
 1 AS `invoiceInFk`,
 1 AS `dueDated`,
 1 AS `bankFk`,
 1 AS `amount`,
 1 AS `foreignValue`,
 1 AS `created`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `invoiceInEntry`
--

DROP TABLE IF EXISTS `invoiceInEntry`;
/*!50001 DROP VIEW IF EXISTS `invoiceInEntry`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `invoiceInEntry` AS SELECT 
 1 AS `id`,
 1 AS `invoiceInFk`,
 1 AS `entryFk`,
 1 AS `percentage`,
 1 AS `invoiceInAwbFk`,
 1 AS `isBooked`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `invoiceInIntrastat`
--

DROP TABLE IF EXISTS `invoiceInIntrastat`;
/*!50001 DROP VIEW IF EXISTS `invoiceInIntrastat`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `invoiceInIntrastat` AS SELECT 
 1 AS `invoiceInFk`,
 1 AS `intrastatFk`,
 1 AS `amount`*/;
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) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`code`),
  KEY `InvoiceInSerial_Fk1_idx` (`cplusTerIdNifFk`),
  KEY `InvoiceInSerialTaxArea_idx` (`taxAreaFk`),
  CONSTRAINT `InvoiceInSerialTaxArea` FOREIGN KEY (`taxAreaFk`) REFERENCES `taxArea` (`code`) ON UPDATE CASCADE,
  CONSTRAINT `InvoiceInSerial_Fk1` FOREIGN KEY (`cplusTerIdNifFk`) REFERENCES `cplusTerIdNif` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `invoiceInTax`
--

DROP TABLE IF EXISTS `invoiceInTax`;
/*!50001 DROP VIEW IF EXISTS `invoiceInTax`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `invoiceInTax` AS SELECT 
 1 AS `id`,
 1 AS `invoiceInFk`,
 1 AS `taxCodeFk`,
 1 AS `taxableBase`,
 1 AS `expenceFk`,
 1 AS `foreignValue`,
 1 AS `created`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `invoiceInTaxBookingAccount`
--

DROP TABLE IF EXISTS `invoiceInTaxBookingAccount`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceInTaxBookingAccount` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `effectived` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `account` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `taxAreaFk` varchar(15) CHARACTER SET utf8 NOT NULL,
  `priority` int(2) unsigned DEFAULT NULL,
  `taxClassFk` tinyint(3) unsigned NOT NULL DEFAULT '1',
  `countryFk` mediumint(8) unsigned NOT NULL DEFAULT '1',
  `rate` decimal(5,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`id`),
  KEY `invoiceInTaxBookingAccount_fk1_idx` (`taxAreaFk`),
  KEY `invoiceInTaxBookingAccount_fk2_idx` (`taxClassFk`),
  KEY `invoiceInTaxBookingAccount_fk3_idx` (`countryFk`),
  CONSTRAINT `invoiceInTaxBookingAccount_fk1` FOREIGN KEY (`taxAreaFk`) REFERENCES `taxArea` (`code`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `invoiceInTaxBookingAccount_fk2` FOREIGN KEY (`taxClassFk`) REFERENCES `vn2008`.`iva_group` (`iva_group_id`) ON UPDATE CASCADE,
  CONSTRAINT `invoiceInTaxBookingAccount_fk3` FOREIGN KEY (`countryFk`) REFERENCES `vn2008`.`Paises` (`Id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `invoiceOut`
--

DROP TABLE IF EXISTS `invoiceOut`;
/*!50001 DROP VIEW IF EXISTS `invoiceOut`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `invoiceOut` AS SELECT 
 1 AS `id`,
 1 AS `ref`,
 1 AS `serial`,
 1 AS `issued`,
 1 AS `amount`,
 1 AS `clientFk`,
 1 AS `created`,
 1 AS `companyFk`,
 1 AS `dued`,
 1 AS `booked`,
 1 AS `bankFk`,
 1 AS `cplusInvoiceType477Fk`,
 1 AS `cplusTaxBreakFk`,
 1 AS `cplusSubjectOpFk`,
 1 AS `cplusTrascendency477Fk`,
 1 AS `pdf`*/;
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=110733 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) CHARACTER SET utf8 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 `invoiceOutSeriaTaxArea` FOREIGN KEY (`taxAreaFk`) REFERENCES `taxArea` (`code`) ON UPDATE 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=1086225 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `item`
--

DROP TABLE IF EXISTS `item`;
/*!50001 DROP VIEW IF EXISTS `item`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `item` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `typeFk`,
 1 AS `size`,
 1 AS `inkFk`,
 1 AS `category`,
 1 AS `stems`,
 1 AS `originFk`,
 1 AS `description`,
 1 AS `producerFk`,
 1 AS `intrastatFk`,
 1 AS `isOnOffer`,
 1 AS `box`,
 1 AS `expenceFk`,
 1 AS `isBargain`,
 1 AS `comment`,
 1 AS `relevancy`,
 1 AS `image`,
 1 AS `generic`,
 1 AS `density`,
 1 AS `taxClassFk`,
 1 AS `minPrice`,
 1 AS `hasMinPrice`,
 1 AS `isActive`,
 1 AS `longName`,
 1 AS `subName`,
 1 AS `tag5`,
 1 AS `value5`,
 1 AS `tag6`,
 1 AS `value6`,
 1 AS `tag7`,
 1 AS `value7`,
 1 AS `tag8`,
 1 AS `value8`,
 1 AS `tag9`,
 1 AS `value9`,
 1 AS `tag10`,
 1 AS `value10`,
 1 AS `minimum`,
 1 AS `upToDown`,
 1 AS `compression`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `itemBarcode`
--

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

--
-- Temporary table structure for view `itemBotanical`
--

DROP TABLE IF EXISTS `itemBotanical`;
/*!50001 DROP VIEW IF EXISTS `itemBotanical`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemBotanical` AS SELECT 
 1 AS `itemFk`,
 1 AS `botanical`,
 1 AS `genusFk`,
 1 AS `specieFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `itemBotanicalWithGenus`
--

DROP TABLE IF EXISTS `itemBotanicalWithGenus`;
/*!50001 DROP VIEW IF EXISTS `itemBotanicalWithGenus`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemBotanicalWithGenus` AS SELECT 
 1 AS `itemFk`,
 1 AS `ediBotanic`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `itemCategory`
--

DROP TABLE IF EXISTS `itemCategory`;
/*!50001 DROP VIEW IF EXISTS `itemCategory`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemCategory` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `display`,
 1 AS `color`,
 1 AS `icon`,
 1 AS `merchandise`,
 1 AS `order`,
 1 AS `shortLife`*/;
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 */;

--
-- Temporary table structure for view `itemCategoryL10n`
--

DROP TABLE IF EXISTS `itemCategoryL10n`;
/*!50001 DROP VIEW IF EXISTS `itemCategoryL10n`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemCategoryL10n` AS SELECT 
 1 AS `id`,
 1 AS `name`*/;
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 `itemFreeNumber`
--

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

--
-- Table structure for table `itemLog`
--

DROP TABLE IF EXISTS `itemLog`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemLog` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `originFk` int(11) NOT NULL,
  `userFk` int(10) unsigned DEFAULT NULL,
  `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL,
  `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `description` text CHARACTER SET utf8,
  `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `oldInstance` text COLLATE utf8_unicode_ci,
  `newInstance` text COLLATE utf8_unicode_ci,
  `changedModelId` int(11) DEFAULT NULL,
  `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `itemLogItemFk_idx` (`originFk`),
  KEY `itemLogUserFk_idx` (`userFk`),
  CONSTRAINT `itemLogItemFk` FOREIGN KEY (`originFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `itemLogUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=18231 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `itemPlacement`
--

DROP TABLE IF EXISTS `itemPlacement`;
/*!50001 DROP VIEW IF EXISTS `itemPlacement`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemPlacement` AS SELECT 
 1 AS `id`,
 1 AS `itemFk`,
 1 AS `warehouseFk`,
 1 AS `code`,
 1 AS `reserve`,
 1 AS `pickable`,
 1 AS `modificationDate`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `itemPlacementSupply`
--

DROP TABLE IF EXISTS `itemPlacementSupply`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemPlacementSupply` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `itemFk` int(11) NOT NULL,
  `quantity` decimal(10,0) NOT NULL DEFAULT '0',
  `priority` int(10) unsigned NOT NULL DEFAULT '0',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `userFk` int(10) unsigned NOT NULL COMMENT 'Persona que crea la orden',
  `repoUserFk` int(10) unsigned DEFAULT NULL COMMENT 'Reponedor que la tiene asignada',
  PRIMARY KEY (`id`),
  KEY `itemPlacementSupply_fk1_idx` (`itemFk`),
  KEY `itemPlacementSupply_fk2_idx` (`userFk`),
  KEY `itemPlacementSupply_fk2_idx1` (`repoUserFk`),
  CONSTRAINT `itemPlacementSupply_fk1` FOREIGN KEY (`itemFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `itemPlacementSupply_fk2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `itemPlacementSupply_fk3` FOREIGN KEY (`repoUserFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=20850 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Lista de nichos de picking que hay que reponer';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `itemPlacementSupplyList`
--

DROP TABLE IF EXISTS `itemPlacementSupplyList`;
/*!50001 DROP VIEW IF EXISTS `itemPlacementSupplyList`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemPlacementSupplyList` AS SELECT 
 1 AS `id`,
 1 AS `itemFk`,
 1 AS `quantity`,
 1 AS `priority`,
 1 AS `created`,
 1 AS `userFk`,
 1 AS `repoUserFk`,
 1 AS `saldo`,
 1 AS `longName`,
 1 AS `subName`,
 1 AS `size`,
 1 AS `workerCode`,
 1 AS `repoCode`,
 1 AS `parking`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `itemRepo`
--

DROP TABLE IF EXISTS `itemRepo`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemRepo` (
  `itemFk` int(11) NOT NULL,
  `quantity` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`itemFk`),
  CONSTRAINT `itemRepo_fk1` 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 `itemShelving`
--

DROP TABLE IF EXISTS `itemShelving`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemShelving` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `itemFk` int(11) NOT NULL,
  `shelvingFk` varchar(10) CHARACTER SET utf8 NOT NULL,
  `shelve` varchar(2) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'A',
  `deep` int(11) unsigned NOT NULL DEFAULT '1',
  `quantity` decimal(10,0) NOT NULL DEFAULT '0',
  `visible` decimal(10,0) NOT NULL DEFAULT '0',
  `available` decimal(10,0) NOT NULL DEFAULT '0',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `priority` int(11) unsigned DEFAULT NULL COMMENT 'El 0 es la mínima prioridad',
  `grouping` smallint(5) unsigned DEFAULT NULL,
  `packing` int(11) unsigned DEFAULT NULL,
  `packagingFk` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `level` varchar(45) COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  KEY `itemShelving_fk1_idx` (`itemFk`),
  KEY `itemShelving_fk2_idx` (`shelvingFk`),
  KEY `itemShelving_fk3_idx` (`packagingFk`),
  CONSTRAINT `itemShelving_fk1` FOREIGN KEY (`itemFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `itemShelving_fk2` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`code`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `itemShelving_fk3` FOREIGN KEY (`packagingFk`) REFERENCES `vn2008`.`Cubos` (`Id_Cubo`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=85512 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla utilizada para localizar los artículos dentro de los carros. Usado para la gestión del almacén en el altillo ';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `itemShelvingAvailable`
--

DROP TABLE IF EXISTS `itemShelvingAvailable`;
/*!50001 DROP VIEW IF EXISTS `itemShelvingAvailable`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemShelvingAvailable` AS SELECT 
 1 AS `saleFk`,
 1 AS `Modificado`,
 1 AS `ticketFk`,
 1 AS `isPicked`,
 1 AS `itemFk`,
 1 AS `quantity`,
 1 AS `concept`,
 1 AS `size`,
 1 AS `Estado`,
 1 AS `sectorProdPriority`,
 1 AS `available`,
 1 AS `sectorFk`,
 1 AS `matricula`,
 1 AS `parking`,
 1 AS `itemShelving`,
 1 AS `Agency`,
 1 AS `shipped`,
 1 AS `grouping`,
 1 AS `packing`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `itemShelvingAvailableKk`
--

DROP TABLE IF EXISTS `itemShelvingAvailableKk`;
/*!50001 DROP VIEW IF EXISTS `itemShelvingAvailableKk`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemShelvingAvailableKk` AS SELECT 
 1 AS `saleFk`,
 1 AS `Modificado`,
 1 AS `ticketFk`,
 1 AS `isPicked`,
 1 AS `itemFk`,
 1 AS `quantity`,
 1 AS `concept`,
 1 AS `size`,
 1 AS `Estado`,
 1 AS `sectorProdPriority`,
 1 AS `available`,
 1 AS `sectorFk`,
 1 AS `matricula`,
 1 AS `parking`,
 1 AS `itemShelving`,
 1 AS `Agency`,
 1 AS `shipped`,
 1 AS `grouping`,
 1 AS `packing`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `itemShelvingList`
--

DROP TABLE IF EXISTS `itemShelvingList`;
/*!50001 DROP VIEW IF EXISTS `itemShelvingList`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemShelvingList` AS SELECT 
 1 AS `shelvingFk`,
 1 AS `visible`,
 1 AS `created`,
 1 AS `parking`,
 1 AS `itemFk`,
 1 AS `longName`,
 1 AS `size`,
 1 AS `subName`,
 1 AS `parked`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `itemShelvingPlacementSupply`
--

DROP TABLE IF EXISTS `itemShelvingPlacementSupply`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemShelvingPlacementSupply` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `itemShelvingFk` int(10) unsigned NOT NULL,
  `itemPlacementSupplyFk` int(10) unsigned NOT NULL,
  `quantity` decimal(10,0) NOT NULL DEFAULT '0',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `userFk` int(10) unsigned NOT NULL,
  `isPicked` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `itemShelvingPlacementSupply_fk1_idx` (`itemShelvingFk`),
  KEY `itemShelvingPlacementSupply_fk2_idx` (`itemPlacementSupplyFk`),
  KEY `itemShelvingPlacementSupply_fk3_idx` (`userFk`),
  CONSTRAINT `itemShelvingPlacementSupply_fk1` FOREIGN KEY (`itemShelvingFk`) REFERENCES `itemShelving` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `itemShelvingPlacementSupply_fk2` FOREIGN KEY (`itemPlacementSupplyFk`) REFERENCES `itemPlacementSupply` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=18644 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Detalle de los itemShelving afectados por las ordenes de reposicion de nicho';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `itemShelvingPlacementSupplyStock`
--

DROP TABLE IF EXISTS `itemShelvingPlacementSupplyStock`;
/*!50001 DROP VIEW IF EXISTS `itemShelvingPlacementSupplyStock`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemShelvingPlacementSupplyStock` AS SELECT 
 1 AS `itemShelvingFk`,
 1 AS `itemFk`,
 1 AS `quantity`,
 1 AS `packing`,
 1 AS `stock`,
 1 AS `longName`,
 1 AS `size`,
 1 AS `subName`,
 1 AS `shelving`,
 1 AS `parking`,
 1 AS `created`,
 1 AS `priority`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `itemShelvingSale`
--

DROP TABLE IF EXISTS `itemShelvingSale`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemShelvingSale` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `itemShelvingFk` int(10) unsigned NOT NULL,
  `saleFk` int(11) NOT NULL,
  `quantity` decimal(10,0) NOT NULL DEFAULT '0',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `userFk` int(11) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `itemShelvingSale_fk1_idx` (`itemShelvingFk`),
  KEY `itemShelvingSale_fk2_idx` (`saleFk`),
  KEY `itemShelvingSale_fk3_idx` (`userFk`),
  CONSTRAINT `itemShelvingSale_fk1` FOREIGN KEY (`itemShelvingFk`) REFERENCES `itemShelving` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `itemShelvingSale_fk2` FOREIGN KEY (`saleFk`) REFERENCES `vn2008`.`Movimientos` (`Id_Movimiento`) ON UPDATE CASCADE,
  CONSTRAINT `itemShelvingSale_fk3` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=7079 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Detalle del producto que se retira de los carros, relacionando la linea de movimiento correspondiente';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `itemShelvingStock`
--

DROP TABLE IF EXISTS `itemShelvingStock`;
/*!50001 DROP VIEW IF EXISTS `itemShelvingStock`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemShelvingStock` AS SELECT 
 1 AS `itemFk`,
 1 AS `visible`,
 1 AS `packing`,
 1 AS `sector`,
 1 AS `visibleOriginal`,
 1 AS `removed`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `itemShelvingStockRemoved`
--

DROP TABLE IF EXISTS `itemShelvingStockRemoved`;
/*!50001 DROP VIEW IF EXISTS `itemShelvingStockRemoved`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemShelvingStockRemoved` AS SELECT 
 1 AS `itemShelvingFk`,
 1 AS `itemFk`,
 1 AS `removed`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `itemShelvingStock_beta`
--

DROP TABLE IF EXISTS `itemShelvingStock_beta`;
/*!50001 DROP VIEW IF EXISTS `itemShelvingStock_beta`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemShelvingStock_beta` AS SELECT 
 1 AS `itemFk`,
 1 AS `visible`,
 1 AS `packing`,
 1 AS `sector`,
 1 AS `visibleOriginal`,
 1 AS `removed`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `itemShelvingStock_old`
--

DROP TABLE IF EXISTS `itemShelvingStock_old`;
/*!50001 DROP VIEW IF EXISTS `itemShelvingStock_old`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemShelvingStock_old` AS SELECT 
 1 AS `itemFk`,
 1 AS `visible`,
 1 AS `packing`*/;
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(50) COLLATE utf8_unicode_ci NOT NULL,
  `priority` int(2) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `itemFk` (`itemFk`,`tagFk`),
  KEY `tagFk` (`tagFk`,`value`),
  KEY `priorityItem` (`priority`,`itemFk`),
  KEY `value` (`value`),
  CONSTRAINT `itemFK` FOREIGN KEY (`itemFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1178986 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`.`itemTag_AFTER_INSERT` AFTER INSERT ON `itemTag` FOR EACH ROW
proc_label:BEGIN
	IF @isTriggerDisabled THEN
		LEAVE proc_label;
	END IF;
	
    CALL vn.itemRefreshTags(NEW.itemFk);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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`.`itemTag_AFTER_UPDATE` AFTER UPDATE ON `itemTag` FOR EACH ROW
proc_label:BEGIN
	IF @isTriggerDisabled THEN
		LEAVE proc_label;
	END IF;
    
	CALL vn.itemRefreshTags(NEW.itemFk);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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`.`itemTag_AFTER_DELETE` AFTER DELETE ON `itemTag` FOR EACH ROW
proc_label:BEGIN
	IF @isTriggerDisabled THEN
		LEAVE proc_label;
	END IF;
 
	CALL vn.itemRefreshTags(OLD.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 */ ;

--
-- Temporary table structure for view `itemTagged`
--

DROP TABLE IF EXISTS `itemTagged`;
/*!50001 DROP VIEW IF EXISTS `itemTagged`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemTagged` AS SELECT 
 1 AS `itemFk`*/;
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`),
  UNIQUE KEY `itemFk_UNIQUE` (`itemFk`,`countryFk`),
  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=718998 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 */;

--
-- Temporary table structure for view `itemTaxCountrySpain`
--

DROP TABLE IF EXISTS `itemTaxCountrySpain`;
/*!50001 DROP VIEW IF EXISTS `itemTaxCountrySpain`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemTaxCountrySpain` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `typeFk`,
 1 AS `stems`,
 1 AS `description`,
 1 AS `intrastatFk`,
 1 AS `expenceFk`,
 1 AS `comment`,
 1 AS `relevancy`,
 1 AS `image`,
 1 AS `generic`,
 1 AS `taxClassFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `itemType`
--

DROP TABLE IF EXISTS `itemType`;
/*!50001 DROP VIEW IF EXISTS `itemType`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemType` AS SELECT 
 1 AS `id`,
 1 AS `code`,
 1 AS `name`,
 1 AS `categoryFk`,
 1 AS `life`,
 1 AS `workerFk`,
 1 AS `warehouseFk`,
 1 AS `isPackaging`,
 1 AS `density`,
 1 AS `order`*/;
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 */;

--
-- Temporary table structure for view `itemTypeL10n`
--

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

--
-- Table structure for table `itemTypeTag`
--

DROP TABLE IF EXISTS `itemTypeTag`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemTypeTag` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `itemTypeFk` smallint(5) unsigned NOT NULL,
  `tagFk` int(11) NOT NULL,
  `priority` int(2) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `itemTypeFk_UNIQUE` (`itemTypeFk`,`tagFk`),
  KEY `itemTypeTagTipo_idx` (`itemTypeFk`),
  KEY `itemTypeTagTag_idx` (`tagFk`),
  CONSTRAINT `itemTypeTagTag` FOREIGN KEY (`tagFk`) REFERENCES `tag` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `itemTypeTagTipos` FOREIGN KEY (`itemTypeFk`) REFERENCES `vn2008`.`Tipos` (`tipo_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=236 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 `labourTree`
--

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

--
-- Temporary table structure for view `mail`
--

DROP TABLE IF EXISTS `mail`;
/*!50001 DROP VIEW IF EXISTS `mail`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `mail` AS SELECT 
 1 AS `id`,
 1 AS `senderFk`,
 1 AS `recipientFk`,
 1 AS `sender`,
 1 AS `replyTo`,
 1 AS `subject`,
 1 AS `body`,
 1 AS `plainTextBody`,
 1 AS `attachment`,
 1 AS `creationDate`,
 1 AS `sent`,
 1 AS `status`*/;
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 */;

--
-- Temporary table structure for view `manaSpellers`
--

DROP TABLE IF EXISTS `manaSpellers`;
/*!50001 DROP VIEW IF EXISTS `manaSpellers`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `manaSpellers` AS SELECT 
 1 AS `worker`,
 1 AS `size`,
 1 AS `used`,
 1 AS `pricesModifierRate`,
 1 AS `pricesModifierActivated`,
 1 AS `workerCode`,
 1 AS `firstname`,
 1 AS `name`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `mandate`
--

DROP TABLE IF EXISTS `mandate`;
/*!50001 DROP VIEW IF EXISTS `mandate`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `mandate` AS SELECT 
 1 AS `id`,
 1 AS `clientFk`,
 1 AS `companyFk`,
 1 AS `code`,
 1 AS `created`,
 1 AS `finished`,
 1 AS `mandateTypeFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `mandateType`
--

DROP TABLE IF EXISTS `mandateType`;
/*!50001 DROP VIEW IF EXISTS `mandateType`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `mandateType` AS SELECT 
 1 AS `id`,
 1 AS `name`*/;
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 `medicalCenter`
--

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

--
-- Table structure for table `medicalReview`
--

DROP TABLE IF EXISTS `medicalReview`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `medicalReview` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `workerFk` int(11) NOT NULL,
  `centerFk` int(11) NOT NULL,
  `date` date DEFAULT NULL,
  `time` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `fit` tinyint(1) DEFAULT NULL,
  `amount` double DEFAULT NULL,
  `invoice` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `remark` longtext COLLATE utf8_unicode_ci,
  PRIMARY KEY (`id`),
  KEY `frgcenter_idx` (`centerFk`),
  KEY `frgnkWorker_idx` (`workerFk`),
  CONSTRAINT `frgcenter` FOREIGN KEY (`centerFk`) REFERENCES `medicalCenter` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `frgnkWorker` FOREIGN KEY (`workerFk`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=220 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=1851169 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=2018582 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `mobileAppVersionControl`
--

DROP TABLE IF EXISTS `mobileAppVersionControl`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mobileAppVersionControl` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `appName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `version` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla para llevar el control de las Versions de las aplicaciones móvil ';
/*!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 */;

--
-- Temporary table structure for view `observationType`
--

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

--
-- Temporary table structure for view `orderTicket`
--

DROP TABLE IF EXISTS `orderTicket`;
/*!50001 DROP VIEW IF EXISTS `orderTicket`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `orderTicket` AS SELECT 
 1 AS `orderFk`,
 1 AS `ticketFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `origin`
--

DROP TABLE IF EXISTS `origin`;
/*!50001 DROP VIEW IF EXISTS `origin`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `origin` AS SELECT 
 1 AS `id`,
 1 AS `code`,
 1 AS `name`,
 1 AS `countryFk`*/;
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 */;

--
-- Temporary table structure for view `originL10n`
--

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

--
-- Temporary table structure for view `outgoingInvoice`
--

DROP TABLE IF EXISTS `outgoingInvoice`;
/*!50001 DROP VIEW IF EXISTS `outgoingInvoice`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `outgoingInvoice` AS SELECT 
 1 AS `id`,
 1 AS `serie`,
 1 AS `dateInvoice`,
 1 AS `total`,
 1 AS `dueDate`,
 1 AS `bank`,
 1 AS `client`,
 1 AS `remittance`,
 1 AS `remit`,
 1 AS `worker`,
 1 AS `creationDate`,
 1 AS `company`,
 1 AS `liquidacion?`,
 1 AS `isPdf`*/;
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 */;

--
-- Temporary table structure for view `packageEquivalentItem`
--

DROP TABLE IF EXISTS `packageEquivalentItem`;
/*!50001 DROP VIEW IF EXISTS `packageEquivalentItem`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `packageEquivalentItem` AS SELECT 
 1 AS `itemFk`,
 1 AS `equivalentFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `packaging`
--

DROP TABLE IF EXISTS `packaging`;
/*!50001 DROP VIEW IF EXISTS `packaging`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `packaging` AS SELECT 
 1 AS `id`,
 1 AS `volume`,
 1 AS `width`,
 1 AS `height`,
 1 AS `depth`,
 1 AS `isPackageReturnable`,
 1 AS `created`,
 1 AS `itemFk`,
 1 AS `price`,
 1 AS `isBox`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `parking`
--

DROP TABLE IF EXISTS `parking`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `parking` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `column` varchar(5) CHARACTER SET utf8 NOT NULL DEFAULT '--',
  `row` varchar(5) CHARACTER SET utf8 NOT NULL DEFAULT '--',
  `sectorFk` int(11) NOT NULL DEFAULT '2',
  `code` varchar(8) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `column_UNIQUE` (`column`,`row`),
  UNIQUE KEY `code_UNIQUE` (`code`),
  KEY `parking_fk1_idx` (`sectorFk`),
  CONSTRAINT `parking_fk1` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=25479 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla con los parkings del altillo';
/*!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`.`parking_BEFORE_INSERT` BEFORE INSERT ON `parking` FOR EACH ROW
BEGIN

	-- SET new.`code` = CONCAT(new.`column`,' - ',new.`row`) ;

END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `vn`.`parking_BEFORE_UPDATE` BEFORE UPDATE ON `parking` FOR EACH ROW
BEGIN

	-- SET new.`code` = CONCAT(new.`column`,' - ',new.`row`) ;
    
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;

--
-- Temporary table structure for view `payDem`
--

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

--
-- Temporary table structure for view `payMethod`
--

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

--
-- Temporary table structure for view `payment`
--

DROP TABLE IF EXISTS `payment`;
/*!50001 DROP VIEW IF EXISTS `payment`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `payment` AS SELECT 
 1 AS `id`,
 1 AS `received`,
 1 AS `supplierFk`,
 1 AS `amount`,
 1 AS `currencyFk`,
 1 AS `divisa`,
 1 AS `bankFk`,
 1 AS `payMethod`,
 1 AS `companyFk`,
 1 AS `exchangeInsuranceFk`,
 1 AS `isConciliate`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `paymentExchangeInsurance`
--

DROP TABLE IF EXISTS `paymentExchangeInsurance`;
/*!50001 DROP VIEW IF EXISTS `paymentExchangeInsurance`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `paymentExchangeInsurance` AS SELECT 
 1 AS `id`,
 1 AS `amount`,
 1 AS `created`,
 1 AS `dueDay`,
 1 AS `entityFk`,
 1 AS `ref`,
 1 AS `rate`,
 1 AS `companyFk`,
 1 AS `financialProductTypefk`,
 1 AS `upperBarrier`,
 1 AS `lowerBarrier`,
 1 AS `strike`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `payrollCenter`
--

DROP TABLE IF EXISTS `payrollCenter`;
/*!50001 DROP VIEW IF EXISTS `payrollCenter`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `payrollCenter` AS SELECT 
 1 AS `codCenter`,
 1 AS `name`,
 1 AS `nss`,
 1 AS `street`,
 1 AS `city`,
 1 AS `postcode`,
 1 AS `companyFk`,
 1 AS `companyCode`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `pedidosInternos`
--

DROP TABLE IF EXISTS `pedidosInternos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `pedidosInternos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `idArticle` int(11) DEFAULT NULL,
  `quantity` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=54 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!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 */;

--
-- Temporary table structure for view `plantpassport`
--

DROP TABLE IF EXISTS `plantpassport`;
/*!50001 DROP VIEW IF EXISTS `plantpassport`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `plantpassport` AS SELECT 
 1 AS `producerFk`,
 1 AS `plantpassportAuthorityFk`,
 1 AS `number`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `plantpassportAuthority`
--

DROP TABLE IF EXISTS `plantpassportAuthority`;
/*!50001 DROP VIEW IF EXISTS `plantpassportAuthority`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `plantpassportAuthority` AS SELECT 
 1 AS `id`,
 1 AS `denomination`,
 1 AS `countryFk`*/;
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` char(5) COLLATE utf8_unicode_ci NOT NULL,
  `townFk` int(11) NOT NULL,
  `geoFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`code`,`townFk`),
  KEY `postCodeTownFk_idx` (`townFk`),
  CONSTRAINT `postCodeTownFk` FOREIGN KEY (`townFk`) REFERENCES `town` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `preparationException`
--

DROP TABLE IF EXISTS `preparationException`;
/*!50001 DROP VIEW IF EXISTS `preparationException`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `preparationException` AS SELECT 
 1 AS `exceptionDay`,
 1 AS `warehouseFk`,
 1 AS `percentage`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `preparationPercentage`
--

DROP TABLE IF EXISTS `preparationPercentage`;
/*!50001 DROP VIEW IF EXISTS `preparationPercentage`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `preparationPercentage` AS SELECT 
 1 AS `weekDay`,
 1 AS `warehouseFk`,
 1 AS `percentage`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `priceBuilder`
--

DROP TABLE IF EXISTS `priceBuilder`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `priceBuilder` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `itemTypeFk` smallint(5) unsigned NOT NULL COMMENT 'Sirve para definir precios en tarifa2 para grupos de items',
  `started` date DEFAULT NULL,
  `finished` date DEFAULT NULL,
  `price` decimal(10,3) NOT NULL,
  `userFk` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `priceBuilder_fk1_idx` (`itemTypeFk`),
  KEY `priceBuilder_fk2_idx` (`userFk`),
  CONSTRAINT `priceBuilder_fk1` FOREIGN KEY (`itemTypeFk`) REFERENCES `vn2008`.`Tipos` (`tipo_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `priceBuilder_fk2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `priceBuilderDistinctTags`
--

DROP TABLE IF EXISTS `priceBuilderDistinctTags`;
/*!50001 DROP VIEW IF EXISTS `priceBuilderDistinctTags`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `priceBuilderDistinctTags` AS SELECT 
 1 AS `priceBuilderFk`,
 1 AS `numTags`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `priceBuilderTag`
--

DROP TABLE IF EXISTS `priceBuilderTag`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `priceBuilderTag` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `priceBuilderFk` int(11) NOT NULL,
  `tagFk` int(11) NOT NULL,
  `value` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `priceBuilderTag_fk1_idx` (`priceBuilderFk`),
  KEY `priceBuilderTag_fk2_idx` (`tagFk`),
  CONSTRAINT `priceBuilderTag_fk1` FOREIGN KEY (`priceBuilderFk`) REFERENCES `priceBuilder` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `priceBuilderTag_fk2` FOREIGN KEY (`tagFk`) REFERENCES `tag` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `priceBuilderWarehouse`
--

DROP TABLE IF EXISTS `priceBuilderWarehouse`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `priceBuilderWarehouse` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `warehouseFk` smallint(6) unsigned NOT NULL,
  `priceBuilderFk` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `priceBuilderWarehouse_fk1_idx` (`warehouseFk`),
  KEY `priceBuilderWarehouse_fk2_idx` (`priceBuilderFk`),
  CONSTRAINT `priceBuilderWarehouse_fk1` FOREIGN KEY (`warehouseFk`) REFERENCES `vn2008`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `priceBuilderWarehouse_fk2` FOREIGN KEY (`priceBuilderFk`) REFERENCES `priceBuilder` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `priceFixed`
--

DROP TABLE IF EXISTS `priceFixed`;
/*!50001 DROP VIEW IF EXISTS `priceFixed`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `priceFixed` AS SELECT 
 1 AS `itemFk`,
 1 AS `rate0`,
 1 AS `rate1`,
 1 AS `rate2`,
 1 AS `rate3`,
 1 AS `started`,
 1 AS `ended`,
 1 AS `bonus`,
 1 AS `warehouseFk`,
 1 AS `created`,
 1 AS `id`,
 1 AS `grouping`,
 1 AS `packing`,
 1 AS `box`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `printServerQueue`
--

DROP TABLE IF EXISTS `printServerQueue`;
/*!50001 DROP VIEW IF EXISTS `printServerQueue`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `printServerQueue` AS SELECT 
 1 AS `id`,
 1 AS `printerFk`,
 1 AS `priorityFk`,
 1 AS `reportFk`,
 1 AS `statusFk`,
 1 AS `started`,
 1 AS `finished`,
 1 AS `param1`,
 1 AS `workerFk`,
 1 AS `param2`,
 1 AS `param3`,
 1 AS `error`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `printer`
--

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

--
-- Temporary table structure for view `printingQueue`
--

DROP TABLE IF EXISTS `printingQueue`;
/*!50001 DROP VIEW IF EXISTS `printingQueue`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `printingQueue` AS SELECT 
 1 AS `id`,
 1 AS `printer`,
 1 AS `priority`,
 1 AS `report`,
 1 AS `state`,
 1 AS `startingTime`,
 1 AS `endingTime`,
 1 AS `text`,
 1 AS `worker`,
 1 AS `text2`,
 1 AS `text3`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `printingQueueCheck`
--

DROP TABLE IF EXISTS `printingQueueCheck`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `printingQueueCheck` (
  `lastCount` int(11) unsigned NOT NULL DEFAULT '0',
  `lastCheckSum` int(11) unsigned NOT NULL DEFAULT '0',
  `isAlreadyNotified` tinyint(2) NOT NULL DEFAULT '0',
  PRIMARY KEY (`lastCount`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Comprueba que el servidor de impresion no esta parado';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `producer`
--

DROP TABLE IF EXISTS `producer`;
/*!50001 DROP VIEW IF EXISTS `producer`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `producer` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `isVisible`*/;
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 */;

--
-- Temporary table structure for view `promissoryNote`
--

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

--
-- Temporary table structure for view `province`
--

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

--
-- Temporary table structure for view `receipt`
--

DROP TABLE IF EXISTS `receipt`;
/*!50001 DROP VIEW IF EXISTS `receipt`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `receipt` AS SELECT 
 1 AS `id`,
 1 AS `invoiceFk`,
 1 AS `amountPaid`,
 1 AS `amountUnpaid`,
 1 AS `payed`,
 1 AS `workerFk`,
 1 AS `bankFk`,
 1 AS `clientFk`,
 1 AS `created`,
 1 AS `companyFk`,
 1 AS `isConciliate`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `recovery`
--

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

--
-- Temporary table structure for view `referenceRate`
--

DROP TABLE IF EXISTS `referenceRate`;
/*!50001 DROP VIEW IF EXISTS `referenceRate`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `referenceRate` AS SELECT 
 1 AS `currencyFk`,
 1 AS `dated`,
 1 AS `value`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `referenceRateConfig`
--

DROP TABLE IF EXISTS `referenceRateConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `referenceRateConfig` (
  `simulatedValue` float unsigned NOT NULL DEFAULT '1.2309',
  PRIMARY KEY (`simulatedValue`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `role`
--

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

--
-- Temporary table structure for view `route`
--

DROP TABLE IF EXISTS `route`;
/*!50001 DROP VIEW IF EXISTS `route`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `route` AS SELECT 
 1 AS `id`,
 1 AS `workerFk`,
 1 AS `created`,
 1 AS `vehicleFk`,
 1 AS `agencyModeFk`,
 1 AS `time`,
 1 AS `isOk`,
 1 AS `kmStart`,
 1 AS `kmEnd`,
 1 AS `started`,
 1 AS `finished`,
 1 AS `gestdocFk`,
 1 AS `cost`,
 1 AS `m3`,
 1 AS `description`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `routeAction`
--

DROP TABLE IF EXISTS `routeAction`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `routeAction` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `price` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `routeComplement`
--

DROP TABLE IF EXISTS `routeComplement`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `routeComplement` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dated` date NOT NULL,
  `workerFk` int(11) NOT NULL,
  `price` decimal(10,2) NOT NULL,
  `routeActionFk` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `fgn_workerFk_idx` (`workerFk`),
  KEY `fgn_routeActionFk_idx` (`routeActionFk`),
  CONSTRAINT `fgn_routeActionFk` FOREIGN KEY (`routeActionFk`) REFERENCES `routeAction` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fgn_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`)
) ENGINE=InnoDB AUTO_INCREMENT=159 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,
  `ready` tinyint(4) NOT NULL DEFAULT '0',
  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 `routeLoadWorker`
--

DROP TABLE IF EXISTS `routeLoadWorker`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `routeLoadWorker` (
  `routeFk` int(10) unsigned NOT NULL,
  `workerFk` int(11) NOT NULL,
  PRIMARY KEY (`routeFk`,`workerFk`),
  KEY `frmWorker_idx` (`workerFk`),
  CONSTRAINT `frmRutas` FOREIGN KEY (`routeFk`) REFERENCES `vn2008`.`Rutas` (`Id_Ruta`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `frmWorker` FOREIGN KEY (`workerFk`) 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 `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(10) unsigned NOT NULL,
  `userFk` int(10) unsigned DEFAULT NULL,
  `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL,
  `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `description` text CHARACTER SET utf8,
  `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `oldInstance` text COLLATE utf8_unicode_ci,
  `newInstance` text COLLATE utf8_unicode_ci,
  `changedModelId` int(11) DEFAULT NULL,
  `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `originFk` (`originFk`),
  KEY `userFk` (`userFk`),
  CONSTRAINT `routeLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `vn2008`.`Rutas` (`Id_Ruta`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `routeLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3267 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `routeParams`
--

DROP TABLE IF EXISTS `routeParams`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `routeParams` (
  `ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `kmRate` decimal(10,4) DEFAULT NULL,
  `m3Distributed` decimal(10,4) DEFAULT NULL,
  `load1m3` decimal(10,4) DEFAULT NULL,
  `load2m3` decimal(10,4) DEFAULT NULL,
  `load3m3` decimal(10,4) DEFAULT NULL,
  `load4m3` decimal(10,4) DEFAULT NULL,
  `load5m3` decimal(10,4) DEFAULT NULL,
  `load6m3` decimal(10,4) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `routesControl`
--

DROP TABLE IF EXISTS `routesControl`;
/*!50001 DROP VIEW IF EXISTS `routesControl`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `routesControl` AS SELECT 
 1 AS `routeFk`,
 1 AS `expeditions`,
 1 AS `scanned`,
 1 AS `pallets`,
 1 AS `lastScanned`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `sale`
--

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

--
-- Temporary table structure for view `saleChecked`
--

DROP TABLE IF EXISTS `saleChecked`;
/*!50001 DROP VIEW IF EXISTS `saleChecked`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `saleChecked` AS SELECT 
 1 AS `saleFk`,
 1 AS `isChecked`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `saleComponent`
--

DROP TABLE IF EXISTS `saleComponent`;
/*!50001 DROP VIEW IF EXISTS `saleComponent`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `saleComponent` AS SELECT 
 1 AS `saleFk`,
 1 AS `componentFk`,
 1 AS `value`,
 1 AS `created`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `saleItemShelving`
--

DROP TABLE IF EXISTS `saleItemShelving`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `saleItemShelving` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `saleFk` int(11) NOT NULL,
  `itemShelvingFk` int(10) unsigned NOT NULL,
  `quantity` int(11) NOT NULL DEFAULT '0',
  `isPicked` tinyint(4) NOT NULL DEFAULT '0',
  `ubication` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `saleItemShelving_fk1_idx` (`itemShelvingFk`)
) ENGINE=InnoDB AUTO_INCREMENT=26204 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `saleState`
--

DROP TABLE IF EXISTS `saleState`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `saleState` (
  `saleFk` int(11) NOT NULL,
  `stateFk` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`saleFk`),
  KEY `saleState_fk2_idx` (`stateFk`),
  CONSTRAINT `saleState_fk1` FOREIGN KEY (`saleFk`) REFERENCES `vn2008`.`Movimientos` (`Id_Movimiento`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `saleState_fk2` FOREIGN KEY (`stateFk`) REFERENCES `vn2008`.`state` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='cahce para el estado de la linea';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `saleTracking`
--

DROP TABLE IF EXISTS `saleTracking`;
/*!50001 DROP VIEW IF EXISTS `saleTracking`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `saleTracking` AS SELECT 
 1 AS `saleFk`,
 1 AS `isChecked`,
 1 AS `created`,
 1 AS `originalQuantity`,
 1 AS `workerFk`,
 1 AS `actionFk`,
 1 AS `id`,
 1 AS `stateFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `sample`
--

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

--
-- Table structure for table `sector`
--

DROP TABLE IF EXISTS `sector`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sector` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`,`warehouseFk`),
  KEY `sector_fk1_idx` (`warehouseFk`),
  CONSTRAINT `sector_fk1` FOREIGN KEY (`warehouseFk`) REFERENCES `vn2008`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `sharingCart`
--

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

--
-- Temporary table structure for view `sharingClient`
--

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

--
-- Table structure for table `shelving`
--

DROP TABLE IF EXISTS `shelving`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shelving` (
  `code` varchar(10) CHARACTER SET utf8 NOT NULL,
  `parkingFk` int(11) DEFAULT NULL,
  `isPrinted` tinyint(4) NOT NULL DEFAULT '0',
  `priority` int(11) DEFAULT NULL,
  `parked` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`code`),
  KEY `shelving_fk1_idx` (`parkingFk`),
  CONSTRAINT `shelving_fk1` FOREIGN KEY (`parkingFk`) REFERENCES `parking` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla usada para localizar el carro en el parking del altillo';
/*!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`.`shelving_BEFORE_UPDATE` BEFORE UPDATE ON `shelving` FOR EACH ROW
BEGIN

	IF OLD.parkingFk != NEW.parkingFk THEN
    
		SET NEW.parked = NOW();
        
    END IF;

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

--
-- 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=131004 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=InnoDB 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 ;

--
-- Temporary table structure for view `specialPrice`
--

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

--
-- Temporary table structure for view `state`
--

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

--
-- 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=655667 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `stowaway`
--

DROP TABLE IF EXISTS `stowaway`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `stowaway` (
  `id` int(11) NOT NULL COMMENT 'ticket pequeño',
  `shipFk` int(11) NOT NULL COMMENT 'ticket grande',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tickets polizones y sus naves de embarque';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `supplier`
--

DROP TABLE IF EXISTS `supplier`;
/*!50001 DROP VIEW IF EXISTS `supplier`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `supplier` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `account`,
 1 AS `countryFk`,
 1 AS `nif`,
 1 AS `isFarmer`,
 1 AS `phone`,
 1 AS `retAccount`,
 1 AS `commission`,
 1 AS `created`,
 1 AS `postcodeFk`,
 1 AS `isActive`,
 1 AS `street`,
 1 AS `city`,
 1 AS `provinceFk`,
 1 AS `postCode`,
 1 AS `payMethodFk`,
 1 AS `payDemFk`,
 1 AS `nickname`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `supplierAccount`
--

DROP TABLE IF EXISTS `supplierAccount`;
/*!50001 DROP VIEW IF EXISTS `supplierAccount`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `supplierAccount` AS SELECT 
 1 AS `id`,
 1 AS `supplierFk`,
 1 AS `iban`,
 1 AS `bankEntityFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `supplierPackaging`
--

DROP TABLE IF EXISTS `supplierPackaging`;
/*!50001 DROP VIEW IF EXISTS `supplierPackaging`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `supplierPackaging` AS SELECT 
 1 AS `supplierFk`,
 1 AS `itemFk`,
 1 AS `longName`,
 1 AS `supplier`,
 1 AS `entryFk`,
 1 AS `landed`,
 1 AS `out`,
 1 AS `in`,
 1 AS `almacen`*/;
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,
  `isFree` 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,
  `ediTypeFk` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `tagEdiTypeFkIdx` (`ediTypeFk`),
  CONSTRAINT `fgnTag` FOREIGN KEY (`ediTypeFk`) REFERENCES `edi`.`type` (`type_id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=103 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 `tagAbbreviation`
--

DROP TABLE IF EXISTS `tagAbbreviation`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tagAbbreviation` (
  `value` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `abbreviation` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`value`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!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 */;

--
-- Temporary table structure for view `tagL10n`
--

DROP TABLE IF EXISTS `tagL10n`;
/*!50001 DROP VIEW IF EXISTS `tagL10n`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `tagL10n` AS SELECT 
 1 AS `id`,
 1 AS `name`*/;
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) CHARACTER SET utf8 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 */;

--
-- Temporary table structure for view `taxClass`
--

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

--
-- Temporary table structure for view `taxClassCode`
--

DROP TABLE IF EXISTS `taxClassCode`;
/*!50001 DROP VIEW IF EXISTS `taxClassCode`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `taxClassCode` AS SELECT 
 1 AS `taxClassFk`,
 1 AS `effectived`,
 1 AS `taxCodeFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `taxCode`
--

DROP TABLE IF EXISTS `taxCode`;
/*!50001 DROP VIEW IF EXISTS `taxCode`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `taxCode` AS SELECT 
 1 AS `id`,
 1 AS `dated`,
 1 AS `code`,
 1 AS `taxTypeFk`,
 1 AS `rate`,
 1 AS `equalizationTax`,
 1 AS `type`,
 1 AS `link`,
 1 AS `isActive`,
 1 AS `updated`,
 1 AS `transactionCode`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `taxType`
--

DROP TABLE IF EXISTS `taxType`;
/*!50001 DROP VIEW IF EXISTS `taxType`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `taxType` AS SELECT 
 1 AS `id`,
 1 AS `nickname`,
 1 AS `isAccrued`,
 1 AS `serial`,
 1 AS `TIPOOPE`,
 1 AS `description`,
 1 AS `countryFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `ticket`
--

DROP TABLE IF EXISTS `ticket`;
/*!50001 DROP VIEW IF EXISTS `ticket`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticket` AS SELECT 
 1 AS `id`,
 1 AS `clientFk`,
 1 AS `warehouseFk`,
 1 AS `shipped`,
 1 AS `landed`,
 1 AS `nickname`,
 1 AS `refFk`,
 1 AS `addressFk`,
 1 AS `location`,
 1 AS `solution`,
 1 AS `routeFk`,
 1 AS `companyFk`,
 1 AS `agencyModeFk`,
 1 AS `priority`,
 1 AS `packages`,
 1 AS `isDeleted`,
 1 AS `created`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `ticketConfig`
--

DROP TABLE IF EXISTS `ticketConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketConfig` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `scopeDays` tinyint(3) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `ticketDms`
--

DROP TABLE IF EXISTS `ticketDms`;
/*!50001 DROP VIEW IF EXISTS `ticketDms`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketDms` AS SELECT 
 1 AS `ticketFk`,
 1 AS `dmsFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `ticketDown`
--

DROP TABLE IF EXISTS `ticketDown`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketDown` (
  `ticketFk` int(11) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `selected` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`ticketFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Cola de impresion para los tickets que se van a solicitar al altillo';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `ticketDownBuffer`
--

DROP TABLE IF EXISTS `ticketDownBuffer`;
/*!50001 DROP VIEW IF EXISTS `ticketDownBuffer`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketDownBuffer` AS SELECT 
 1 AS `ticketFk`,
 1 AS `created`,
 1 AS `selected`,
 1 AS `sacador`,
 1 AS `parking`*/;
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 DEFAULT NULL,
  `action` set('insert','update','delete','select') COLLATE utf8_unicode_ci NOT NULL,
  `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `description` text CHARACTER SET utf8,
  `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `oldInstance` text COLLATE utf8_unicode_ci,
  `newInstance` text COLLATE utf8_unicode_ci,
  `changedModelId` int(11) DEFAULT NULL,
  `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `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_user` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5651565 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `ticketNotInvoiced`
--

DROP TABLE IF EXISTS `ticketNotInvoiced`;
/*!50001 DROP VIEW IF EXISTS `ticketNotInvoiced`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketNotInvoiced` AS SELECT 
 1 AS `companyFk`,
 1 AS `companyCode`,
 1 AS `clientFk`,
 1 AS `clientName`,
 1 AS `shipped`,
 1 AS `value`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `ticketObservation`
--

DROP TABLE IF EXISTS `ticketObservation`;
/*!50001 DROP VIEW IF EXISTS `ticketObservation`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketObservation` AS SELECT 
 1 AS `id`,
 1 AS `ticketFk`,
 1 AS `observationTypeFk`,
 1 AS `description`*/;
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,
  `workerFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `ticketPackaging_fk1_idx` (`ticketFk`),
  KEY `ticketPackaging_fk2_idx` (`packagingFk`),
  KEY `ticketPackaging_fk3_idx` (`workerFk`),
  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,
  CONSTRAINT `ticketPackaging_fk3` FOREIGN KEY (`workerFk`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=60590 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`.`ticketPackaging_BEFORE_INSERT` BEFORE INSERT ON `ticketPackaging` FOR EACH ROW
BEGIN

	SET NEW.workerFk = vn.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 */ ;

--
-- 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,
  `isForgetable` tinyint(1) NOT NULL DEFAULT '0',
  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 */;

--
-- Temporary table structure for view `ticketRequest`
--

DROP TABLE IF EXISTS `ticketRequest`;
/*!50001 DROP VIEW IF EXISTS `ticketRequest`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketRequest` AS SELECT 
 1 AS `id`,
 1 AS `description`,
 1 AS `requesterFk`,
 1 AS `atenderFk`,
 1 AS `quantity`,
 1 AS `itemFk`,
 1 AS `price`,
 1 AS `isOk`,
 1 AS `saleFk`,
 1 AS `ticketFk`,
 1 AS `response`,
 1 AS `created`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `ticketService`
--

DROP TABLE IF EXISTS `ticketService`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketService` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `quantity` int(11) NOT NULL DEFAULT '0',
  `price` decimal(10,2) unsigned NOT NULL DEFAULT '0.00',
  `taxClassFk` tinyint(3) unsigned DEFAULT NULL,
  `ticketFk` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `ticketServiceIvaGroup_idx` (`taxClassFk`),
  KEY `fgn_ticketFk_idx` (`ticketFk`),
  CONSTRAINT `fgn_ticketFk` FOREIGN KEY (`ticketFk`) REFERENCES `vn2008`.`Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `ticketServiceIvaGroup` FOREIGN KEY (`taxClassFk`) REFERENCES `vn2008`.`iva_group` (`iva_group_id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Servicios asociadas a un ticket';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `ticketServiceType`
--

DROP TABLE IF EXISTS `ticketServiceType`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketServiceType` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Lista de los posibles servicios a elegir';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `ticketState`
--

DROP TABLE IF EXISTS `ticketState`;
/*!50001 DROP VIEW IF EXISTS `ticketState`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketState` AS SELECT 
 1 AS `updated`,
 1 AS `stateFk`,
 1 AS `workerFk`,
 1 AS `ticketFk`,
 1 AS `state`,
 1 AS `productionOrder`,
 1 AS `alertLevel`,
 1 AS `code`,
 1 AS `ticket`,
 1 AS `worker`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `ticketStateToday`
--

DROP TABLE IF EXISTS `ticketStateToday`;
/*!50001 DROP VIEW IF EXISTS `ticketStateToday`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketStateToday` AS SELECT 
 1 AS `ticket`,
 1 AS `state`,
 1 AS `productionOrder`,
 1 AS `alertLevel`,
 1 AS `worker`,
 1 AS `code`,
 1 AS `updated`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `ticketToPrepare`
--

DROP TABLE IF EXISTS `ticketToPrepare`;
/*!50001 DROP VIEW IF EXISTS `ticketToPrepare`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketToPrepare` AS SELECT 
 1 AS `Id_Ticket`,
 1 AS `Id_Movimiento`,
 1 AS `Id_Movimiento_mark`,
 1 AS `Id_Trabjador`,
 1 AS `Id_Article`,
 1 AS `Concepte`,
 1 AS `subName`,
 1 AS `Cantidad`,
 1 AS `original_quantity`,
 1 AS `Hora`,
 1 AS `Departure`,
 1 AS `Minuto`,
 1 AS `agency_id`,
 1 AS `warehouse_id`,
 1 AS `province_id`,
 1 AS `picked`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `ticketTracking`
--

DROP TABLE IF EXISTS `ticketTracking`;
/*!50001 DROP VIEW IF EXISTS `ticketTracking`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketTracking` AS SELECT 
 1 AS `id`,
 1 AS `stateFk`,
 1 AS `created`,
 1 AS `ticketFk`,
 1 AS `workerFk`*/;
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 */;

--
-- Temporary table structure for view `ticketUpdateAction`
--

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

--
-- Temporary table structure for view `ticketWeekly`
--

DROP TABLE IF EXISTS `ticketWeekly`;
/*!50001 DROP VIEW IF EXISTS `ticketWeekly`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketWeekly` AS SELECT 
 1 AS `ticketFk`,
 1 AS `weekDay`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `ticketeToPreparePrepared`
--

DROP TABLE IF EXISTS `ticketeToPreparePrepared`;
/*!50001 DROP VIEW IF EXISTS `ticketeToPreparePrepared`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketeToPreparePrepared` AS SELECT 
 1 AS `Id_Ticket`,
 1 AS `Id_Movimiento`,
 1 AS `Id_Movimiento_mark`,
 1 AS `Id_Trabjador`,
 1 AS `Id_Article`,
 1 AS `Concepte`,
 1 AS `subName`,
 1 AS `Cantidad`,
 1 AS `original_quantity`,
 1 AS `Hora`,
 1 AS `Departure`,
 1 AS `Minuto`,
 1 AS `agency_id`,
 1 AS `warehouse_id`,
 1 AS `province_id`,
 1 AS `picked`,
 1 AS `trabajador`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `till`
--

DROP TABLE IF EXISTS `till`;
/*!50001 DROP VIEW IF EXISTS `till`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `till` AS SELECT 
 1 AS `id`,
 1 AS `created`,
 1 AS `serie`,
 1 AS `concept`,
 1 AS `in`,
 1 AS `out`,
 1 AS `bankFk`,
 1 AS `supplierFk`,
 1 AS `isAccountable`,
 1 AS `inForeignValue`,
 1 AS `outForeignValue`,
 1 AS `workerFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `tillConfig`
--

DROP TABLE IF EXISTS `tillConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tillConfig` (
  `id` int(11) NOT NULL,
  `openingBalance` decimal(10,2) NOT NULL,
  `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `time`
--

DROP TABLE IF EXISTS `time`;
/*!50001 DROP VIEW IF EXISTS `time`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `time` AS SELECT 
 1 AS `dated`,
 1 AS `period`,
 1 AS `month`,
 1 AS `year`,
 1 AS `day`,
 1 AS `week`*/;
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,
  `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `provinceFk` smallint(6) unsigned NOT NULL,
  `geoFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `townProvinceFk_idx` (`provinceFk`),
  CONSTRAINT `townProvinceFk` FOREIGN KEY (`provinceFk`) REFERENCES `vn2008`.`province` (`province_id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `trainingCenter`
--

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

--
-- Table structure for table `trainingCourse`
--

DROP TABLE IF EXISTS `trainingCourse`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `trainingCourse` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `workerFk` int(11) NOT NULL,
  `trainingCourseTypeFk` int(11) NOT NULL,
  `centerFk` int(11) DEFAULT NULL,
  `started` datetime NOT NULL,
  `ended` datetime NOT NULL,
  `invoice` int(11) DEFAULT NULL,
  `amount` double DEFAULT NULL,
  `remark` longtext COLLATE utf8_unicode_ci,
  PRIMARY KEY (`id`),
  KEY `frgnWorker_idx` (`workerFk`),
  KEY `frgnCenter_idx` (`centerFk`),
  KEY `frgnTrainingCourseType_idx` (`trainingCourseTypeFk`),
  CONSTRAINT `frgnCenter` FOREIGN KEY (`centerFk`) REFERENCES `trainingCenter` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `frgnTrainingCourseType` FOREIGN KEY (`trainingCourseTypeFk`) REFERENCES `trainingCourseType` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `frgnWorker` FOREIGN KEY (`workerFk`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=265 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Lista de trabajadores que han realizado una formación';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `trainingCourseType`
--

DROP TABLE IF EXISTS `trainingCourseType`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `trainingCourseType` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Lista de las formaciones';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `travel`
--

DROP TABLE IF EXISTS `travel`;
/*!50001 DROP VIEW IF EXISTS `travel`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `travel` AS SELECT 
 1 AS `id`,
 1 AS `shipped`,
 1 AS `shipmentHour`,
 1 AS `landed`,
 1 AS `landingHour`,
 1 AS `warehouseInFk`,
 1 AS `warehouseOutFk`,
 1 AS `agencyFk`,
 1 AS `ref`,
 1 AS `isDelivered`,
 1 AS `isReceived`,
 1 AS `m3`,
 1 AS `kg`,
 1 AS `cargoSupplierFk`,
 1 AS `totalEntries`*/;
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=20 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Observaciones de travel';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `travelRecalc`
--

DROP TABLE IF EXISTS `travelRecalc`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `travelRecalc` (
  `travelFk` int(10) unsigned NOT NULL,
  PRIMARY KEY (`travelFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Travels to recalc it''s entry count';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `unary`
--

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

--
-- Temporary table structure for view `unaryScan`
--

DROP TABLE IF EXISTS `unaryScan`;
/*!50001 DROP VIEW IF EXISTS `unaryScan`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `unaryScan` AS SELECT 
 1 AS `unaryFk`,
 1 AS `name`,
 1 AS `created`,
 1 AS `type`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `unaryScanLine`
--

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

--
-- Temporary table structure for view `unaryScanLineBuy`
--

DROP TABLE IF EXISTS `unaryScanLineBuy`;
/*!50001 DROP VIEW IF EXISTS `unaryScanLineBuy`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `unaryScanLineBuy` AS SELECT 
 1 AS `unaryScanLineFk`,
 1 AS `itemFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `unaryScanLineExpedition`
--

DROP TABLE IF EXISTS `unaryScanLineExpedition`;
/*!50001 DROP VIEW IF EXISTS `unaryScanLineExpedition`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `unaryScanLineExpedition` AS SELECT 
 1 AS `unaryScanLineFk`,
 1 AS `expeditionFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `user`
--

DROP TABLE IF EXISTS `user`;
/*!50001 DROP VIEW IF EXISTS `user`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `user` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `password`,
 1 AS `role`,
 1 AS `active`,
 1 AS `recoverPass`,
 1 AS `lastPassChange`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `userConfig`
--

DROP TABLE IF EXISTS `userConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `userConfig` (
  `userFk` int(10) unsigned NOT NULL,
  `warehouseFk` smallint(6) DEFAULT NULL,
  `companyFk` smallint(5) unsigned DEFAULT NULL,
  `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `updated` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`userFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Configuración de usuario en Salix';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `vehicle`
--

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

--
-- Temporary table structure for view `warehouse`
--

DROP TABLE IF EXISTS `warehouse`;
/*!50001 DROP VIEW IF EXISTS `warehouse`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `warehouse` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `isInventory`,
 1 AS `isFeedStock`,
 1 AS `isComparative`,
 1 AS `hasComission`,
 1 AS `hasAvailable`,
 1 AS `isManaged`,
 1 AS `isForTicket`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `warehouseAlias`
--

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

--
-- 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,
  `warehouseFk` smallint(6) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `workCenterHoliday`
--

DROP TABLE IF EXISTS `workCenterHoliday`;
/*!50001 DROP VIEW IF EXISTS `workCenterHoliday`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `workCenterHoliday` AS SELECT 
 1 AS `workCenterFk`,
 1 AS `days`,
 1 AS `year`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `worker`
--

DROP TABLE IF EXISTS `worker`;
/*!50001 DROP VIEW IF EXISTS `worker`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `worker` AS SELECT 
 1 AS `id`,
 1 AS `workerCode`,
 1 AS `firstName`,
 1 AS `name`,
 1 AS `userFk`,
 1 AS `phone`,
 1 AS `bossFk`,
 1 AS `photo`,
 1 AS `fi`,
 1 AS `fiDueDate`,
 1 AS `code`,
 1 AS `lastName`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `workerBosses`
--

DROP TABLE IF EXISTS `workerBosses`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerBosses` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `workerFk` int(11) NOT NULL,
  `bossFk` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `workerFk_UNIQUE` (`workerFk`,`bossFk`),
  KEY `fg_worker_worker_idx` (`workerFk`),
  KEY `fg_bossFk_worker_idx` (`bossFk`),
  CONSTRAINT `fg_bossFk_worker` FOREIGN KEY (`bossFk`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fg_workerFk_worker` FOREIGN KEY (`workerFk`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=2515 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `workerCalendar`
--

DROP TABLE IF EXISTS `workerCalendar`;
/*!50001 DROP VIEW IF EXISTS `workerCalendar`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `workerCalendar` AS SELECT 
 1 AS `businessFk`,
 1 AS `workerFk`,
 1 AS `absenceTypeFk`,
 1 AS `dated`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `workerClockLog`
--

DROP TABLE IF EXISTS `workerClockLog`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerClockLog` (
  `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 `logWorkerClockoriginFk` (`originFk`),
  KEY `logWorkerClockuserFk` (`userFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `workerDepartment`
--

DROP TABLE IF EXISTS `workerDepartment`;
/*!50001 DROP VIEW IF EXISTS `workerDepartment`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `workerDepartment` AS SELECT 
 1 AS `workerFk`,
 1 AS `departmentFk`*/;
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=10462 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workerHourPrice`
--

DROP TABLE IF EXISTS `workerHourPrice`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerHourPrice` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dated` date NOT NULL,
  `hollidayInc` decimal(4,2) DEFAULT NULL,
  `nightInc` decimal(4,2) DEFAULT NULL,
  `extraInc` decimal(4,2) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Recoge los acuerdos de los distintos convenios';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workerJourney`
--

DROP TABLE IF EXISTS `workerJourney`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerJourney` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userFk` int(10) unsigned NOT NULL,
  `dated` date NOT NULL,
  `total` decimal(5,2) NOT NULL DEFAULT '0.00',
  `priceOrdinaryHour` decimal(5,2) NOT NULL DEFAULT '0.00',
  `nocturn` decimal(5,2) NOT NULL DEFAULT '0.00',
  `priceNocturnHour` decimal(5,2) NOT NULL DEFAULT '0.00',
  `hollyday` decimal(5,2) NOT NULL DEFAULT '0.00',
  `priceHollydayHour` decimal(5,2) NOT NULL DEFAULT '0.00',
  `lunch` decimal(5,2) NOT NULL DEFAULT '0.00',
  `priceExtraHour` decimal(5,2) NOT NULL DEFAULT '0.00',
  `extra` decimal(5,2) NOT NULL DEFAULT '0.00',
  `contractJourney` decimal(5,2) NOT NULL DEFAULT '0.00',
  `priceExtraHollyday` decimal(5,2) NOT NULL DEFAULT '0.00',
  `businessFk` int(11) DEFAULT NULL,
  `isPaid` tinyint(1) NOT NULL DEFAULT '0',
  `isUpdated` tinyint(1) NOT NULL DEFAULT '0',
  `permission` decimal(5,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`id`),
  UNIQUE KEY `userFk_UNIQUE` (`userFk`,`dated`),
  KEY `fk_workerJourney_user_idx` (`userFk`),
  CONSTRAINT `fk_workerJourney_user` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=33852830 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `workerLabour`
--

DROP TABLE IF EXISTS `workerLabour`;
/*!50001 DROP VIEW IF EXISTS `workerLabour`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `workerLabour` AS SELECT 
 1 AS `businessFk`,
 1 AS `workerFk`,
 1 AS `workCenterFk`,
 1 AS `started`,
 1 AS `ended`,
 1 AS `departmentFk`*/;
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=10915 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `workerMedia`
--

DROP TABLE IF EXISTS `workerMedia`;
/*!50001 DROP VIEW IF EXISTS `workerMedia`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `workerMedia` AS SELECT 
 1 AS `workerFk`,
 1 AS `mediaValue`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `workerTeam`
--

DROP TABLE IF EXISTS `workerTeam`;
/*!50001 DROP VIEW IF EXISTS `workerTeam`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `workerTeam` AS SELECT 
 1 AS `team`,
 1 AS `user`,
 1 AS `id`,
 1 AS `Id_Trabajador`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `workerTeamCollegues`
--

DROP TABLE IF EXISTS `workerTeamCollegues`;
/*!50001 DROP VIEW IF EXISTS `workerTeamCollegues`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `workerTeamCollegues` AS SELECT 
 1 AS `workerFk`,
 1 AS `collegueFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `workerTimeControl`
--

DROP TABLE IF EXISTS `workerTimeControl`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerTimeControl` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userFk` int(10) unsigned NOT NULL,
  `timed` datetime NOT NULL,
  `manual` tinyint(4) NOT NULL DEFAULT '0',
  `order` int(11) DEFAULT NULL,
  `warehouseFk` smallint(6) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `userFk_Timed_uniq` (`userFk`,`timed`),
  KEY `warehouseFkfk1_idx` (`warehouseFk`),
  CONSTRAINT `warehouseFk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `vn2008`.`warehouse` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `workerTimeControl_fk1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3589864 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Fichadas';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workerTimeControlConfig`
--

DROP TABLE IF EXISTS `workerTimeControlConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerTimeControlConfig` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `warehouseFk` smallint(6) unsigned NOT NULL,
  `host` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `warehouseFk_1_idx` (`warehouseFk`),
  CONSTRAINT `warehouseFk_2` FOREIGN KEY (`warehouseFk`) REFERENCES `vn2008`.`warehouse` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workerTimeControlSchedule`
--

DROP TABLE IF EXISTS `workerTimeControlSchedule`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerTimeControlSchedule` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `time` time DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `punique_trhf` (`time`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `workerTimeControl_Journey`
--

DROP TABLE IF EXISTS `workerTimeControl_Journey`;
/*!50001 DROP VIEW IF EXISTS `workerTimeControl_Journey`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `workerTimeControl_Journey` AS SELECT 
 1 AS `userFk`,
 1 AS `dated`,
 1 AS `Journey`,
 1 AS `dayName`,
 1 AS `name`,
 1 AS `firstname`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `workerTimeJourneyNG`
--

DROP TABLE IF EXISTS `workerTimeJourneyNG`;
/*!50001 DROP VIEW IF EXISTS `workerTimeJourneyNG`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `workerTimeJourneyNG` AS SELECT 
 1 AS `userFk`,
 1 AS `dated`,
 1 AS `Journey`,
 1 AS `dayName`,
 1 AS `name`,
 1 AS `firstname`*/;
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=23782 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` datetime NOT NULL,
  `warehouseFk` smallint(6) unsigned NOT NULL,
  `agencyModeFk` int(11) NOT NULL,
  `travelingDays` int(11) NOT NULL DEFAULT '1',
  `price` double NOT NULL DEFAULT '0',
  `bonus` double NOT NULL DEFAULT '0',
  `isVolumetric` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`,`name`),
  KEY `fk_zone_1_idx` (`warehouseFk`),
  KEY `fk_zone_2_idx` (`agencyModeFk`),
  CONSTRAINT `fk_zone_1` FOREIGN KEY (`warehouseFk`) REFERENCES `vn2008`.`warehouse` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `fk_zone_2` FOREIGN KEY (`agencyModeFk`) REFERENCES `vn2008`.`Agencias` (`Id_Agencia`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=43 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` date NOT NULL,
  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` (
  `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,
  PRIMARY KEY (`id`),
  UNIQUE KEY `zoneGeo_lft_IDX` (`lft`) USING BTREE,
  UNIQUE KEY `zoneGeo_rgt_IDX` (`rgt`) USING BTREE,
  KEY `zoneGeo_name_idx` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `zoneIncluded`
--

DROP TABLE IF EXISTS `zoneIncluded`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneIncluded` (
  `zoneFk` int(11) NOT NULL,
  `geoFk` int(11) NOT NULL,
  `isIncluded` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`zoneFk`,`geoFk`),
  KEY `geoFk_idx` (`geoFk`),
  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 */;

--
-- Dumping events for database 'vn'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `envialiaThreHoldChecker` */;
DELIMITER ;;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
/*!50003 SET character_set_client  = utf8mb4 */ ;;
/*!50003 SET character_set_results = utf8mb4 */ ;;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone      = @@time_zone */ ;;
/*!50003 SET time_zone             = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `envialiaThreHoldChecker` ON SCHEDULE EVERY 1 DAY STARTS '2019-02-07 07:00:00' ON COMPLETION NOT PRESERVE ENABLE COMMENT 'comprueba el rango de numeros para las etiquetas de envialia' DO BEGIN
	DECLARE vActualNumber BIGINT;
	DECLARE vEndRange BIGINT;
    DECLARE vIsAlreadyNotified BOOLEAN;
    DECLARE vNotificationThrehold INT;

	SELECT actualNumber, endRange, isAlreadyNotified, notificationThrehold 
			INTO vActualNumber, vEndRange, vIsAlreadyNotified, vNotificationThrehold
		FROM envialiaConfig;
    
	IF (vActualNumber+vNotificationThrehold) >= vEndRange AND
        vIsAlreadyNotified = FALSE
	THEN
		 INSERT INTO vn2008.mail (`to`, subject, text)
			VALUES ('cau@verdnatura.es',
				'Hablar con envialia, acercandonos al numero final del rango permitido para las etiquetas',
                CONCAT('Numero actual: ', vActualNumber, ' , numero final: ',vEndRange)); 
		UPDATE envialiaConfig SET isAlreadyNotified = TRUE;
	END IF;
    
	IF (vActualNumber+vNotificationThrehold) < vEndRange AND
        vIsAlreadyNotified = TRUE
	THEN
		UPDATE envialiaConfig SET isAlreadyNotified = FALSE;
	END IF;
    
END */ ;;
/*!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 `printingQueueChecker` */;;
DELIMITER ;;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
/*!50003 SET character_set_client  = utf8mb4 */ ;;
/*!50003 SET character_set_results = utf8mb4 */ ;;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone      = @@time_zone */ ;;
/*!50003 SET time_zone             = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`z-developer`@`%`*/ /*!50106 EVENT `printingQueueChecker` ON SCHEDULE EVERY 10 MINUTE STARTS '2018-05-01 00:00:00' ON COMPLETION NOT PRESERVE ENABLE DO BEGIN

	DECLARE vCurrentCount INT;
	DECLARE vCheckSum INT;
    DECLARE vIsAlreadyNotified BOOLEAN;

	SELECT COUNT(*), SUM(id) INTO vCurrentCount, vCheckSum
		FROM printingQueue WHERE state = 1;
        
    SELECT isAlreadyNotified INTO vIsAlreadyNotified 
    	FROM printingQueueCheck;
		
	IF (SELECT lastCount FROM printingQueueCheck) = vCurrentCount AND
		(SELECT lastCheckSum FROM printingQueueCheck) = vCheckSum AND
        vIsAlreadyNotified = FALSE
	THEN
		INSERT INTO vn2008.mail (`to`, subject, text)
			VALUES ('cau@verdnatura.es',
				'servidor de impresion parado', 
                CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas'));
		UPDATE printingQueueCheck SET isAlreadyNotified = TRUE;
	END IF;
    
    IF (SELECT lastCount FROM printingQueueCheck) > vCurrentCount AND
        vIsAlreadyNotified = TRUE
	THEN
		UPDATE printingQueueCheck SET isAlreadyNotified = FALSE;
	END IF;
    
	UPDATE printingQueueCheck
		SET lastCount = vCurrentCount,
			lastCheckSum = vCheckSum;
END */ ;;
/*!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 `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 */ ;;
/*!50106 DROP EVENT IF EXISTS `travel_doRecalc` */;;
DELIMITER ;;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
/*!50003 SET character_set_client  = utf8mb4 */ ;;
/*!50003 SET character_set_results = utf8mb4 */ ;;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone      = @@time_zone */ ;;
/*!50003 SET time_zone             = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`z-developer`@`%`*/ /*!50106 EVENT `travel_doRecalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-05-17 10:52:29' ON COMPLETION PRESERVE ENABLE DO CALL travel_doRecalc */ ;;
/*!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 OR  NOT vSupplierIsUeeMember) AND vSupplierCountry != vClientCountry 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 `barcodeToItem` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `barcodeToItem`(vBarcode VARCHAR(22)) RETURNS int(11)
    DETERMINISTIC
BEGIN

	DECLARE vItemFk INT;

	SELECT id INTO vItemFk
		FROM vn.item
        WHERE id = vBarcode;
        
	IF vItemFk THEN 
		RETURN vItemFk;
	END IF;

	SELECT itemFk INTO vItemFk 
		FROM buy 
        WHERE id = vBarcode;
	
    IF vItemFk THEN 
		RETURN vItemFk;
	END IF;
    
	SELECT itemFk INTO vItemFk 
		FROM itemBarcode 
        WHERE code = vBarcode;
  
	RETURN vItemFk;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `bionicCalcReverse` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `bionicCalcReverse`(vWarehouse INT,
    vMargin DECIMAL(10,3),
    vRetailedPrice DECIMAL(10,3),
    vM3 DECIMAL(10,3),
    vConsigna INT,
    vAgencia INT) RETURNS decimal(10,3)
BEGIN

	DECLARE COEFICIENTE_DE_INFLACION_GENERAL INT DEFAULT 1.3;
    DECLARE DENSIDAD_MINIMA_PESO_VOLUMETRICO INT DEFAULT 167;
    DECLARE VOLUMEN_CAJA_VERDNATURA BIGINT DEFAULT 138000;    
    DECLARE vCustomer INT;
    DECLARE vComponentRecovery INT DEFAULT 17;
	DECLARE vComponentMana INT DEFAULT 39;
	DECLARE vComponentPort INT DEFAULT 15;
	DECLARE vComponentMargin INT DEFAULT 29;
	DECLARE vComponentCost INT DEFAULT 28;
    DECLARE vCost DECIMAL(10,2);
	DECLARE vItem INT DEFAULT 98;
    
    SELECT clientFk INTO vCustomer FROM address WHERE id = vConsigna;

	-- Creamos la tabla tmp.bionic_component
    DROP TEMPORARY TABLE IF EXISTS tmp.bionic_component;
    CREATE TEMPORARY TABLE tmp.bionic_component LIKE
		vn2008.template_bionic_component;
        
   -- Margen
	INSERT INTO tmp.bionic_component (warehouse_id, item_id, component_id, cost)
		SELECT vWarehouse, vItem, vComponentMargin, vMargin;
				        
   -- Recobro
	INSERT INTO tmp.bionic_component (warehouse_id, item_id, component_id, cost)
		SELECT vWarehouse, vItem, vComponentRecovery, ROUND(LEAST(recobro,0.25), 3) 
			FROM bi.claims_ratio
				WHERE Id_Cliente = vCustomer AND recobro > 0.009;
                            
	-- Componente de maná automático, en función del maná acumulado por el comercial.
	INSERT INTO tmp.bionic_component (warehouse_id, item_id, component_id, cost)
		SELECT vWarehouse, vItem, vComponentMana, ROUND(prices_modifier_rate, 3)
			FROM client c 
				JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador 
			WHERE ms.prices_modifier_activated AND c.id = vCustomer LIMIT 1;
 
	-- Reparto
	INSERT INTO tmp.bionic_component (warehouse_id, item_id, component_id, cost)
		SELECT vWarehouse, vItem, vComponentPort, COEFICIENTE_DE_INFLACION_GENERAL
				* ROUND(
						vM3 
						* az.price 
						* az.inflation 
						/ VOLUMEN_CAJA_VERDNATURA, 4
						)
			FROM agencyMode ag
				JOIN address a ON a.id = vConsigna AND ag.id = vAgencia
				JOIN agencyProvince ap ON ap.agencyFk = ag.agencyFk AND ap.warehouseFk = vWarehouse AND ap.provinceFk = a.provinceFk
				JOIN agencyModeZone az ON az.agencyModeFk = vAgencia AND az.zone = ap.zone AND az.itemFk = 71 AND az.warehouseFk = vWarehouse;
    
    -- Coste
	SELECT vRetailedPrice - SUM(cost) INTO vCost
		FROM tmp.bionic_component;

	INSERT INTO tmp.bionic_component (warehouse_id, item_id, component_id, cost)
		VALUES ( vWarehouse, vItem, vComponentCost,vCost);
        
    RETURN vCost;
            
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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)
    READS SQL DATA
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);
    DECLARE vHasDebt BOOLEAN;

	SELECT COUNT(*) INTO vHasDebt
		FROM `client` c
		WHERE c.id = vClient AND c.typeFk = 'normal';
	
	IF NOT vHasDebt THEN
		RETURN 0;
	END IF;

	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;
    DECLARE vHasMana BOOLEAN;

	SELECT COUNT(*) INTO vHasMana
		FROM `client` c
		WHERE c.id = vClient AND c.typeFk = 'normal';
	
	IF NOT vHasMana THEN
		RETURN 0;
	END IF;
	
	SELECT max(dated) INTO vFromDated
	FROM vn.clientManaCache;

	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.shipped < TIMESTAMPADD(DAY,1,CURDATE())
							AND a.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 r.Fechacobro <= CURDATE()
					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 g.Fecha <= CURDATE()
					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 `clientGetSalesPerson` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `clientGetSalesPerson`(vClientFk INT, vDated DATE) RETURNS int(11)
    DETERMINISTIC
BEGIN
/**
 * Dado un id cliente y una fecha, devuelve su comercial para ese dia, teniendo 
 * en cuenta la jerarquía de las tablas: 1º la de sharingClient, 2º la de 
 * sharingCart y tercero la de clientes.
 *
 * @param vClientFk El id del cliente
 * @param vDated Fecha a comprobar
 * @return El id del comercial para la fecha dada
 **/
	DECLARE vSalesperson INT DEFAULT NULL;
	DECLARE vSubstitute INT DEFAULT NULL;
	DECLARE vLoop BOOLEAN;

	-- Obtiene el comercial original y el de sharingClient

	SELECT c.salesPersonFk, s.workerFk
		INTO vSalesperson, vSubstitute
		FROM client c
			LEFT JOIN sharingClient s
				ON c.id = s.clientFk
					AND vDated BETWEEN s.started AND s.ended
		WHERE c.id = vClientFk
		ORDER BY s.id
        LIMIT 1;

	-- Si no hay ninguno en sharingClient busca en sharingCart

	IF vSubstitute IS NOT NULL
	THEN
		SET vSalesperson = vSubstitute;
	ELSEIF vSalesperson IS NOT NULL
	THEN
		DROP TEMPORARY TABLE IF EXISTS tmp.stack;
		CREATE TEMPORARY TABLE tmp.stack
			(INDEX (substitute))
			ENGINE = MEMORY
			SELECT vSalesperson substitute;

		l: LOOP
			SELECT workerSubstitute INTO vSubstitute
				FROM sharingCart 
				WHERE vDated BETWEEN started AND ended
					AND workerFk = vSalesperson
				ORDER BY id
				LIMIT 1;
				
			IF vSubstitute IS NULL THEN
				LEAVE l;
			END IF;
				
			SELECT COUNT(*) > 0 INTO vLoop
				FROM tmp.stack WHERE substitute = vSubstitute;

			IF vLoop THEN
				LEAVE l;
			END IF;
			
			INSERT INTO tmp.stack SET
				substitute = vSubstitute;
			
			SET vSalesperson = vSubstitute;
		END LOOP;
		
		DROP TEMPORARY TABLE tmp.stack;
	END IF;

	RETURN vSalesperson;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 o 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 `currentRate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `currentRate`(vCurrencyFk INT, vDated DATE) RETURNS decimal(10,4)
BEGIN

	DECLARE curRate DECIMAL(10,4);
    
    SELECT value INTO curRate
		FROM referenceRate
        WHERE dated <= vDated
			AND currencyFk = vCurrencyFk
        ORDER BY dated DESC
        LIMIT 1;

RETURN curRate;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `entry_calcCommission` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `entry_calcCommission`(
	vCurrentCommission INT,
    vTravelFk INT,
    vCurrencyFk INT
) RETURNS int(11)
    READS SQL DATA
BEGIN
	DECLARE vCommission INT;

	IF vCurrencyFk != 2 /* Dollar */ THEN
		RETURN vCurrentCommission;
	END IF;

	SELECT ROUND(-100 * (1 - (1 / r.rate))) INTO vCommission
		FROM travel t
			LEFT JOIN vn2008.reference_min r
				ON r.moneda_id = vCurrencyFk AND r.`date` <= t.shipped
		WHERE t.id = vTravelFk
		ORDER BY r.`date` DESC
		LIMIT 1;
		
	SET vCommission = IFNULL(vCommission, 0);

	RETURN vCommission;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `entry_getCurrency` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `entry_getCurrency`(
	vCurrency INT,
    vSupplierFk INT
) RETURNS int(11)
    READS SQL DATA
BEGIN
	DECLARE vIsDollarAccount BOOL;

	SELECT account LIKE '___4______' INTO vIsDollarAccount
		FROM vn.supplier WHERE id = vSupplierFk;

	IF vIsDollarAccount THEN
		RETURN 2;
	ELSE
		RETURN vCurrency;
	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 FUNCTION IF EXISTS `floramondoNewItemFk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `floramondoNewItemFk`() RETURNS int(11)
BEGIN

	DECLARE vItemFk INT;
    
    SELECT max(id) + 1 INTO vItemFk
		FROM item 
        WHERE id BETWEEN 250000 AND 290000;

	RETURN vItemFk;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `getAlert3State` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 isWaitingForPickUp BOOLEAN DEFAULT FALSE;
	DECLARE vCode VARCHAR(45);
		
	SELECT a.Vista
	INTO vDeliveryType 
		FROM vn2008.Tickets t
			JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia
	WHERE Id_Ticket = vTicket;
		
		CASE vDeliveryType
			WHEN 1 THEN -- AGENCIAS
				SET vCode = 'DELIVERED';
					   
			WHEN 2 THEN -- REPARTO
				SET vCode = 'ON_DELIVERY';
					
			ELSE -- MERCADO, OTROS
				SELECT MIN(t.warehouse_id <> w.warehouse_id) INTO isWaitingForPickUp
					FROM vn2008.Tickets t 
						LEFT JOIN vn2008.warehouse_pickup w 
							ON w.agency_id = t.Id_Agencia
					WHERE t.Id_Ticket = vTicket;
						
			IF isWaitingForPickUp THEN
				SET vCode = 'WAITING_FOR_PICKUP';
					ELSE
				SET vCode = 'DELIVERED';
			END IF;
		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 */ ;
/*!50003 DROP FUNCTION IF EXISTS `getAlert3StateTest` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `getAlert3StateTest`(vTicket INT) RETURNS varchar(45) CHARSET latin1
BEGIN
	DECLARE vDeliveryType INTEGER DEFAULT 0;
		DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE;
		DECLARE vCode VARCHAR(45);
		
	SELECT 
		a.Vista
	INTO vDeliveryType 
		FROM vn2008.Tickets t
			JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia
	WHERE Id_Ticket = vTicket;
		
		CASE vDeliveryType
			WHEN 1 THEN -- AGENCIAS
				SET vCode = 'DELIVERED';
					   
			WHEN 2 THEN -- REPARTO
				SET vCode = 'ON_DELIVERY';
					
			ELSE -- MERCADO, OTROS
				SELECT t.warehouse_id <> w.warehouse_id INTO isWaitingForPickUp
					FROM vn2008.Tickets t 
						LEFT JOIN vn2008.warehouse_pickup w 
							ON w.agency_id = t.Id_Agencia AND w.warehouse_id = t.warehouse_id
					WHERE t.Id_Ticket = vTicket;
						
			IF isWaitingForPickUp THEN
				SET vCode = 'WAITING_FOR_PICKUP';
					ELSE
				SET vCode = 'DELIVERED';
			END IF;
		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 */ ;
/*!50003 DROP FUNCTION IF EXISTS `getDueDate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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;
    
	IF vDayToPay = 0 THEN
		RETURN vDated;
	END IF;
    
	SET vDued = TIMESTAMPADD(DAY,vDayToPay MOD 30, LAST_DAY(TIMESTAMPADD(MONTH, vDayToPay DIV 30, 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 */ ;
/*!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 `getNewItemId` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `getNewItemId`() RETURNS int(11)
BEGIN

	DECLARE newItemId INT;
    
    SELECT i1.id + 1 INTO newItemId
		FROM item i1
			LEFT JOIN item i2 ON i1.id + 1 = i2.id
		WHERE i2.id IS NULL
		ORDER BY i1.id
		LIMIT 1;

	RETURN newItemId;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `getPlacementReserve` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `getPlacementReserve`(vItemFk INT, vWarehouseFk INT) RETURNS varchar(25) CHARSET utf8
BEGIN

	DECLARE vPlacementReserve VARCHAR(25);
    
    SELECT CONCAT(IFNULL(`code`,'--'), ' / ', IFNULL(reserve,'--')) INTO vPlacementReserve
		FROM itemPlacement
        WHERE itemFk = vItemFk
        AND warehouseFk = vWarehouseFk;

RETURN vPlacementReserve;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `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.agencyFk as agency_id
				, t.warehouseFk as warehouse_id
				, a.provinceFk 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.specialPrice
		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;
    -- PAK 22/10/18
    DECLARE PREVIOUS_PREPARATION INT DEFAULT 26;
    DECLARE vHasBeenPreviouslyPrepared INT DEFAULT 0;

	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.agencyFk as agency_id
			, t.warehouseFk as warehouse_id
			, a.provinceFk 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, (code = 'PRINTED_BACK') DESC ,  loadingOrder
		LIMIT 1;

	-- Aviso de ticket para bajar
	SELECT COUNT(*) INTO vHasBeenPreviouslyPrepared
		FROM vncontrol.inter
        WHERE Id_Ticket = vTicket
        AND state_id = PREVIOUS_PREPARATION;
        
	IF vHasBeenPreviouslyPrepared AND ticketWarehouseGet(vTicket) = 1 THEN 
	
		INSERT IGNORE INTO vn.ticketDown(ticketFk) VALUES(vTicket);
        
	END IF;


	RETURN vTicket;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `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` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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
/* JGF 2019-03-04 obsoleto, usar account.userGetId() */
	 /*RETURN getWorker(); */
    RETURN account.userGetId();
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `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 `getWorkerCode` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `getWorkerCode`() RETURNS varchar(3) CHARSET utf8
BEGIN
DECLARE vUserCode VARCHAR(3) CHARSET utf8 COLLATE utf8_unicode_ci;

SELECT code INTO vUserCode
FROM worker
WHERE userFk = account.userGetId();

RETURN vUserCode;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `isIntrastatEntry` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `isIntrastatEntry`(vEntryFk INT) RETURNS int(11)
BEGIN

	DECLARE isIntrastatOperation BOOL DEFAULT FALSE;
    DECLARE vSupplierCountry INT DEFAULT -1;
    DECLARE vClientCountry INT DEFAULT -1;

	SELECT c.id INTO vSupplierCountry
		FROM vn.country c
        JOIN vn.supplier s ON s.countryFk = c.id
        JOIN vn.entry e ON e.supplierFk = s.id
        WHERE e.id = vEntryFk
			AND c.isUeeMember = TRUE;
        
	SELECT c.id INTO vClientCountry
		FROM vn.country c
        JOIN vn.supplier s ON s.countryFk = c.id
        JOIN vn.company co ON co.id = s.id
        JOIN vn.entry e ON e.companyFk = co.id
        WHERE e.id = vEntryFk
			AND c.isUeeMember = TRUE;
    
    IF vSupplierCountry != vClientCountry AND vSupplierCountry * vClientCountry > 0 THEN
    
		SET isIntrastatOperation = TRUE;
        
	END IF;

	RETURN isIntrastatOperation;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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
        LIMIT 1;

	 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 `itemPacking` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `itemPacking`(vBarcode VARCHAR(22), vWarehouseFk INT) RETURNS int(11)
BEGIN

	DECLARE vPacking INTEGER DEFAULT 0;
    DECLARE vItemFk INTEGER;
    
    SELECT IFNULL(packing,0) INTO vPacking 
		FROM vn.buy 
        WHERE id = CAST(vBarcode AS DECIMAL(18,0));
    
    IF NOT vPacking THEN
    
		SELECT vn.barcodeToItem(vBarcode) INTO vItemFk;
    
		SELECT IFNULL(packing,1) INTO vPacking
			FROM 
			(SELECT packing , created
				FROM vn.itemShelving
				WHERE itemFk = vItemFk
			 UNION ALL
			 SELECT b.packing, landing
				FROM vn.buy b
				JOIN cache.last_buy lb ON lb.buy_id = b.id
				WHERE lb.warehouse_id = vWarehouseFk
					AND b.itemFk = vItemFk
			) packings
			ORDER BY created desc
			LIMIT 1;
	
    END IF;
        
	RETURN vPacking;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `itemPlacementGet` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `itemPlacementGet`(vItemFk INT, vWarehouseFk INT) RETURNS varchar(25) CHARSET utf8
BEGIN

	DECLARE vPlacementReserve VARCHAR(25);
    
    SELECT CONCAT(IFNULL(`code`,'--'), ' / ', IFNULL(reserve,'--')) INTO vPlacementReserve
		FROM itemPlacement
        WHERE itemFk = vItemFk
        AND warehouseFk = vWarehouseFk;

RETURN vPlacementReserve;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `messageSend` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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) CHARSET utf8, vMessage TEXT CHARSET utf8) RETURNS int(11)
BEGIN
	DECLARE result INT;
	DECLARE vSenderFk INT;
    
    SELECT id INTO vSenderFk 
		FROM account.user WHERE `name` = account.userGetName();
        
	RETURN (SELECT messageSendWithUser(vSenderFk, vRecipient, vMessage));
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `messageSendWithUser` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `messageSendWithUser`(vSenderFK INT, vRecipient VARCHAR(255) CHARSET utf8, vMessage TEXT CHARSET utf8) RETURNS int(11)
    DETERMINISTIC
BEGIN

	DECLARE vCount INT;
	DECLARE vUuid VARCHAR(255);
	DECLARE vSendDate DATETIME DEFAULT NOW();
	DECLARE vSender VARCHAR(255) CHARSET utf8;

	SELECT `name` INTO vSender 
		FROM account.user WHERE id = vSenderFK;
        
	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 != vSender
				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 = vSender,
			recipient = vRecipient,
			message = vMessage,
			sendDate = vSendDate;

	INSERT INTO messageInbox (uuid, sender, recipient, finalRecipient, message, sendDate) 
		SELECT vUuid, vSender, 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 */ ;
/*!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 `orderTotalVolume` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `orderTotalVolume`(vOrderId INT) RETURNS decimal(10,3)
    READS SQL DATA
BEGIN
	-- Devuelte el volumen total de la orden sumada
	DECLARE vWarehouseId INTEGER;
	DECLARE vVolume DECIMAL(10,3);
 
    SELECT IFNULL(SUM(o.amount * i.compression * r.cm3)/1000000,0) INTO vVolume
		FROM hedera.orderRow o
			JOIN vn.item i ON i.id = o.itemFk
			JOIN bi.rotacion r on r.Id_Article = o.itemFk AND r.warehouse_id = o.warehouseFk
		WHERE o.orderFk = vOrderId;

    RETURN vVolume;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `orderTotalVolumeBoxes` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `orderTotalVolumeBoxes`(vOrderId INT) RETURNS decimal(10,3)
BEGIN

/* 
 *  Devuelve el volumen estimado del ticket sumado, en cajas
 *
 *	idT Numero de ticket
 *	
 */
	DECLARE vVolumeBoxM3 DOUBLE;
    DECLARE vOrderTotalVolumeBoxes DECIMAL(10,1);
    DECLARE vVnBoxId VARCHAR(10) DEFAULT '94';
    
    SELECT volume / 1000000 INTO vVolumeBoxM3 FROM packaging WHERE id = vVnBoxId;
    
    SET vOrderTotalVolumeBoxes = orderTotalVolume(vOrderId) / vVolumeBoxM3;
    
    RETURN vOrderTotalVolumeBoxes;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `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 = 'pasaporte fitosanitario'
        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 `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.ticketFk
   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 `ticketSplitCounter` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketSplitCounter`(vTicketFk INT) RETURNS varchar(15) CHARSET utf8 COLLATE utf8_unicode_ci
    READS SQL DATA
BEGIN
	DECLARE vSplitCounter VARCHAR(15);

	SELECT CONCAT(OK,'/',Total, IF(OK = Total ,' LS','')) INTO vSplitCounter
		FROM
		(
			SELECT count(l.Id_Movimiento) as OK, COUNT(*) as Total
				FROM vn.sale s
					LEFT JOIN vn2008.movement_label l ON l.Id_Movimiento = s.id
				WHERE ticketFk = vTicketFk
		) sub;
	RETURN vSplitCounter;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `ticketTotalVolume` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketTotalVolume`(vTicketId INT) RETURNS decimal(10,3)
    READS SQL DATA
BEGIN
	-- Devuelte el volumen total del ticket sumado
	-- DECLARE vWarehouseId INTEGER;
    -- DECLARE vShippedDate DATE;
	DECLARE vVolume DECIMAL(10,3);
	/*
    SELECT warehouseFk, shipped INTO vWarehouseId,vShippedDate FROM vn.ticket WHERE id = vTicketId;
    
    SELECT IFNULL(SUM(s.quantity * i.compression * r.cm3)/1000000,0) INTO vVolume
		FROM sale s
			JOIN vn.item i ON i.id = s.itemFk
			JOIN bi.rotacion r on r.Id_Article = s.itemFk AND r.warehouse_id = vWarehouseId
		WHERE s.ticketFk = vTicketId;
    */
        SELECT sum(volume) INTO vVolume
			FROM vn2008.v_Movimientos_Volumen_shipping_charge
			WHERE Id_Ticket = vTicketId;
	   
    RETURN vVolume;

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

/* 
 *  Devuelve el volumen estimado del ticket sumado, en cajas
 *
 *	idT Numero de ticket
 *	
 */

	DECLARE vVolumeBoxM3 DOUBLE;
    DECLARE vTicketTotalVolumeBoxes DECIMAL(10,1);
    DECLARE vVnBoxId VARCHAR(10) DEFAULT '94';
    
    SELECT volume / 1000000 INTO vVolumeBoxM3 FROM packaging WHERE id = vVnBoxId;
    
    SET vTicketTotalVolumeBoxes = ticketTotalVolume(vTicketId) / vVolumeBoxM3;
    
    RETURN vTicketTotalVolumeBoxes;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `ticketWarehouseGet` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketWarehouseGet`(vTicketFk INT) RETURNS int(11)
BEGIN

	DECLARE vWarehouseFk INT;

	SELECT warehouseFk INTO vWarehouseFk
		FROM ticket 
		WHERE id = vTicketFk;

	RETURN vWarehouseFk;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `addNoteFromDelivery` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `addNoteFromDelivery`(idTicket INT,nota TEXT)
BEGIN

	DECLARE observationTypeFk INT DEFAULT 3; /*3 = REPARTIDOR*/

	INSERT INTO ticketObservation(ticketFk,observationTypeFk,description)
	VALUES (idTicket,observationTypeFk,nota)
	ON DUPLICATE KEY UPDATE description = CONCAT(ticketObservation.description,VALUES(description),' ');


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE 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`@`%` PROCEDURE `addressTaxArea`()
    READS SQL DATA
BEGIN
/**
 * Devuelve el taxArea para un conjunto de Consignatarios y empresas, 
 *
 * @table tmp.addressCompany(addressFk, companyFk) valores a calcular
 * @return tmp.addressTaxArea(addressFk,companyFk)
 */

    DECLARE vSpainCountryCode INT DEFAULT 1;
    
    DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea;
	CREATE TEMPORARY TABLE tmp.addressTaxArea
		(PRIMARY KEY (addressFk, companyFk))
		ENGINE = MEMORY
		SELECT CASE 
			WHEN (NOT cClient.isUeeMember OR  NOT cSupplier.isUeeMember) AND s.countryFk != c.countryFk THEN 
				'WORLD'
			WHEN cClient.isUeeMember AND cSupplier.isUeeMember AND c.countryFk != s.countryFk AND c.isVies THEN 
				'CEE'
			WHEN a.isEqualizated AND c.countryFk = vSpainCountryCode  THEN 
				'EQU'
			ELSE
				'NATIONAL'
		END AS areaFk, ac.addressFk, ac.companyFk
		FROM tmp.addressCompany ac
			JOIN address a ON a.id = ac.addressFk
			JOIN `client` c ON c.id = a.clientFk
			JOIN country cClient ON cClient.id = c.countryFk
			JOIN supplier s ON s.id = ac.companyFk
            JOIN country cSupplier ON cSupplier.id = s.countryFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `agencyHourGetAgency` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `agencyHourGetAgency`(vAddress INT, vDate DATE)
BEGIN
/**
 * DEPRECATED usar zoneGetAgency
 * Devuelve el listado de agencias disponibles para la fecha 
 * y dirección pasadas.
 *
 * @param vAddress Id de dirección de envío, %NULL si es recogida
 * @param vDate Fecha de recogida
 * @table agencyModeList Listado de agencias disponibles
 */
	DECLARE vAgency INT;
	DECLARE vDone BOOL DEFAULT FALSE;

	DECLARE vCur CURSOR FOR
		SELECT DISTINCT a.id
			FROM agency a
				JOIN agencyHour ah ON ah.agencyFk = a.id;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

	DROP TEMPORARY TABLE IF EXISTS agencyModeList;
	CREATE TEMPORARY TABLE agencyModeList (
		id INT NOT NULL,
		agency VARCHAR(20),
		description VARCHAR(45),
		deliveryMethodFk VARCHAR(45),
		shipped DATE,
		warehouse VARCHAR(45),
		PRIMARY KEY(id)
	)
	ENGINE = MEMORY;

	OPEN vCur;
	FETCH vCur INTO vAgency;

	WHILE NOT vDone
	DO
		CALL vn.agencyHourGetShipped(vDate, vAddress, vAgency);
		INSERT INTO agencyModeList
			SELECT a.id, a.name, a.description,
				a.deliveryMethodFk, ah.shipped, w.name
				FROM agencyMode a
					JOIN tmp.agencyHourGetShipped ah 
					JOIN warehouse w on w.id = ah.warehouseFk
				WHERE a.agencyFk = vAgency
					AND a.web
			ON DUPLICATE KEY UPDATE
				warehouse = CONCAT(warehouse, ', ', w.name);

		FETCH vCur INTO vAgency;
	END WHILE;

	CLOSE vCur;
    
	DROP TEMPORARY TABLE tmp.agencyHourGetShipped;
	SELECT * FROM agencyModeList;
    DROP TEMPORARY TABLE IF EXISTS agencyModeList;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `agencyHourGetFirstShipped` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `agencyHourGetFirstShipped`(vAgencyMode INT, vAddress INT, vWarehouse INT)
BEGIN
/**
  * DEPRECATED usar zoneGetFirstShipped
* Devuelve la primera fecha de envio disponible para una agencia en una direccion y un warehouse
*
* @param vAgencyMode id de la agencia en  vn.agencyMode
* @param vAddress id de la direccion
* @param vWarehouse id del warehouse
* @return vShipped la primera fecha disponible y vLanded la fecha de llegada/recojida
*/    
DECLARE vAgency INT;
DECLARE vShipped DATE;
DECLARE vLanded DATE DEFAULT CURDATE();
	SELECT agencyFk INTO vAgency FROM agencyMode WHERE id= vAgencyMode;

	l: LOOP
    
		CALL agencyHourGetShipped(vLanded,vAddress,vAgency);
        SELECT shipped INTO vShipped 
			FROM tmp.agencyHourGetShipped
			WHERE warehouseFk = vWarehouse LIMIT 1;
	
	IF vShipped THEN
		LEAVE l;
	END IF;
    
    SET vLanded = DATE_ADD(vLanded, INTERVAL +1 DAY);
    
	END LOOP;
    
    SELECT vShipped,vLanded;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `agencyHourGetLanded` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `agencyHourGetLanded`(vDated DATE, vAddress INT, vAgency INT, vWarehouse INT)
BEGIN
/**
  * DEPRECATED usar zoneGetLanded
  * Devuelve una tabla temporal con el dia de recepcion para vDated.
 *
 * @param vDated Fecha de preparacion de mercancia
 * @param vAddress Id de consignatario, %NULL para recogida
 * @param vAgency Id agencia
 * @table tmp.agencyHourGetLanded Datos de recepción
 */
    DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetLanded;
    CREATE TEMPORARY TABLE tmp.agencyHourGetLanded
    ENGINE = MEMORY
        SELECT vWarehouse warehouseFk, landed FROM (
            SELECT * FROM (
                SELECT vWarehouse, TIMESTAMPADD(DAY, ah.substractDay, vDated) landed, ah.substractDay, ah.maxHour
                    FROM agencyHour ah
                    LEFT JOIN address a ON a.id = vAddress
                        WHERE (ah.weekDay = WEEKDAY(TIMESTAMPADD(DAY, ah.substractDay, vDated)) OR ah.weekDay IS NULL)
                            AND (ah.agencyFk = vAgency OR ah.agencyFk IS NULL)
                            AND ah.warehouseFk = vWarehouse
                            AND (ah.provinceFk = a.provinceFk OR ah.provinceFk IS NULL OR vAddress IS NULL)
                            ORDER BY (
                            (ah.weekDay IS NOT NULL) +
                            (ah.agencyFk IS NOT NULL) +
                            (- ah.substractDay) +
                            ((ah.provinceFk IS NOT NULL)*3)
                        ) DESC
            ) t
            LIMIT 1
        ) t
        WHERE IF(vDated = CURDATE(), t.maxHour > HOUR(NOW()), TRUE) AND t.substractDay < 225;
        
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `agencyHourGetShipped` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `agencyHourGetShipped`(vLanded DATE, vAddressFk INT, vAgencyFk INT)
BEGIN
/**
  * DEPRECATED usar zoneGetShipped
 * Devuelve las posibles fechas de envÃ­o de un ticket
 * 
 * @param vLanded La fecha de recepcion
 * @param vAddressFk Id del consignatario
 * @param vAgencyFk Id de la agencia
 * @return tmp.agencyHourGetShipped
 */
	DECLARE vDone BOOL;
	DECLARE vWarehouseFk SMALLINT;

	DECLARE vCur CURSOR FOR
		SELECT w.id warehouseFk
			FROM vn.warehouse w 
			WHERE w.hasAvailable;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

	DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetShipped;
	CREATE TEMPORARY TABLE tmp.agencyHourGetShipped
	(
		warehouseFk TINYINT NOT NULL PRIMARY KEY,
		shipped DATE NOT NULL,
		landed DATE NOT NULL
	)
	ENGINE = MEMORY;

	OPEN vCur;

	l: LOOP
		SET vDone = FALSE;
		FETCH vCur INTO vWarehouseFk;
		
		IF vDone THEN
			LEAVE l;
		END IF;
		INSERT INTO tmp.agencyHourGetShipped (warehouseFk, shipped, landed)
			SELECT vWarehouseFk, shipping, vLanded FROM (
				SELECT TIMESTAMPADD(DAY, -ah.substractDay, vLanded) shipping, ah.maxHour
					FROM agencyHour ah
					LEFT JOIN address a ON a.id = vAddressFk
						WHERE ah.warehouseFk = vWarehouseFk
                            AND (weekDay = WEEKDAY(vLanded)
								OR weekDay IS NULL)
							AND (ah.agencyFk = vAgencyFk
								OR ah.agencyFk IS NULL)
							AND (ah.provinceFk = a.provinceFk
								OR ah.provinceFk IS NULL
								OR vAddressFk IS NULL)
						ORDER BY (
								(ah.weekDay IS NOT NULL) +
								(ah.agencyFk IS NOT NULL) +
								((ah.provinceFk IS NOT NULL) * 3)
							) DESC
						LIMIT 1
			) t
			WHERE t.shipping >= CURDATE()
				AND IF(t.shipping = CURDATE(), t.maxHour > HOUR(NOW()), TRUE);
	END LOOP;

	CLOSE vCur;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `agencyHourGetWarehouse` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `agencyHourGetWarehouse`(vAddress INT, vDate DATE, vWarehouse INT)
BEGIN
/**
  * DEPRECATED usar zoneGetWarehouse
 * Devuelve el listado de agencias disponibles para la fecha,
 * dirección y warehouuse pasadas
 * 
 * @param vAddress no puede ser NULL
 *  @param vWarehouse warehouse donde comprobaremos las agencias y fecha
 * @param vDate Fecha de recogida
 * @table agencyModeWarehouseList Listado de agencias disponibles
 */
	DECLARE vAgency INT;
	DECLARE vDone BOOL DEFAULT FALSE;    
	DECLARE vCur CURSOR FOR
		SELECT DISTINCT a.id
			FROM agency a
				JOIN agencyHour ah ON ah.agencyFk = a.id;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

			IF vAddress IS NULL
	THEN
		CALL util.throw ('Address cannot be null');
	END IF;

	DROP TEMPORARY TABLE IF EXISTS tmp.agencyModeWarehouseList;
	CREATE TEMPORARY TABLE tmp.agencyModeWarehouseList (
		id INT NOT NULL,
		agency VARCHAR(20),
		description VARCHAR(45),
		deliveryMethodFk VARCHAR(45),
		shipped DATE,
		warehouse VARCHAR(45),
		PRIMARY KEY(id)
	)
	ENGINE = MEMORY;
  
	OPEN vCur;
	FETCH vCur INTO vAgency;

	WHILE NOT vDone
	DO
	
		INSERT INTO tmp.agencyModeWarehouseList
			SELECT am.id, am.name, am.description,am.deliveryMethodFk, TIMESTAMPADD(DAY, -ah.substractDay, vDate), w.name
						FROM agencyHour ah
						LEFT JOIN address a ON a.id = vAddress
                        JOIN agencyMode am ON am.agencyFk =  vAgency
						JOIN warehouse w on w.id = ah.warehouseFk
							WHERE ah.warehouseFk = vWarehouse
								AND (weekDay = WEEKDAY(vDate)
									OR weekDay IS NULL)
								AND (ah.agencyFk = vAgency
									OR ah.agencyFk IS NULL)
								AND (ah.provinceFk = a.provinceFk
									OR ah.provinceFk IS NULL
									OR vAddress IS NULL)
								AND TIMESTAMPADD(DAY, -ah.substractDay, vDate) >= CURDATE()
								AND IF(TIMESTAMPADD(DAY, -ah.substractDay, vDate) = CURDATE(), ah.maxHour > HOUR(NOW()), TRUE)
							ORDER BY (
									(ah.weekDay IS NOT NULL) +
									(ah.agencyFk IS NOT NULL) +
									((ah.provinceFk IS NOT NULL) * 3)
								) DESC
							LIMIT 1;


		FETCH vCur INTO vAgency;
	END WHILE;

	CLOSE vCur;
    
	SELECT * FROM tmp.agencyModeWarehouseList;
	DROP TEMPORARY TABLE tmp.agencyModeWarehouseList;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `agencyHourListGetShipped` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `agencyHourListGetShipped`(vDate DATE, vAddress INT, vAgency INT)
BEGIN
 /* * DEPRECATED usar zoneGetShipped
*/
	CALL vn.agencyHourGetShipped(vDate, vAddress, vAgency);

	SELECT * FROM tmp.agencyHourGetShipped;
    
   DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetShipped;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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
/**
 * DEPRECATED usar zoneGetAgency
 * 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 agencyAvailable 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 `artificialBuffer` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `artificialBuffer`(vWarehouseFk INT)
BEGIN

	DECLARE vCalcFk INT;
    
    CALL cache.ticketShippingRefresh(vCalcFk,FALSE,vWarehouseFk);
    
    SELECT 
        `s`.`id` AS `saleFk`,
        `tst`.`updated` AS `Modificado`,
        `s`.`ticketFk` AS `ticketFk`,
        `s`.`isPicked` AS `isPicked`,
        `s`.`itemFk` AS `itemFk`,
        `s`.`quantity` AS `quantity`,
        `s`.`concept` AS `concept`,
        `i`.`size` AS `size`,
        `w`.`code` AS `workerCode`,
        `ip`.`code` AS `Nicho`,
        `ip`.`reserve` AS `Reserva`,
        `st`.`name` AS `Estado`,
        `st`.`order` AS `orden`,tsh.shippingHour, tsh.shippingMinute
    FROM
        (((((((`vn`.`sale` `s`
        JOIN `vn`.`ticket` `t` ON ((`t`.`id` = `s`.`ticketFk`)))
        LEFT JOIN cache.ticketShipping tsh ON ((tsh.ticketFk = t.id)))
        JOIN `vn`.`item` `i` ON ((`i`.`id` = `s`.`itemFk`)))
        JOIN `vn`.`itemType` `it` ON ((`it`.`id` = `i`.`typeFk`)))
        JOIN `vn`.`ticketStateToday` `tst` ON ((`tst`.`ticket` = `t`.`id`)))
        JOIN `vn`.`state` `st` ON ((`st`.`id` = `tst`.`state`)))
        JOIN `vn`.`itemPlacement` `ip` ON (((`ip`.`itemFk` = `s`.`itemFk`)
            AND (`ip`.`warehouseFk` = `t`.`warehouseFk`))))
        JOIN `vn`.`worker` `w` ON ((`w`.`id` = `tst`.`worker`))
    WHERE
        ((`t`.`shipped` >= `util`.`yesterday`())
			AND tsh.calc_id = vCalcFk
            AND (ASCII(`ip`.`code`) = ASCII('5'))
            AND (`t`.`warehouseFk` = vWarehouseFk)
            AND (`st`.`order` BETWEEN 3 AND 6))
    ORDER BY tsh.shippingHour, tsh.shippingMinute;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buyUltimate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `buyUltimate`(vWarehouseFk SMALLINT, vDate DATE)
BEGIN
/**
 * Calcula las Ãºltimas compras realizadas hasta una fecha
 *
 * @param vWarehouseFk Id del almacÃ©n
 * @param vDate Compras hasta fecha
 * @return tmp.buyUltimate
 */
	CALL cache.last_buy_refresh (FALSE);

	DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate;
	CREATE TEMPORARY TABLE tmp.buyUltimate
		(PRIMARY KEY (itemFk, warehouseFk),
        INDEX(itemFk))
		ENGINE = MEMORY 
		SELECT item_id itemFk, buy_id buyFk, warehouse_id warehouseFk
			FROM cache.last_buy
            WHERE warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL;

	CALL vn.buyUltimateFromInterval(vWarehouseFk, CURDATE(), vDate);

	REPLACE INTO tmp.buyUltimate
		SELECT itemFk, buyFk, warehouseFk
			FROM tmp.buyUltimateFromInterval
            WHERE warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL;

	DROP TEMPORARY TABLE tmp.buyUltimateFromInterval;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buyUltimateFromInterval` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `buyUltimateFromInterval`(vWarehouseFk SMALLINT, vStarted DATE, vEnded DATE)
BEGIN
/**
 * Calcula las Ãºltimas compras realizadas 
 * desde un rango de fechas.
 *
 * @param vWarehouseFk Id del almacÃ©n
 * @param vStarted Fecha inicial
 * @param vEnded Fecha fin
 * @return tmp.buyUltimateFromInterval
 */
    IF vEnded IS NULL THEN
        SET vEnded = vStarted;
    END IF;
    
    IF vEnded < vStarted THEN
		SET vStarted = TIMESTAMPADD(MONTH, -1, vEnded);
    END IF;

	DROP TEMPORARY TABLE  IF EXISTS tmp.buyUltimateFromInterval;
	CREATE TEMPORARY TABLE tmp.buyUltimateFromInterval
		 (INDEX (itemFk), INDEX(buyFk)) ENGINE = MEMORY
		SELECT 
				b.itemFk, 
                t.warehouseInFk warehouseFk, 
                MULTIMAX(t.landed, b.id) buyFk, 
                MAX(t.landed) landed
			FROM buy b
				JOIN entry e ON e.id = b.entryFk
				JOIN travel t ON t.id = e.travelFk
			WHERE t.landed BETWEEN vStarted AND vEnded
				AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
				AND b.price2 > 0
				AND NOT b.isIgnored
			GROUP BY itemFk, warehouseInFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_afterUpsert` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `buy_afterUpsert`(vSelf INT)
BEGIN
/**
 * Triggered actions when a buy is updated or inserted.
 *
 * @param vSelf The buy reference
 */
	DECLARE vEntryFk INT;
	DECLARE vItemFk INT;
	DECLARE vStickers INT;
	DECLARE vPacking INT;
	DECLARE vWarehouse INT;
	DECLARE vWarehouseOut INT;
	DECLARE vIsMerchandise BOOL;
	DECLARE vIsFeedStock BOOL;

	SELECT entryFk, itemFk, stickers, packing
		INTO vEntryFk, vItemFk, vStickers, vPacking
		FROM buy
		WHERE id = vSelf;

	SELECT t.warehouseInFk, t.warehouseOutFk
		INTO vWarehouse, vWarehouseOut
		FROM entry e
			JOIN travel t ON t.id = e.travelFk
		WHERE e.id = vEntryFk;

	SELECT k.merchandise INTO vIsMerchandise
		FROM itemCategory k
			JOIN itemType it ON it.categoryFk = k.id
			JOIN item i ON i.typeFk = it.id
		WHERE i.id = vItemFk;

	IF vIsMerchandise THEN
		REPLACE bi.rotacion	SET
			Id_Article = vItemFk,
			warehouse_id = vWarehouse,
			cm3 = vn2008.cm3_unidad(vSelf);
	END IF;

	SELECT isFeedStock INTO vIsFeedStock
		FROM warehouse WHERE id = vWarehouseOut AND id <> 13;

	IF vIsFeedStock AND vn2008.has_notify_passport(vItemFk, vSelf) THEN
		CALL vn2008.notify_passport(vItemFk, vStickers, vPacking, vSelf);
		CALL vn2008.insert_producer_plantpassport(vSelf);
	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 `buy_checkGrouping` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `buy_checkGrouping`(vGrouping INT)
BEGIN
/**
 * Checks the buy grouping, throws an error if it's invalid.
 *
 * @param vGrouping The grouping
 */
	IF vGrouping = 0 THEN
		SIGNAL SQLSTATE '45000'
			SET MESSAGE_TEXT = 'Grouping cannot be zero';
	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 `carrosOficialesANoOficiales` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `carrosOficialesANoOficiales`()
BEGIN

DECLARE done BOOL DEFAULT FALSE;
DECLARE vClientFk INT;
DECLARE vQuantity INT;
DECLARE vTicketFk INT;
DECLARE vAgencyTypeFk INT DEFAULT 628;


DECLARE rs CURSOR FOR
		SELECT clientFk, sum(quantity) as carros
			FROM `ticketPackaging` tp
				JOIN ticket t ON t.id = tp.ticketFk
			WHERE packagingFk = 'cc'
				and t.shipped between '2017-10-30' AND '2019-01-06 23:59:59'
			group by clientFk
			having carros != 0;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN rs;

FETCH rs INTO vClientFk, vQuantity;

--  WHILE NOT done DO

	CALL vn.ticketCreate(vClientFk, '2019-01-06', 13, 442, NULL, vAgencyTypeFk, NULL, '2019-01-01', vTicketFk);
    
    INSERT INTO vn.ticketPackaging(ticketFk, packagingFk, quantity)
		VALUES (vTicketFk, 'cc', - VQuantity);
        
	INSERT INTO vn.ticketPackaging(ticketFk, packagingFk, quantity)
		VALUES (vTicketFk, 'dc', VQuantity);
        
	INSERT INTO vn.sale(ticketFk, itemFk, concept)
		VALUES (vTicketFk, 90, 'Regularización CCs 2019');
    
    CALL vn.`ticketStateUpdate`(vTicketFk, 'DELIVERED'); -- entregado
    
--     FETCH rs INTO vClientFk, vQuantity;

-- END WHILE;


CLOSE rs;

SELECT vTicketFk;


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 oneYearAgo DATE;
	DECLARE twoYearsAgo DATE;
	DECLARE fourYearsAgo DATE;

	SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE());
	SET oneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE());
	SET twoYearsAgo = TIMESTAMPADD(YEAR,-2,CURDATE());
	SET fourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE());

	DELETE FROM vn.message WHERE sendDate < vDateShort;
	DELETE FROM vn.messageInbox WHERE sendDate < vDateShort;
	DELETE FROM vn.messageInbox WHERE sendDate < vDateShort;
	DELETE FROM vn.workerTimeControl WHERE timed < fourYearsAgo;
	DELETE FROM vn.itemShelving WHERE created < CURDATE() AND visible = 0;

	UPDATE vn.shelving s
			LEFT JOIN vn.itemShelving it ON it.shelvingFk = s.code
		SET it.visible = 0
			WHERE it.shelvingFk IS NULL;
			
	CALL vn.ticketPackagingRecovery;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `clearShelvingList` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clearShelvingList`(vShelvingFk VARCHAR(8))
BEGIN

	UPDATE vn.itemShelving 
    SET visible = 0, available = 0
    WHERE  shelvingFk COLLATE utf8_unicode_ci =vShelvingFk COLLATE utf8_unicode_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 `clientCreate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clientCreate`(
	vFirstname VARCHAR(50),
    vSurnames VARCHAR(50), 
    vFi VARCHAR(9), 
    vAddress TEXT, 
    vPostcode CHAR(5),
    vCity VARCHAR(25),
    vProvinceFk SMALLINT(5),
    vCompanyFk SMALLINT(5),
    vPhone VARCHAR(11),
    vUserFk INT)
BEGIN
/**
 * Create new client
 *
 */
    DECLARE vPayMethodFk INT DEFAULT 4;
    DECLARE vDueDay INT DEFAULT 5;
    DECLARE vDefaultCredit DECIMAL(10, 2) DEFAULT 300.00;
    DECLARE vIsTaxDataChecked TINYINT(1) DEFAULT 1;
	DECLARE vHasCoreVnl BOOLEAN DEFAULT TRUE;
    DECLARE vMandateTypeFk INT DEFAULT 2;
    
	INSERT INTO `client` (
			id,
			name,
			street,
			fi,
			phone,
			provinceFk,
			city,
			postcode,
			socialName,
			payMethodFk,
			dueDay,
			credit,
			isTaxDataChecked,
			hasCoreVnl,
			isEqualizated)
		VALUES (
			vUserFk,
			CONCAT('TR ', vFirstname, ' ', vSurnames),
			vAddress,
			vFi,
			vPhone,
			vProvinceFk,
			vCity,
			vPostcode,
			CONCAT(vSurnames, ' ', vFirstname), 
			vPayMethodFk,
			vDueDay,
			vDefaultCredit,
			vIsTaxDataChecked,
			vHasCoreVnl,
			FALSE
		) ON duplicate key update  
            payMethodFk = vPayMethodFk,
			dueDay = vDueDay,
			credit = vDefaultCredit,
			isTaxDataChecked = vIsTaxDataChecked,
			hasCoreVnl = vHasCoreVnl,
            isActive = TRUE;
	
    IF (SELECT COUNT(*) FROM mandate WHERE clientFk = vUserFk AND companyFk = vCompanyFk AND mandateTypeFk = vMandateTypeFk) = 0 THEN
		INSERT INTO mandate (clientFk, companyFk, mandateTypeFk)
			VALUES (vUserFk, vCompanyFk, vMandateTypeFk);
	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 `clientDebtSpray` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clientDebtSpray`(vClientFk INT)
BEGIN

	/* Reparte el saldo de un cliente en greuge en la cartera que corresponde, y desasigna el comercial
    *
    *
    */

	DECLARE vClientDebt DOUBLE;
    
    SELECT vn.clientGetDebt(vClientFk, CURDATE()) INTO vClientDebt;
    
    INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk)
		VALUES (vClientFk, 'Saldo pendiente', vClientDebt, CURDATE(), 5);
    
    CALL vn.clientGreugeSpray(vClientFk, TRUE, '', TRUE);
    
    INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk)
			SELECT vClientFk, 'Liquidación cliente', sum(amount), CURDATE(), 5
				FROM vn.greuge
				WHERE clientFk = vClientFk;
                
	UPDATE vn.client 
		SET salesPersonFk = NULL 
		WHERE id = vClientFk;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 
			AND c.payMethodFk NOT IN (5,8)
            AND c.typeFk = 'normal';
            
		UPDATE vn.client c
			JOIN bi.defaulters d ON d.client = c.id AND d.date = TIMESTAMPADD(DAY,10,CURDATE())
			JOIN vn.config ON TRUE
			SET c.isFreezed = TRUE
		WHERE d.amount > config.defaultersMaxAmount 
			AND c.payMethodFk IN (5,8)
            AND c.typeFk = 'normal';
		
    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 `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`@`%` PROCEDURE `clientGetDebt`(vDate DATE)
BEGIN
/**
 * Calcula el riesgo para los clientes activos
 *
 * @table tmp.clientGetDebt(clientFk)
 * @param vDate Fecha maxima de los registros
 * @return tmp.risk
 */
	DECLARE vStarted DATETIME DEFAULT TIMESTAMPADD(DAY, - DAYOFMONTH(CURDATE()) - 5, CURDATE());
	DECLARE vEnded DATETIME;

	SET vEnded = TIMESTAMP(IFNULL(vDate, CURDATE()), '23:59:59');
    
	DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
	CREATE TEMPORARY TABLE tmp.ticket
		(INDEX (ticketFk))
		ENGINE = MEMORY
		SELECT id ticketFk, c.clientFk
			FROM ticket t
				JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk
			WHERE refFk IS NULL
				AND shipped BETWEEN vStarted AND vEnded;

	CALL ticketGetTotal();
    
    DROP TEMPORARY TABLE IF EXISTS tClientRisk;
    CREATE TEMPORARY TABLE tClientRisk 
		ENGINE = MEMORY
        SELECT cr.customer_id clientFk, SUM(cr.amount) amount
			FROM bi.customer_risk cr
				JOIN tmp.clientGetDebt c ON c.clientFk = cr.customer_id
			GROUP BY cr.customer_id;
            
	INSERT INTO tClientRisk
        SELECT c.clientFk, SUM(r.amountPaid)
			FROM receipt r
				JOIN tmp.clientGetDebt c ON c.clientFk = r.clientFk
			WHERE r.payed > vEnded
			GROUP BY c.clientFk;

	INSERT INTO tClientRisk
		SELECT t.clientFk, CAST(-SUM(t.amount) / 100 AS DECIMAL(10,2))
				FROM hedera.tpvTransaction t
					JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk
				WHERE t.receiptFk IS NULL
					AND t.status = 'ok'
				GROUP BY t.clientFk;
                    
	INSERT INTO tClientRisk
		SELECT t.clientFk, total
			FROM tmp.ticketTotal tt
				JOIN tmp.ticket t ON t.ticketFk = tt.ticketFk;

	DROP TEMPORARY TABLE IF EXISTS tmp.risk;
	CREATE TEMPORARY TABLE tmp.risk
		(PRIMARY KEY (clientFk))
		ENGINE = MEMORY
		SELECT clientFk, SUM(amount) risk
			FROM client c
				JOIN tClientRisk cr ON cr.clientFk = c.id
			WHERE c.isActive
			GROUP BY c.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 `clientGetDebtDiary` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clientGetDebtDiary`(vClientFK INT, vCompanyFk INT)
BEGIN
/**
 * Devuelve el registro de deuda
 *
 * @param vClientFK Id del cliente
 * @param vCompanyFk Id de la empresa
 */
	DECLARE vDone BOOL;
	DECLARE vDate DATETIME;
    DECLARE vTotalBalance DOUBLE DEFAULT 0.00;
    DECLARE vCreated DATETIME;
    DECLARE vIssued DATETIME;
    DECLARE vBalance DOUBLE DEFAULT 0.00;
    DECLARE cur CURSOR FOR
		SELECT 
				created, 
				issued, 
				ROUND(amount, 2) AS balance
			FROM invoiceOut
			WHERE clientFk = vClientFk AND companyFk = vCompanyFk 
		UNION ALL 
		SELECT 
				created, 
				payed, 
				ROUND(-1 * amountPaid, 2) AS balance
			FROM receipt 
			WHERE clientFk = vClientFk AND companyFk = vCompanyFk
		ORDER BY issued, created;
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
            
	OPEN cur;
    
    proc: LOOP
		SET vDone = FALSE;
        
        FETCH cur INTO vCreated, vIssued, vBalance;

        IF vDone THEN
			LEAVE proc;
		END IF;

        SET vTotalBalance = vTotalBalance + vBalance;

		IF CAST(ABS(vTotalBalance) AS UNSIGNED) = 0 THEN
			SET vDate = vIssued;
            SET vDone = TRUE;
        END IF;
	END LOOP;
	
	CLOSE cur;
    
	SELECT 
        issued, 
        CAST(debtOut AS DECIMAL(10,2)) debtOut, 
        CAST(debtIn AS DECIMAL(10,2)) debtIn,
		ref, 
        companyFk, 
        priority
	FROM
		(SELECT 
                NULL AS issued, 
                SUM(amountUnpaid) AS debtOut, 
				NULL AS debtIn, 
				'Saldo Anterior' AS ref, 
                companyFk,
                0 as priority 
			FROM 
				(SELECT SUM(amount) AS amountUnpaid, companyFk, 0 
					FROM invoiceOut
					WHERE clientFk = vClientFK 
						AND issued < vDate  
					GROUP BY companyFk 
                
				UNION ALL 
            
				SELECT SUM(-1 * amountPaid), companyFk, 0 
					FROM receipt 
					WHERE clientFk = vClientFK 
						AND payed < vDate 
					GROUP BY companyFk) AS transactions 
			GROUP BY companyFk 
            
			UNION ALL 
		
			SELECT 
					issued, 
					amount as debtOut, 
					NULL AS debtIn, 
					ref,
					companyFk,
					1 
				FROM invoiceOut 
				WHERE clientFk = vClientFK 
					AND issued >= vDate
			UNION ALL 
		
			SELECT 
					r.payed, 
					NULL as debtOut, 
					r.amountPaid, 
					r.invoiceFk, 
					r.companyFk,
					0 
				FROM receipt r
				WHERE r.clientFk = vClientFK 
					AND r.payed >= vDate) t 
			INNER JOIN `client` c ON c.id = vClientFK 
	HAVING debtOut <> 0 OR debtIn <> 0 
    ORDER BY issued, priority DESC, debtIn;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `clientGreugeSpray` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clientGreugeSpray`(IN vClientFk INT, IN onlyForHisOwner BOOL, IN vWorkerCode VARCHAR(3), IN vWithMana BOOLEAN)
BEGIN

	DECLARE vGreuge DECIMAL(10,2);
	DECLARE vOwner INT;
	DECLARE vTotalSale INT;
	DECLARE vGreugeTypeFk INT DEFAULT 5; -- HERENCIA
    DECLARE vGreugeTypeMana INT DEFAULT 3;-- Maná
    DECLARE vMana DECIMAL(10,2);
    
    SELECT vn.clientGetMana(vClientFk) INTO vMana;
    
    IF vWithMana AND vMana THEN
    
		INSERT INTO vn.greuge(	clientFk,
								description,
                                amount,
                                shipped,
                                greugeTypeFk)
        VALUES(	vClientFk, 
				'Desasignación',
                -1 * vMana,
                CURDATE(),
                vGreugeTypeMana);
    
    END IF;

	SELECT sum(amount) INTO vGreuge
		FROM vn.greuge
		WHERE clientFk = vClientFk;

	IF vGreuge != 0 THEN

		IF LENGTH(vWorkerCode) = 0 THEN

			SELECT salesPersonFk INTO vOwner
				FROM vn.client
				WHERE id = vClientFk;

		ELSE
		
			SELECT id INTO vOwner
				FROM vn.worker
				WHERE code = vWorkerCode COLLATE utf8_general_ci;

		END IF;
		
		DROP TEMPORARY TABLE IF EXISTS tmp.clientList;
		CREATE TEMPORARY TABLE tmp.clientList
			SELECT DISTINCT t.clientFk, floor(cr.yearSale / 12) AS monthSale
				FROM vn.ticket t
					JOIN vn.client c ON c.id = t.clientFk
					JOIN vn.manaSpellers ms ON ms.worker = c.salesPersonFk
					JOIN vn.claimRatio cr ON cr.clientFk = c.id
				WHERE ms.worker = IF(onlyForHisOwner, vOwner, ms.worker)
				AND t.shipped >= TIMESTAMPADD(MONTH,-1,CURDATE())
				AND c.id != vClientFk
				HAVING monthSale > 100;
					
		SELECT SUM(monthSale) INTO vTotalSale
			FROM tmp.clientList;

		INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk)
			SELECT clientFk, CONCAT('Cliente: ',vClientFk), vGreuge * monthSale / vTotalSale, CURDATE(), vGreugeTypeFk
				FROM tmp.clientList
			UNION ALL
			SELECT vClientFk, 'Reparto greuge', -vGreuge, CURDATE(), vGreugeTypeFk;
        
	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 `clientPackagingOverstock` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clientPackagingOverstock`(vClientFk INT, vGraceDays INT )
BEGIN

	DROP TEMPORARY TABLE IF EXISTS tmp.clientPackagingOverstock;
    CREATE TEMPORARY TABLE tmp.clientPackagingOverstock
		ENGINE = MEMORY 
	SELECT itemFk, 
			sum(GotfromClient) - sum(SenttoClient) as devueltos, 
            sum(InvoicedtoClient) - sum(InvoicedfromClient) as facturados,
            LEAST(	
					sum(GotfromClient) - sum(SenttoClient), 
					sum(InvoicedtoClient) - sum(InvoicedfromClient)
				) as abonables
              
            FROM
	(   

		SELECT t.*,
			IF(@month = month, 0, 1) monthEnd,
			@month := month
			FROM      
				(
				SELECT  x.id as ticketFk, 
						date(x.shipped) as shipped, 
						x.itemFk, 
						IFNULL(cast(sum(x.InvoicedtoClient) as DECIMAL(10,0)),0) InvoicedtoClient, 
						IFNULL(cast(sum(x.InvoicedfromClient) as DECIMAL(10,0)),0) InvoicedfromClient, 
						IFNULL(cast(sum(x.SenttoClient) as DECIMAL(10,0)),0) SenttoClient, 
						IFNULL(cast(sum(x.GotfromClient) as DECIMAL(10,0)),0) GotfromClient,
						i.name as concept,
						x.refFk as invoice,
						month(shipped) month,
						x.companyFk
						
				FROM
				(

				SELECT  t.id,
						t.shipped,
						IFNULL(pe.equivalentFk, s.itemFk) itemFk,
						IF(s.quantity > 0, s.quantity, NULL) InvoicedtoClient,
						IF(s.quantity < 0, -s.quantity, NULL) InvoicedfromClient,
						NULL SenttoClient,
						NULL GotfromClient,
						t.refFk,
						@month := 0 month,
						t.companyFk
					FROM vn.sale s
						JOIN vn.ticket t on t.id = s.ticketFk 
						JOIN vn2008.Cubos c ON c.item_id = s.itemFk 
						LEFT JOIN vn.packageEquivalentItem pe ON pe.itemFk = s.itemFk
						WHERE t.clientFk = vClientFk
						AND t.shipped > '2017-11-30' 
						AND c.Retornable
							
				UNION ALL

				SELECT  NULL,
						'2017-11-30',
						IFNULL(pe.equivalentFk, tps.itemFk) itemFk,
						tps.sent InvoicedtoClient,
						tps.returned InvoicedfromClient,
						NULL SenttoClient,
						NULL GotfromClient,
						'Histórico',
						NULL,
						NULL
						
					FROM vn.ticketPackagingStartingStock tps
						LEFT JOIN vn.packageEquivalentItem pe ON pe.itemFk = tps.itemFk
						WHERE tps.clientFk = vClientFk
							AND tps.isForgetable = FALSE

				UNION ALL

				SELECT  t.id,
					t.shipped,
					IFNULL(pe.equivalentFk, p.itemFk) itemFk,
					NULL,
					NULL,
					IF(tp.quantity > 0 AND t.shipped <= TIMESTAMPADD(DAY, - vGraceDays, CURDATE()), tp.quantity, NULL) SenttoClient,
					IF(tp.quantity < 0, -tp.quantity, NULL) GotfromClient,
					NULL AS refFk,
					NULL,
					t.companyFk
				FROM vn.ticketPackaging tp 
					JOIN vn.ticket t on t.id = tp.ticketFk 
					JOIN vn.packaging p ON p.id = tp.packagingFk
					LEFT JOIN vn.packageEquivalentItem pe ON pe.itemFk = p.itemFk
					WHERE clientFk = vClientFk
					AND t.shipped > '2017-11-21' ) x

					JOIN vn.item i ON x.itemFk = i.id
					GROUP BY x.id, x.itemFk
				
			) t
			ORDER BY itemFk, shipped DESC
		) t2
		GROUP BY itemFk
    
;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `clientPackagingOverstockReturn` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clientPackagingOverstockReturn`(vClientFk INT, vGraceDays INT )
BEGIN

	DECLARE vNewTicket INT DEFAULT 0;

	IF account.myUserHasRole('administrative') THEN

		CALL vn.clientPackagingOverstock(vClientFk,vGraceDays);
		
		CALL vn.ticketCreate(
				 vClientFk
				,curdate()
				,13 -- Inventario
				,442 -- Verdnatura
				,NULL -- address
				,628 -- Embalajes
				,NULL -- route
				,curdate()
				,vNewTicket);
				
		INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price)
			SELECT vNewTicket, cpo.itemFk, - cpo.abonables, i.longName, p.price
				FROM tmp.clientPackagingOverstock cpo
					JOIN vn.item i ON i.id = cpo.itemFk
					JOIN vn.packaging p ON p.itemFk = cpo.itemFk
				WHERE cpo.abonables > 0;
				
		INSERT INTO vn.ticketPackaging(ticketFk, packagingFk, quantity)
			SELECT vNewTicket, p.id, cpo.abonables
				FROM tmp.clientPackagingOverstock cpo
					JOIN vn.packaging p ON p.itemFk = cpo.itemFk
				WHERE cpo.abonables > 0;
	
    END IF;
    
		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 `clientRandomSelection` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clientRandomSelection`(vNumero INT)
BEGIN

	DECLARE vClient INT;

	SET @vIndex := 0;

	DROP TEMPORARY TABLE IF EXISTS tmp.client;
    
    CREATE TEMPORARY TABLE tmp.client
		SELECT 	io.clientFk, 
				FALSE as isSelected,
                @vIndex := @vIndex + 1 id
		FROM vn.client c
		JOIN vn.invoiceOut io ON io.clientFk = c.id
		JOIN vn.address a ON a.clientFk = c.id
		JOIN vn.province p ON p.id = a.provinceFk
		WHERE p.name = 'MADRID'
		AND io.issued = '2019-01-31'
		AND a.isDefaultAddress
		AND c.name NOT LIKE 'TR %';
        
	WHILE vNumero DO
    
		SET vClient = FLOOR(RAND() * @vIndex + 1);
        
        IF (SELECT isSelected FROM tmp.client WHERE id = vClient) = FALSE THEN
        
			UPDATE tmp.client 
				SET isSelected = TRUE
				WHERE id = vClient;
		
			SET vNumero = vNumero - 1;
        
        END IF;
    
    END WHILE;

	SELECT * FROM tmp.client JOIN vn.client c ON c.id = clientFk;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `clientRemoveWorker` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clientRemoveWorker`()
BEGIN
	DECLARE done BOOL DEFAULT FALSE;
	DECLARE vClientFk INT;

	DECLARE rs CURSOR FOR
		SELECT c.clientFk
			FROM tmp.clientGetDebt c
				LEFT JOIN tmp.risk r ON r.clientFk = c.clientFk
			WHERE IFNULL(r.risk,0) = 0;
				
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt;
	CREATE TEMPORARY TABLE tmp.clientGetDebt
		SELECT cd.id as clientFk
			FROM bs.clientDied cd
				LEFT JOIN vn.clientProtected cp ON cp.clientFk = cd.id
				JOIN vn.client c ON c.id = cd.id
				JOIN vn.province p ON p.id = c.provinceFk
				JOIN vn.country co ON co.id = p.countryFk
			WHERE  cd.Aviso = 'TERCER AVISO'
				AND cp.clientFk IS NULL
				AND co.country NOT IN ('Portugal','Francia','España exento')
				AND c.salesPersonFk IS NOT NULL;
					
	CALL vn.clientGetDebt(curdate());

	DROP TEMPORARY TABLE IF EXISTS tmp.contador;
	CREATE TEMPORARY TABLE tmp.contador (id INT)
		ENGINE = MEMORY;

	OPEN rs;
	FETCH rs INTO vClientFk;

	WHILE NOT done DO
		INSERT INTO tmp.contador SET id = vClientFk;
		CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE);
		UPDATE vn.client SET salesPersonFk = NULL WHERE id = vClientFk;
		REPLACE bs.clientNewBorn(clientFk, shipped)
			VALUES(vClientFk, CURDATE());
		FETCH rs INTO vClientFk;
	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 `clonTravelComplete` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clonTravelComplete`(IN `vTravelFk` INT, IN `vDateStart` DATE, IN `vDateEnd` DATE, IN `vRef` VARCHAR(255))
BEGIN
    
		DECLARE vTravelNew INT;
        DECLARE vEntryNew INT;
		DECLARE vDone BIT DEFAULT 0;
        DECLARE vAuxEntryFk INT;
		DECLARE vRsEntry CURSOR FOR
			SELECT e.id
				FROM vn.entry e
					JOIN vn.travel t 
						ON t.id = e.travelFk
				WHERE e.travelFk = vTravelFk;
			
		 DECLARE vRsBuy CURSOR FOR
			SELECT b.*
				FROM vn.buy b
					JOIN vn.entry  e 
					ON  b.entryFk = e.id
			WHERE 	e.travelFk = vTravelNew and b.entryFk=entryNew
			ORDER BY e.id;
            
		DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1;
        
        DECLARE EXIT HANDLER FOR SQLEXCEPTION 
			BEGIN 
				ROLLBACK;
				RESIGNAL;
			END;
              
		START TRANSACTION;
              
		INSERT INTO vn.travel (shipped,landed, warehouseInFk, warehouseOutFk, agencyFk, ref, isDelivered, isReceived, m3, kg)
			SELECT vDateStart, vDateEnd,warehouseInFk, warehouseOutFk, agencyFk, vRef, isDelivered, isReceived, m3, kg
				FROM vn.travel
				WHERE id = vTravelFk;
			
		SET vTravelNew = LAST_INSERT_ID();
		SET vDone = 0;	 
		OPEN vRsEntry ;
		FETCH vRsEntry INTO vAuxEntryFk;
		
			WHILE NOT vDone DO
				INSERT INTO vn.entry (supplierFk,
									ref,
                                    isInventory,
                                    isConfirmed, 
                                    isOrdered,
                                    isRaid,
                                    commission,
                                    created,
                                    evaNotes,
                                    travelFk,
                                    currencyFk,
                                    companyFk,
                                    gestDocFk, 
                                    invoiceInFk)
						 SELECT supplierFk,
								ref,
								isInventory,
								isConfirmed, 
								isOrdered,
								isRaid,
								commission,
								created,
								evaNotes,
								vTravelNew,
								currencyFk,
								companyFk,
								gestDocFk, 
								invoiceInFk
						FROM vn.entry
						WHERE id = vAuxEntryFk;
                                    
				SET vEntryNew  = LAST_INSERT_ID();
				
	/*			INSERT INTO vn.buy (
							entryFk,
							itemFk,
							amount,
							buyingValue,
							quantity,
							packageFk,
							stickers,
							freightValue,
							packageValue,
							comissionValue,
							packing,
							`grouping`,
							groupingMode,
							location,
							price1,
							price2,
							price3,
							minPrice,
							producer,
							printedStickers,
							isCkecked)
						SELECT 
								vEntryNew,
								itemFk,
								amount,
								buyingValue,
								quantity,
								packageFk,
								stickers,
								freightValue,
								packageValue,
								comissionValue,
								packing,
								`grouping`,
								groupingMode,
								location,
								price1,
								price2,
								price3,
								minPrice,
								producer,
								printedStickers,
								isCkecked
							FROM buy
                            WHERE entryFk = vAuxEntryFk;*/
                            
                     INSERT INTO vn2008.Compres (Id_Entrada,
												Id_Article,
												Cantidad,
												Costefijo,
												Id_Cubo,
												Etiquetas,
												Portefijo,
												Embalajefijo,
												Comisionfija,
												Packing,
												`grouping`,
												caja,
												Nicho,
												Tarifa1,
												Tarifa2,
												Tarifa3,
												PVP,
												Productor,
												Vida,
												punteo)
								SELECT vEntryNew,
										Id_Article,
										Cantidad,
										Costefijo,
										Id_Cubo,
										Etiquetas,
										Portefijo,
										Embalajefijo,
										Comisionfija,
										Packing,
										`grouping`,
										caja,
										Nicho,
										Tarifa1,
										Tarifa2,
										Tarifa3,
										PVP,
										Productor,
										Vida,
										punteo
									FROM vn2008.Compres
									WHERE Id_Entrada = vAuxEntryFk;       
									
                              
				FETCH vRsEntry INTO vAuxEntryFk;
			END WHILE;
		CLOSE vRsEntry;
        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 `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 `createPedidoInterno` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `createPedidoInterno`(vItemFk INT,vQuantity INT)
BEGIN

	
	UPDATE vn.item SET upToDown = vQuantity WHERE id = vItemFk;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cristalBall` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `cristalBall`()
BEGIN
/*
*se utiliza en campaña
* sirve para tener un control del stock en Silla y fuentes
*
*/

DECLARE vLastDate DATETIME DEFAULT '2018-10-30 23:59';
DECLARE vWarehouse INT DEFAULT 1;

SELECT  date(sub2.dat) dat, 
		sub2.longName, 
        sub2.size, 
        sub2.subName, 
        cast(sub2.entra as decimal(10,1)) as entra, 
        cast(sub2.sale as decimal(10,1)) as sale,
        sub2.itemFk,
		@saldo := entra + sale + ifnull(fue.pal,0) + IF(sub2.itemFk = @item, @saldo, 0) as saldo,
        @item := sub2.itemFk as kk,
        cast(fue.pal as decimal(10,1)) as pal
FROM
(
	SELECT * FROM
	(
	SELECT  e.dat,
			e.item_id as itemFk,
			i.longName,
			i.size,
			i.subName,
			sum(e.amount * r.cm3) / 2000000  as entra,
			0 as sale
	FROM vn2008.item_entry_in e
		JOIN vn.item i ON i.id = e.item_id
		JOIN vn.itemType it ON it.id = i.typeFk
		JOIN vn.itemCategory ic ON ic.id = it.categoryFk
		JOIN bi.rotacion r ON r.Id_Article = e.item_id AND r.warehouse_id = e.warehouse_id
		WHERE e.dat BETWEEN CURDATE() AND vLastDate
			AND e.warehouse_id = vWarehouse
			AND ic.merchandise
            AND e.isVirtualStock is FALSE
		GROUP BY e.dat, e.item_id
		
		UNION ALL
		
		SELECT  s.dat,
			s.item_id as itemFk,
			i.longName,
			i.size,
			i.subName,
			0 as entra,
			sum(s.amount * r.cm3) / 2000000  as sale
			FROM vn2008.item_out s
				JOIN vn.item i ON i.id = s.item_id
				JOIN vn.itemType it ON it.id = i.typeFk
				JOIN vn.itemCategory ic ON ic.id = it.categoryFk
				JOIN bi.rotacion r ON r.Id_Article = s.item_id AND r.warehouse_id = s.warehouse_id
				WHERE s.dat BETWEEN CURDATE() AND vLastDate
					AND s.warehouse_id = vWarehouse
					AND ic.merchandise
				GROUP BY date(s.dat), s.item_id
				
		UNION ALL
		
			SELECT  util.yesterday(),
			@item := st.item_id as itemFk,
			i.longName,
			i.size,
			i.subName,
			st.amount * r.cm3 / 2000000 ,
			@saldo := 0
			FROM cache.stock st
				JOIN vn.item i ON i.id = st.item_id
				JOIN vn.itemType it ON it.id = i.typeFk
				JOIN vn.itemCategory ic ON ic.id = it.categoryFk
				JOIN bi.rotacion r ON r.Id_Article = st.item_id AND r.warehouse_id = st.warehouse_id
			WHERE st.warehouse_id = vWarehouse
					AND ic.merchandise
				
		) sub
	ORDER BY itemFk, dat, entra DESC) sub2
     LEFT JOIN
        (
        SELECT itemFk, 
        - sum(visible / packing)  as pal
        FROM vn.itemShelving WHERE shelvingFk = 'FUE'
        GROUP BY itemFk) fue ON fue.itemFk = sub2.itemFk AND sub2.dat = util.yesterday()
        ;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `dayMinuteWorker` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `dayMinuteWorker`(vDateFrom DATETIME, vDateTo DATETIME)
BEGIN

DECLARE vDateStart DATETIME DEFAULT DATE(vDateFrom);
DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDateTo);

SET @ordr := 0;
SET @user := 0;

DROP TEMPORARY TABLE IF EXISTS tmp.dayMinuteWorker;
CREATE TEMPORARY TABLE tmp.dayMinuteWorker
	ENGINE = MEMORY
	SELECT 	sub3.id,
			sub3.hh as Hora,
			sub3.mm as Minuto,
			sub3.userFk,
			sub3.code as CodigoTrabajador,
			sub3.firstname as Nombre,
			sub3.lastName as Apellidos,
			sub3.warehouseFk as Almacen,
            w.name as NombreAlmacen
		FROM vn.warehouse w
        JOIN
		(
		SELECT 	id,
				hh,
				mm,
				userFk,
				code,
				firstname,
				lastName,  
				@ordr := IF(@user != userFk,0,@ordr),
				IF(@ordr MOD 2, 'presente','--') as estado, 
				@ordr := IFNULL(sub2.`order`,@ordr), 
				@user := IFNULL(sub2.`userFk`,@user),
				warehouseFk
			FROM
			(
			SELECT 	dm.id, 
					dm.hh, 
					dm.mm, 
					users.userFk, 
					sub.`order`, 
					users.code, 
					firstName, 
					lastName,
					users.warehouseFk
				FROM dayMinute dm
					JOIN
						(
						SELECT DISTINCT 	wtc.userFk , 
											code , 
											firstName, 
											lastName,
											IFNULL(warehouseFk,1) warehouseFk
							FROM vn.workerTimeControl wtc
								JOIN vn.worker w ON w.userFk = wtc.userFk
								WHERE timed BETWEEN vDateStart AND vDateEnd
						) users 
					
					LEFT JOIN
						(
						SELECT  `order`, 
								wtc.userFk, 
								hour(timed) * 100 + minute(timed) as dayMinuteFk
							FROM  vn.workerTimeControl wtc 
								WHERE timed BETWEEN vDateStart AND vDateEnd
								ORDER BY wtc.userFk, `order`
						) sub ON sub.dayMinuteFk = dm.id AND sub.userFk = users.userFk
				ORDER BY userFk,dm.id
			) sub2
		) sub3 ON sub3.warehouseFk = w.id
		WHERE estado = 'presente'
			AND sub3.id BETWEEN HOUR(vDateFrom) *100 + MINUTE(vDateFrom) AND HOUR(vDateTo) *100 + MINUTE(vDateTo);
--  SELECT * FROM tmp.dayMinuteWorker;

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

	UPDATE duaEntry de
		JOIN 
			( SELECT b.entryFk, sum(b.quantity * b.buyingValue) as total
					FROM buy b
						JOIN duaEntry de ON de.entryFk = b.entryFk
                        WHERE duaFk = vDuaFk
					GROUP BY b.entryFk
        	 ) sub ON sub.entryFk = de.entryFk
             
        LEFT JOIN 
			(SELECT e.id, sum(iit.taxableBase) as euros
				FROM entry e
					JOIN invoiceInTax iit ON iit.invoiceInFk = e.invoiceInFk
                    JOIN duaEntry de ON de.entryFk = e.id
                    WHERE de.duaFk = vDuaFk
				GROUP BY e.id
			) sub2 ON sub2.id = de.entryFk
            
		SET de.value = sub.total,
			de.euroValue = sub2.euros
        WHERE duaFk = vDuaFk;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `duaInvoiceInBooking` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `duaInvoiceInBooking`(vDuaFk INT)
BEGIN


	DECLARE done BOOL DEFAULT FALSE;
	DECLARE vInvoiceFk INT;
    DECLARE vASIEN BIGINT DEFAULT 0;
    DECLARE vCounter INT DEFAULT 0;
    
	DECLARE rs CURSOR FOR
		SELECT e.invoiceInFk
			FROM entry e
				JOIN duaEntry de ON de.entryFk = e.id
                JOIN invoiceIn ii ON ii.id = e.invoiceInFk
            WHERE de.duaFk = vDuaFk
				AND de.customsValue
				AND ii.isBooked = FALSE;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	OPEN rs;
     
	UPDATE invoiceIn ii
			JOIN entry e ON e.invoiceInFk = ii.id
            JOIN duaEntry de ON de.entryFk = e.id
            JOIN dua d ON d.id = de.duaFk
		SET ii.isBooked = TRUE,
			ii.booked = IFNULL(ii.booked,d.booked),
			ii.operated = IFNULL(ii.operated,d.operated),
            ii.issued = IFNULL(ii.issued,d.issued),
            ii.bookEntried = IFNULL(ii.bookEntried,d.bookEntried),
            e.isConfirmed = TRUE
		WHERE d.id = vDuaFk;
    
    SELECT IFNULL(ASIEN,0) INTO vASIEN
		FROM dua
			WHERE id = vDuaFk;
    
	FETCH rs INTO vInvoiceFk;
     
	WHILE NOT done DO

		CALL invoiceInBookingMain(vInvoiceFk);
        
        IF vCounter > 0 OR vASIEN > 0 THEN
        
			UPDATE vn2008.XDiario x
				JOIN config c ON c.ASIEN = x.ASIEN
                SET x.ASIEN = vASIEN;
        
        ELSE
        
			SELECT ASIEN INTO vASIEN FROM config;
            
		END IF;
			     
        SET vCounter = vCounter + 1;
        
		FETCH rs INTO vInvoiceFk;

	END WHILE;
    
    CLOSE rs;
    
    UPDATE dua 
        SET ASIEN = vASIEN
        WHERE id = vDuaFk;
        
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `duaParcialMake` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `duaParcialMake`(vDuaFk INT)
BEGIN

	DECLARE vNewDuaFk INT;

	INSERT INTO dua(awbFk,companyFk)
		SELECT awbFk,companyFk
			FROM dua
            WHERE id = vDuaFk;
	
	SELECT LAST_INSERT_ID() INTO vNewDuaFk;
    
    INSERT INTO duaEntry(duaFk, entryFk, value, customsValue)
		SELECT vNewDuaFk, entryFk, value, value - customsValue
			FROM duaEntry
            WHERE duaFk = vDuaFk
            AND value != customsValue;

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

	DECLARE vBookNumber INT;
    DECLARE vBookDated DATE;
    DECLARE vDiff DECIMAL(10,2);
    DECLARE vApunte BIGINT;
    
	SELECT IFNULL(d.ASIEN,MAX(x.ASIEN) + 1 )
		INTO vBookNumber
		FROM vn2008.XDiario x
			LEFT JOIN dua d ON d.id = vDuaFk ;
    
    SELECT IFNULL(bookEntried, CURDATE()) INTO vBookDated
		FROM dua
        WHERE id = vDuaFk;
    
	-- Apunte de la aduana

	INSERT INTO vn2008.XDiario(
		ASIEN,
		FECHA,
		SUBCTA,
		CONCEPTO, 
		EUROHABER,
        SERIE,
		empresa_id,
        CLAVE,
        FACTURA)

	SELECT 
			vBookNumber,
			d.bookEntried,
			'4700000999',
			CONCAT('DUA ',d.code),
			sum(di.amount * tr.rate / 100) EUROHABER,
            'R',
			d.companyFk,
            vDuaFk,
            vDuaFk
		FROM duaIntrastat di
			JOIN intrastat ist ON ist.id = di.intrastatFk
            JOIN (SELECT rate, taxClassFk
					FROM
						(SELECT rate, taxClassFk
							FROM invoiceInTaxBookingAccount ta
                            WHERE ta.effectived <= vBookDated
                            ORDER BY ta.effectived DESC
						) tba
					GROUP BY taxClassFk
                  ) tr ON tr.taxClassFk = ist.taxClassFk          
			JOIN dua d ON d.id = di.duaFk
            WHERE di.duaFk = vDuaFk;
            
        -- Apuntes por tipo de IVA y proveedor
        
		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,
			vBookDated FECHA,
			tr.account SUBCTA,
			'4330002067' CONTRA,
			sum(dt.tax) EURODEBE,
			sum(dt.base) BASEEURO, 
			CONCAT('DUA nº',d.code) CONCEPTO,
			d.id FACTURA,
			dt.rate IVA,
			'*' AUXILIAR, 
			'D' SERIE,
			d.issued FECHA_EX,
			d.operated FECHA_OP,
			d.code FACTURAEX,
			1 NFACTICK,
			1 L340,
			TRUE LDIFADUAN,
			1 TIPOCLAVE,
			1 TIPOEXENCI,
			1 TIPONOSUJE,
			5 TIPOFACT,
			1 TIPORECTIF,
			IF(s.countryFk IN (30, 1), 1, 4) TERIDNIF,
			s.nif TERNIF,
			s.name TERNOM,
			d.companyFk,
			IFNULL(d.bookEntried, d.booked) FECREGCON
		FROM duaTax dt
			JOIN dua d ON dt.duaFk = d.id
            JOIN (SELECT account, rate
					FROM
						(SELECT rate, account
							FROM invoiceInTaxBookingAccount ta
                            WHERE ta.effectived <= vBookDated
                            AND taxAreaFk = 'WORLD'
                            ORDER BY ta.effectived DESC
						) tba
					GROUP BY rate
                  ) tr ON tr.rate = dt.rate 
			JOIN supplier s ON s.id = d.companyFk
		WHERE d.id = vDuaFk
        GROUP BY dt.rate;
/*
	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,
			vBookDated FECHA,
			tr.account SUBCTA,
			inv.account CONTRA,
			dt.tax EURODEBE,
			dt.base BASEEURO, 
			CONCAT('COMPRA s/fra ',inv.supplierRef,':',LEFT(inv.name, 10)) CONCEPTO,
			inv.serialNumber FACTURA,
			dt.rate IVA,
			'*' AUXILIAR, 
			'W' SERIE,
			d.issued FECHA_EX,
			d.operated FECHA_OP,
			d.code FACTURAEX,
			1 NFACTICK,
			1 L340,
			TRUE LDIFADUAN,
			1 TIPOCLAVE,
			1 TIPOEXENCI,
			1 TIPONOSUJE,
			5 TIPOFACT,
			1 TIPORECTIF,
			IF(inv.countryFk IN (30, 1), 1, 4) TERIDNIF,
			inv.nif TERNIF,
			inv.name TERNOM,
			d.companyFk,
			IFNULL(d.bookEntried, d.booked) FECREGCON
	FROM duaTax dt
			JOIN dua d ON dt.duaFk = d.id
            JOIN (SELECT account, rate
					FROM
						(SELECT rate, account
							FROM invoiceInTaxBookingAccount ta
                            WHERE ta.effectived <= vBookDated
                            AND taxAreaFk = 'WORLD'
                            ORDER BY ta.effectived DESC
						) tba
					GROUP BY rate
                  ) tr ON tr.rate = dt.rate 
			JOIN
				(SELECT s.countryFk, s.account, ii.supplierRef, s.name, ii.id as serialNumber, s.nif, s.id
                FROM duaEntry de 
				JOIN entry e ON e.id = de.entryFk
				JOIN invoiceIn ii ON ii.id = e.invoiceInFk
				JOIN supplier s ON s.id = ii.supplierFk
                GROUP BY s.id
				) inv ON inv.id = dt.supplierFk
		WHERE d.id = vDuaFk;
*/
	SELECT SUM(EURODEBE) -SUM(EUROHABER), MAX(id) INTO vDiff, vApunte
		FROM vn2008.XDiario
		WHERE ASIEN = vBookNumber;
     
	UPDATE vn2008.XDiario
		SET BASEEURO = 100 * (EURODEBE - vDiff) / IVA,
			EURODEBE = EURODEBE - vDiff			
		WHERE id = vApunte;
    
    UPDATE vn.dua
		SET ASIEN = vBookNumber
        WHERE id = vDuaFk;
            
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `duaTaxUpdate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `duaTaxUpdate`(vDuaFk INT)
BEGIN

	DECLARE vSPAIN INT DEFAULT 1;
	DECLARE vDated DATE;
    DECLARE vTotalDUABase DECIMAL(10,2);

	SELECT IFNULL(operated, CURDATE()) INTO vDated
		FROM dua
        WHERE id = vDuaFk;
    
    SELECT sum(amount) INTO vTotalDUABase
		FROM duaIntrastat
        WHERE duaFk = vDuaFk;
    
    DELETE FROM duaTax
		WHERE duaFk = vDuaFk;
        
    INSERT INTO duaTax(duaFk, supplierFk, taxClassFk, base)    
		SELECT 	vDuaFk, supplierFk, taxClassFk, sum(sub.Base) as Base
			FROM intrastat ist
				JOIN
				(SELECT
						e.supplierFk, 
						i.intrastatFk,
						CAST(sum(b.quantity * b.buyingValue *  de.customsValue / de.value)  * di.amount/ tei.Base AS DECIMAL(10,2)) as Base
					FROM buy b 
						JOIN item i ON i.id = b.itemFk
						JOIN entry e ON e.id = b.entryFk
						JOIN duaEntry de ON de.entryFk = e.id
						JOIN
							(
								SELECT 	i.intrastatFk,
										CAST(sum(b.quantity * b.buyingValue *  de.customsValue / de.value) 	AS DECIMAL(10,2)) as Base
									FROM buy b 
										JOIN item i ON i.id = b.itemFk
										JOIN entry e ON e.id = b.entryFk
										JOIN duaEntry de ON de.entryFk = e.id
									WHERE de.duaFk = vDuaFk
									GROUP BY i.intrastatFk
							
							) tei ON tei.intrastatFk = i.intrastatFk
						JOIN 
							(
								SELECT intrastatFk, sum(amount) as amount
									FROM duaIntrastat
                                    WHERE duaFk = vDuaFk
                                    GROUP BY intrastatFK
                            ) di ON di.intrastatFk = i.intrastatFk
					WHERE de.duaFk = vDuaFk
					GROUP BY e.supplierFk, i.intrastatFk
					HAVING Base 
				) sub ON ist.id = sub.intrastatFk
				GROUP BY ist.taxClassFk, sub.supplierFk;
            
		UPDATE duaTax dt
			JOIN 
				(SELECT taxClassFk, rate
					FROM
					(SELECT taxClassFk, rate
						FROM invoiceInTaxBookingAccount 
						WHERE effectived <= vDated
							AND countryFk = vSPAIN
						ORDER BY effectived DESC
					) ba1
                    GROUP BY taxClassFk
				) ba2 ON dt.taxClassFk = ba2.taxClassFk
			SET dt.rate = ba2.rate,
				dt.tax = dt.base * ba2.rate / 100;
                
                
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `entryConverter`(IN `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 `entryPrepare` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `entryPrepare`(IN `idE` BIGINT)
BEGIN
 SELECT
        b.quantity / b.packing AS Paquetes,
        b.packing AS `Grouping`,
        barcode,
        'ASEGURADO' AS asegurado,
        ic.name,
        ic.order,
        s.name AS Consignatario,
        e.supplierFk AS Id_Cliente,
        e.isOrdered,
        e.isConfirmed,
        10 AS Calidad,
        LPAD(IFNULL(cpd.id, ip.code),
                5,
                '0') AS path,
        b.entryFk AS Id_Ticket,
        t.landed AS Fecha,
        b.itemFk,
        b.quantity,
        i.name AS Concepte,
        i.size,
        i.inkFk,
        i.category,
        o.code AS Origen,
        0 AS Bultos,
        wIn.`name` AS Tipo,
        0 AS OK,
        0 AS Reservado,
        i.stems,
        b.id AS Id_Movimiento,
        ip.code,
        'PEDIDO ASEGURADO' AS MSG,
        0 AS Seguro,
        i.image,
        pr.name AS producer
         FROM vn.buy b
        JOIN vn.entry e ON b.entryFk = e.id
        JOIN vn.travel t ON t.id = e.travelFk
        JOIN vn.warehouse wIn ON wIn.id = t.warehouseInFk
        JOIN vn.warehouse wOut ON wOut.id = t.warehouseOutFk
        JOIN vn.item i ON i.id = b.itemFk                                       
        JOIN vn.itemType it ON it.id =i.typeFk
        JOIN vn.itemCategory ic ON ic.id = it.categoryFk
        JOIN vn.packaging pkg ON pkg.id = b.packageFk
        LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND ip.warehouseFk = wIn.id AND ip.warehouseFk = t.warehouseOutFk
        LEFT JOIN (SELECT itemFk, code AS barcode FROM vn.itemBarcode GROUP BY itemFk) ib ON ib.itemFk = b.itemFk
        LEFT JOIN vn.origin o ON o.id = i.originFk
        LEFT JOIN vn.supplier s ON s.id = e.supplierFk
        LEFT JOIN vn.producer pr on pr.id = i.producerFk
        LEFT JOIN vn.coolerPathDetail cpd ON LEFT(ip.code, 3) = cpd.hallway
    WHERE
        NOT wIn.isFeedStock AND NOT e.isInventory AND NOT e.isRaid
        AND e.id = 158772
        AND i.typeFk IS NOT NULL
        AND ic.merchandise IS NOT 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 `entryWithItem` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `entryWithItem`(IN `vShipmentWarehouse` INT, IN `vLandingWarehouse` INT, IN `vSale` INT, IN `vVolume` INT, IN `vGrossMargin` DECIMAL(10,2), IN `vInOutDate` DATE)
BEGIN

    DECLARE vTravel INT;
    DECLARE vEntry INT;
    DECLARE vBucket VARCHAR(10);
    DECLARE vAgencyDirectFromProvider INT DEFAULT 15;

	-- seleccionamos travel
	SELECT t.id, e.id INTO vTravel, vEntry
		FROM travel t LEFT JOIN entry e ON t.id = e.travelFk
        WHERE t.landed = vInOutDate AND t.shipped = vInOutDate AND t.warehouseOutFk = vShipmentWarehouse 
			AND t.warehouseInFk = vLandingWarehouse AND t.agencyFk = vAgencyDirectFromProvider
	LIMIT 1; 
	
    -- creamos el travel si es necesario
    IF IFNULL(vTravel, FALSE) = FALSE THEN
		INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk, agencyFk)
			VALUES (vInOutDate, vInOutDate, vLandingWarehouse, vShipmentWarehouse, vAgencyDirectFromProvider);
		SELECT LAST_INSERT_ID() INTO vTravel;
    END IF;
    
    -- creamos la Entrada si es necesario
	IF IFNULL(vEntry, FALSE) = FALSE THEN
		INSERT INTO entry (supplierFk, travelFk)
				VALUES (13, vTravel); -- proveedor 'MOVIMIENTO ALMACEN'
		SELECT LAST_INSERT_ID() INTO vEntry;
	END IF;
            
	 -- creamos el cubo si es necesario
	SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1;
	IF vBucket IS NULL THEN
		INSERT INTO packaging (id, volume)
				VALUES (CONCAT('dm',vVolume/1000), vVolume);
		SELECT LAST_INSERT_ID() INTO vBucket;
	END IF;

	INSERT INTO buy(itemFk,quantity, entryFk, packageFk, packing, `grouping`, groupingMode, buyingValue, freightValue, packageValue,
				comissionValue, price2, price3) 
	 SELECT itemFk,
			quantity,
			vEntry,
			vBucket,
			1 packing,
			1 `grouping`,
			0 groupingMode,
			s.price - vGrossMargin,
			0 Portefijo,
			0 Embalajefijo,
			0 Comisionfija,
			SUM(s.price) + vGrossMargin Tarifa2,
			SUM(s.price) + vGrossMargin Tarifa3
		FROM sale s
			JOIN saleComponent sc ON sc.saleFk = s.id
		WHERE s.id = vSale;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `getDayExpeditions` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `getDayExpeditions`()
BEGIN

	SELECT 
		e.expeditions_id as expeditionFk, 
        date_format(e.odbc_date,'%Y-%m-%d') as expeditionDate,
        e.ticket_id as ticketFk,
        t.routeFk as routeFk
    FROM vn2008.expeditions  e
    INNER JOIN vn.ticket t ON t.id =  e.ticket_id
    WHERE DATE(odbc_date) = 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 `getDeliveryWorkers` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `getDeliveryWorkers`()
BEGIN
SELECT  w.id,
		concat(p.firstname," ",p.name) AS fullName,
		w.code AS workerCode, 
        pwc.name,
        rl.routeFk as routeLoader
	FROM postgresql.person AS p  
			LEFT JOIN vn.worker AS w ON p.id_trabajador=w.id  
			LEFT JOIN (SELECT MIN(profile_id) AS pid, person_id FROM postgresql.profile GROUP BY person_id) AS pp ON p.person_id=pp.person_id  
			LEFT JOIN vn2008.profile_labour_payroll AS plp ON pp.pid=plp.profile_id 
			LEFT JOIN (SELECT MAX(business_id) AS bimax, client_id FROM postgresql.business GROUP BY client_id) AS pbv ON pbv.client_id = plp.profile_id  
			LEFT JOIN postgresql.business_labour AS pbl ON pbl.business_id = pbv.bimax
			LEFT JOIN vn2008.department AS pd ON pd.department_id = pbl.department_id
			LEFT JOIN postgresql.workcenter AS pwc ON pwc.workcenter_id=pbl.workcenter_id
			LEFT JOIN vn.user u ON u.id=w.userFK  
            LEFT JOIN vn.routeLoadWorker rl ON rl.workerFk = w.id
	WHERE p.id_trabajador Is Not Null 
		AND pd.name='REPARTO' 
		AND u.active<>0
	ORDER BY pwc.name ASC,p.firstname ASC;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `getItemUbication` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `getItemUbication`(vItemFk INT)
BEGIN

	SELECT 	pk.code as Parking,
			sh.code as Matricula,
            ish.visible as visible,
            ish.available as Disponible,
            ish.level as level
		FROM vn.itemShelving ish
			JOIN vn.shelving sh ON sh.`code` = ish.shelvingFk
            JOIN vn.parking pk ON pk.id = sh.parkingFk
		WHERE ish.itemFk = vItemFk;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `getItemVisibleAvailable` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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`(
	vItem INT,
    vDate DATE,
    vWarehouse TINYINT,
    vRefresh BOOL)
BEGIN
	DECLARE vVisibleCalc INT;
    DECLARE vAvailableCalc INT;
    
    -- FIXME: Android app is always passing %TRUE for #vRefresh, this leads to DB performance issues
	CALL cache.visible_refresh(vVisibleCalc, vRefresh, vWarehouse);
    CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/, 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, an.reserve
  		FROM vn2008.Articles a 
			LEFT JOIN vn2008.Articles_nicho an
				ON a.Id_Article = an.Id_Article AND an.warehouse_id = vWarehouse
			LEFT JOIN cache.visible v
				ON v.item_id = a.Id_Article AND v.calc_id = vVisibleCalc
			LEFT JOIN cache.available av
				ON av.item_id = a.Id_Article AND av.calc_id = vAvailableCalc
			LEFT JOIN vn2008.Origen O
				ON O.id = a.id_origen
			LEFT JOIN vn2008.producer p
				ON p.producer_id = a.producer_id
		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 */ ;
/*!50003 DROP PROCEDURE IF EXISTS `getPedidosInternos` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `getPedidosInternos`()
BEGIN

	SELECT id,name as description,upToDown as  quantity FROM vn.item WHERE upToDown;

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

/**
 * Devuelve el ticket que debe de preparar el trabajador del altillo
 *
 * @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;
    DECLARE vMovimiento INT DEFAULT NULL;
    DECLARE PREVIOUS_PREPARATION INT DEFAULT 26;
    DECLARE vHasBeenPreviouslyPrepared INT DEFAULT 0;

	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 *
		FROM  vn.ticketToPrepare
        WHERE Id_Trabjador = vWorker OR Id_Trabjador = 0;
                
			 
	CALL vn2008.production_buffer_set_priority;
	 
	SELECT Id_Ticket
		FROM tmp.production_buffer
		ORDER BY Hora, Minuto
		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 `intrastat_data_neto_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 `intrastat_data_neto_Update`(IN vinvoiceInFk INT)
BEGIN

UPDATE vn2008.intrastat_data id
	JOIN (
		SELECT 	i.intrastatFk,
				sum(r.cm3 * b.quantity) * i.density / 1000000  as neto
			FROM vn.entry e 
				JOIN vn.travel tr ON tr.id = e.travelFk
				JOIN vn.buy b ON b.entryFk = e.id
				JOIN vn.item i ON i.id = b.itemFk
				JOIN bi.rotacion r ON r.Id_Article = i.id AND tr.warehouseInFk = r.warehouse_id
			WHERE e.invoiceInFk = vinvoiceInFk
			GROUP BY i.intrastatFk) sub ON sub.intrastatFk = id.intrastat_id
	SET id.neto = ROUND(sub.neto,1)
	WHERE id.recibida_id = vInvoiceInFk;

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

DECLARE done BOOL DEFAULT FALSE;
DECLARE vTicketFk INT;

DECLARE rs CURSOR FOR
		SELECT id FROM vn.ticket 
			WHERE shipped = util.yesterday() 
				AND clientFk = 400
                AND warehouseFk IN (1,44);

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN rs;

FETCH rs INTO vTicketFk;

WHILE NOT done DO
   
    INSERT INTO vn.inventoryFailure(dated, itemFk, quantity, value, warehouseFk, throwerFk)
		SELECT 	t.shipped, 
				s.itemFk, 
				s.quantity, 
				b.buyingValue + b.freightValue + b.packageValue + b.comissionValue,
				t.warehouseFk, 
				w.id
			FROM vn.ticket t
				JOIN vn.sale s ON s.ticketFk = t.id
				LEFT JOIN cache.last_buy lb ON lb.warehouse_id = t.warehouseFk AND item_id = s.itemFk
				LEFT JOIN vn.buy b ON b.id = lb.buy_id
				LEFT JOIN vn.worker w ON w.code = LEFT(s.concept, 3)
		WHERE t.id = vTicketFk
			AND s.quantity > 0;

	FETCH rs INTO vTicketFk;
    
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 `inventoryMake` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `inventoryMake`(vDate DATE, vWh INT)
proc: BEGIN
/**
 * Recalcula los inventarios de todos los almacenes, si vWh = 0
 *
 * @param vDate Fecha de los nuevos inventarios
 */
	
   
	DECLARE vDone BOOL;
	DECLARE vEntryFk INT;
	DECLARE vTravelFk INT;
	DECLARE vDateTime DATETIME DEFAULT TIMESTAMP(vDate, '00:00:00');
	DECLARE vDeleteDate DATE DEFAULT TIMESTAMPADD(DAY, -2, vDate);
    DECLARE vDateLastInventory DATE;
    DECLARE vDateYesterday DATETIME DEFAULT TIMESTAMPADD(SECOND,-1,vDate);

	DECLARE cWarehouses CURSOR FOR
		SELECT id FROM vn.warehouse WHERE isInventory AND vWh IN (0,id);

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	SELECT vDateYesterday;

	OPEN cWarehouses;
	SET @isModeInventory := TRUE;
	l: LOOP

		SET vDone = FALSE;
		FETCH cWarehouses INTO vWh;

		IF vDone THEN
			LEAVE l;
		END IF;

		SELECT MAX(landed) INTO vDateLastInventory
			FROM vn.travel tr
            JOIN vn.entry e ON e.travelFk = tr.id
            JOIN vn.buy b ON b.entryFk = e.id
			WHERE warehouseOutFk = 13
				AND landed < vDate
                AND e.supplierFk = 4
				AND warehouseInFk = vWh;
        
        -- Generamos travel, si no existe.
        SET vTravelFK = 0;
        
        SELECT id INTO vTravelFk
			FROM vn.travel
            WHERE warehouseOutFk = 13
				AND warehouseInFk = vWh
                AND landed = vDate
                AND agencyFk = 53
                AND ref = 'inventario'
			LIMIT 1;
        
        IF NOT vTravelFK THEN
        
			INSERT INTO vn.travel SET
				warehouseOutFk = 13,
				warehouseInFk = vWh,
				shipped = vDateTime,
				landed = vDate,
				agencyFk = 53,
				ref = 'inventario',
				isDelivered = TRUE,
				isReceived = TRUE;

			SELECT LAST_INSERT_ID() INTO vTravelFk; 
            
		END IF;
        
        -- Generamos entrada si no existe, o la vaciamos.
        SET vEntryFk = 0;
        
        SELECT id INTO vEntryFk
			FROM vn.entry
            WHERE supplierFk = 4
            AND travelFk = vTravelFk;

		IF NOT vEntryFk THEN

			INSERT INTO entry SET
				supplierFk = 4,
				isConfirmed = TRUE,
				isOrdered = TRUE,
				travelFk = vTravelFk;

			SELECT LAST_INSERT_ID() INTO vEntryFk;
            
		ELSE
        
			DELETE FROM vn.buy WHERE entryFk = vEntryFk;
            
		END IF;

		-- Preparamos tabla auxilar
		DROP TEMPORARY TABLE IF EXISTS tmp.inventory;
		
        CREATE TEMPORARY TABLE tmp.inventory
		(
		  itemFk INT(11) NOT NULL PRIMARY KEY,
		  quantity int(11) DEFAULT '0',
		  buyingValue decimal(10,3) DEFAULT '0.000',
		  freightValue decimal(10,3) DEFAULT '0.000',
		  packing int(11) DEFAULT '0',
		  `grouping` smallint(5) unsigned NOT NULL DEFAULT '1',
		  groupingMode tinyint(4) NOT NULL DEFAULT 0 ,
		  comissionValue decimal(10,3) DEFAULT '0.000',
		  packageValue decimal(10,3) DEFAULT '0.000',
		  packageFk varchar(10) COLLATE utf8_unicode_ci DEFAULT '--',
		  price1 decimal(10,2) DEFAULT '0.00',
		  price2 decimal(10,2) DEFAULT '0.00',
		  price3 decimal(10,2) DEFAULT '0.00',
		  minPrice decimal(10,2) DEFAULT '0.00',
		  producer varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
			INDEX (itemFK))
		ENGINE = MEMORY ;

		-- Compras
        INSERT INTO tmp.inventory(itemFk,quantity)
			SELECT b.itemFk, sum(b.quantity)
				FROM vn.buy b
                JOIN vn.entry e ON e.id = b.entryFk
                JOIN vn.travel tr ON tr.id = e.travelFk
                WHERE tr.warehouseInFk = vWh
					AND tr.landed BETWEEN vDateLastInventory AND vDateYesterday
				GROUP BY b.itemFk;
   SELECT vDateLastInventory , vDateYesterday;             
		-- Traslados
        INSERT INTO tmp.inventory(itemFk,quantity)
			SELECT itemFk, quantityOut
            FROM (
					SELECT b.itemFk, -sum(b.quantity) quantityOut
						FROM vn.buy b
						JOIN vn.entry e ON e.id = b.entryFk
						JOIN vn.travel tr ON tr.id = e.travelFk
						WHERE tr.warehouseOutFk = vWh
							AND tr.shipped BETWEEN vDateLastInventory AND vDateYesterday
						GROUP BY b.itemFk
				 ) sub
			ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity,0) + sub.quantityOut;
            
		-- Ventas
        INSERT INTO tmp.inventory(itemFk,quantity)
			SELECT itemFk, saleOut
            FROM (
					SELECT s.itemFk, -sum(s.quantity) saleOut
						FROM vn.sale s
						JOIN vn.ticket t ON t.id = s.ticketFk
						WHERE t.warehouseFk = vWh
							AND t.shipped BETWEEN vDateLastInventory AND vDateYesterday
						GROUP BY s.itemFk
				 ) sub
			ON DUPLICATE KEY UPDATE quantity =  IFNULL(quantity,0) + sub.saleOut;

		-- Actualiza valores de la ultima compra
		
		UPDATE tmp.inventory inv
			JOIN cache.last_buy lb ON lb.item_id = inv.itemFk AND lb.warehouse_id = vWh
            JOIN vn.buy b ON b.id = lb.buy_id
			SET
				inv.buyingValue 	= b.buyingValue,
				inv.freightValue 	= b.freightValue,
				inv.packing 		= b.packing,
				inv.`grouping` 		= b.`grouping`,
				inv.groupingMode 	= b.groupingMode,
				inv.comissionValue = b.comissionValue,
				inv.packageValue 	= b.packageValue,
				inv.packageFk 		= b.packageFk,
				inv.price1 			= b.price1,
				inv.price2 			= b.price2,
				inv.price3 			= b.price3,
				inv.minPrice 		= b.minPrice,
				inv.producer 		= b.producer;

	
		INSERT INTO vn.buy(	itemFk,
							quantity,
							buyingValue,
							freightValue,
							packing,
							`grouping`,
							groupingMode,
							comissionValue,
							packageValue,
							packageFk,
							price1,
							price2,
							price3,
							minPrice,
							producer,
                            entryFk)
			SELECT 	itemFk,
					quantity,
					buyingValue,
					freightValue,
					packing,
					`grouping`,
					groupingMode,
					comissionValue,
					packageValue,
					packageFk,
					price1,
					price2,
					price3,
					minPrice,
					producer,
                    vEntryFk
				FROM tmp.inventory;

		SELECT vWh, count(*), NOW() FROM tmp.inventory;
        
	-- DROP TEMPORARY TABLE tmp.inventory;
        
	END LOOP;

	CLOSE cWarehouses;

	UPDATE vn2008.tblContadores SET FechaInventario = vDate;
    SET @isModeInventory := FALSE;

	DELETE e, t
		FROM vn.travel t
			JOIN vn.entry e ON e.travelFk = t.id 
		WHERE e.supplierFk = 4
			AND t.shipped <= vDeleteDate
			AND (DAY(t.shipped) <> 1 OR shipped < TIMESTAMPADD(MONTH, -12, 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 `inventoryMakeLauncher` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `inventoryMakeLauncher`()
BEGIN
/**
 * Recalcula los inventarios de todos los almacenes.
 */

	call vn.inventoryMake(TIMESTAMPADD(DAY, -10, CURDATE()), 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 `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),':',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 `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);
    DECLARE vSerial VARCHAR(2);
    
  
    CALL invoiceInBookingCommon(vInvoiceInId,vSerialNumber);
       
	SELECT serial 
		INTO vSerial 
        FROM newInvoiceIn;
    
    SELECT SUM(iit.taxableBase * IF(vSerial = 'R', 1 +(tc.rate/100),1)),
			SUM(iit.foreignValue * IF(vSerial = '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 EUROHABER,
			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 AND tc.link
				JOIN expence e ON e.id = it.expenceFk AND e.taxTypeFk = tc.taxTypeFk
			WHERE tc.isActive 
            AND (tc.type = 'S' OR MID(s.supplierAccount,4,1) = '1')
			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;
            
	UPDATE vn.config
		SET ASIEN = vBookNumber;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceInTaxMakeByDua` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `invoiceInTaxMakeByDua`(vDuaFk INT)
BEGIN

	DECLARE done BOOL DEFAULT FALSE;
	DECLARE vInvoiceInFk INT;

	DECLARE rs CURSOR FOR
			SELECT invoiceInFk
				FROM entry e
					JOIN duaEntry de ON de.entryFk = e.id
				WHERE de.duaFk = vDuaFk;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	OPEN rs;

	FETCH rs INTO vInvoiceInFk;

	WHILE NOT done DO

		CALL vn2008.recibidaIvaInsert(vInvoiceInFk);
        CALL vn2008.recibidaVencimientoReplace(vInvoiceInFk);
        
		FETCH rs INTO vInvoiceInFk;

	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 `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);
	CALL invoiceTaxMake(vInvoice,vCountry);
    
    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 `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 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';
    
	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;
	
	-- 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
					LEFT 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);
		
		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`;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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)
BEGIN

    DELETE FROM invoiceOutTax
			WHERE invoiceOutFk = vInvoice;
    
	DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
	CREATE TEMPORARY TABLE tmp.ticket
		(KEY (ticketFk))
		ENGINE = MEMORY
		SELECT id ticketFk
			FROM ticketToInvoice;
		
	CALL ticketGetTax();

    INSERT INTO invoiceOutTax(
		invoiceOutFk,
		pgcFk,
		taxableBase,
		vat
	)
	SELECT vInvoice,
			pgcFk,
			SUM(taxableBase) as BASE,
			CAST(SUM(taxableBase) * rate / 100 AS DECIMAL (10,2))
		FROM tmp.ticketTax
        GROUP BY pgcFk
        HAVING BASE;
	   
	DROP TEMPORARY TABLE tmp.ticket;
	DROP TEMPORARY TABLE tmp.ticketTax;
	DROP TEMPORARY TABLE tmp.ticketAmount;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemCard` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemCard`(IN `vBarcode` VARCHAR(22), IN `vWarehouseFk` INT, isBarcode BOOL)
BEGIN

	DECLARE vCacheVisibleFk INT;
    DECLARE vCacheAvailableFk INT;
    DECLARE vVisibleAltillo INT;
    DECLARE vItemFk INT;
    
    IF isBarcode THEN
		SELECT vn.barcodeToItem(vBarcode) INTO vItemFk;
	ELSE
		SELECT i.id INTO vItemFk 
        FROM vn.item i
        WHERE i.name LIKE CONCAT('%',vBarcode,'%')
        ORDER BY i.id ASC
        LIMIT 1;
    END IF;
    
    
    IF vItemFk IS NULL THEN
		SELECT vn.barcodeToItem(vBarcode) INTO vItemFk;
    END IF;



    CALL cache.visible_refresh(vCacheVisibleFk, FALSE,vWarehouseFk);
    CALL cache.available_refresh(vCacheAvailableFk, FALSE,vWarehouseFk, CURDATE());
    /*
    SELECT max(id) INTO vCacheVisibleFk 
		FROM cache.cache_calc 
		WHERE cacheName = 'visible' 
			AND params = vWarehouseFk;
	
    SELECT max(id) INTO vCacheAvailableFk 
		FROM cache.cache_calc 
		WHERE cacheName = 'available' 
			AND params = CONCAT(vWarehouseFk,'/',date(CURDATE()));
    */    
    /*
	SELECT sum(visible) INTO vVisibleAltillo
		FROM vn.itemShelving ish
			JOIN vn.shelving sh ON sh.`code` = ish.shelvingFk
            JOIN vn.parking p ON p.id = sh.parkingFk
            JOIN vn.sector s ON s.id = p.sectorFk
        WHERE ish.itemFk = vItemFk
			AND s.warehouseFk = vWarehouseFk;
	*/
    SELECT visible INTO vVisibleAltillo
		FROM vn.itemShelvingStock
        WHERE itemFk = vItemFk;
        
	CALL vn2008.item_last_buy_(vWarehouseFk,vItemFk);

	SELECT  i.id,
			i.longName,
			i.value5,
            i.value6,
            i.value7,
            i.image,
            i.size,
            i.stems,
            i.category,
			i.minimum as min,
			i.upToDown as repo,
            p.name as producer,
            o.code as origin,
            ip.code as nicho,
            ip.reserve as reserva,
            v.visible - IFNULL(vVisibleAltillo,0) as enNicho,
            a.available,
            vVisibleAltillo as enAltillo,
            v.visible as total,
            c.`grouping` as `grouping`,
            c.Packing as packing
        FROM vn.item i
			LEFT JOIN vn.producer p ON p.id = i.producerFk
            LEFT JOIN vn.origin o ON o.id = i.originFk
            LEFT JOIN vn.itemPlacement ip ON ip.itemFk = i.id 
            LEFT JOIN cache.visible v ON v.calc_id = vCacheVisibleFk AND v.item_id = i.id
			LEFT JOIN cache.available a ON a.calc_id = vCacheAvailableFk AND a.item_id = i.id
			LEFT JOIN
                                (SELECT  b.item_id,c.`grouping`,c.Packing
                                FROM vn2008.t_item_last_buy b
                                INNER JOIN  vn2008.Compres c ON c.Id_Compra = b.buy_id
                                where b.warehouse_id = vWarehouseFk) c
			ON  i.id= c.item_id
		WHERE i.id = vItemFk
			AND IFNULL(ip.warehouseFk, vWarehouseFk) = vWarehouseFk;
            
            DROP TEMPORARY TABLE t_item_last_buy;


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemDiary` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemDiary`(IN vItemId INT, IN vWarehouse INT)
BEGIN
    DECLARE vDateInventory DATETIME;
    DECLARE vCurdate DATE DEFAULT CURDATE();
    DECLARE vDayEnd DATETIME DEFAULT util.dayEnd(vCurdate);
    -- traduccion: date, alertLevel, origin, reference, name, In, Out, Balance
    SELECT  Fechainventario INTO vDateInventory FROM vn2008.tblContadores;
    SET @a = 0;
    SELECT DATE(date) AS date,
            alertLevel,
            stateName,
            origin,
            reference,
            clientFk,
            name,
			`in`,
            `out`,
            @a := @a + IFNULL(`in`,0) - IFNULL(`out`,0) as balance,
            isPicked,
            isTicket
        FROM
            ( SELECT  tr.landed as date,
                    b.quantity as `in`,
                    NULL as `out`,
                    IF(tr.isReceived != FALSE,3, IF(tr.isDelivered,1,0)) as alertLevel,
                    st.name AS stateName,
                    s.name as name,
                    e.ref as reference,
                    e.id as origin,
                    s.id as clientFk,
                    TRUE isPicked,
                    FALSE AS isTicket
                FROM vn.buy b
                    JOIN vn.entry e ON e.id = b.entryFk
                    JOIN vn.travel tr ON tr.id = e.travelFk
                    JOIN vn.supplier s ON s.id = e.supplierFk
                    JOIN vn.alertLevel al ON al.alertLevel = 
						CASE
							WHEN tr.isReceived != FALSE THEN 3
							WHEN tr.isDelivered THEN 1
                            ELSE 0
						END
                    JOIN vn.state st ON st.code = al.code
                WHERE tr.landed >= vDateInventory
                    AND vWarehouse = tr.warehouseInFk 
                    AND b.itemFk = vItemId
                    AND e.isInventory = 0

            UNION ALL

            SELECT tr.shipped as date,
                    NULL as `in`,
                    b.quantity as `out`,
                    IF(tr.isReceived != FALSE,3, IF(tr.isDelivered,1,0)) as alertLevel,
                    st.name AS stateName,
                    s.name as name,
                    e.ref as reference,
                    e.id as origin,
                    s.id as clientFk,
                    TRUE isPicked,
                    FALSE AS isTicket
                FROM vn.buy b
                    JOIN vn.entry e ON e.id = b.entryFk
                    JOIN vn.travel tr ON tr.id = e.travelFk
                    JOIN vn.warehouse w ON w.id = tr.warehouseOutFk
                    JOIN vn.supplier s ON s.id = e.supplierFk
                    JOIN vn.alertLevel al ON al.alertLevel = 
						CASE
							WHEN tr.isReceived != FALSE THEN 3
							WHEN tr.isDelivered THEN 1
                            ELSE 0
						END
                    JOIN vn.state st ON st.code = al.code
                WHERE tr.shipped >= vDateInventory
                    AND vWarehouse =tr.warehouseOutFk
                    AND s.id <> 4
                    AND b.itemFk = vItemId
                    AND e.isInventory = 0
                    AND w.isFeedStock = 0

            UNION ALL

            SELECT t.shipped as date,
                NULL as `in`,
                s.quantity as `out`,
                al.alertLevel as alertLevel,
                st.name AS stateName,
                t.nickname as name,
                t.refFk as reference,
                t.id as origin,
                t.clientFk,
                stk.id as isPicked, -- TRUE as isPicked 
                TRUE as isTicket
                FROM vn.sale s
                    JOIN vn.ticket t ON t.id = s.ticketFk
                    LEFT JOIN vn.ticketState ts ON ts.ticket = t.id
                    JOIN vn.client c ON c.id = t.clientFk
                    JOIN vn.alertLevel al ON al.alertLevel = 
						CASE
							WHEN t.shipped < vCurdate THEN 3
							WHEN t.shipped > vDayEnd THEN 0
                            ELSE IFNULL(ts.alertLevel, 0)
						END
                    JOIN vn.state st ON st.code = al.code
                    LEFT JOIN vn.saleTracking stk ON stk.saleFk = s.id AND stk.stateFk = 14 -- comentar
                WHERE t.shipped >= vDateInventory
                    AND s.itemFk = vItemId
                    AND vWarehouse =t.warehouseFk
            ) AS itemDiary
        ORDER BY date, isTicket, alertLevel DESC, isPicked DESC, `in` DESC, `out` 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 `itemFuentesBalance` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemFuentesBalance`(vDaysInFuture INT)
BEGIN

	CALL cache.stock_refresh(FALSE);

	SELECT 	alt.itemFk, 
			i.longName,
            i.size,
            i.subName,
			v.amount as visible, 
			alt.reserva, 
			sale.venta, 
			IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra, 
			IFNULL(v.amount,0) - reserva + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as saldo
		FROM cache.stock v
		JOIN (
				SELECT itemFk, CAST(SUM(visible) AS DECIMAL(10,0)) AS reserva
					FROM vn.itemShelving
					WHERE shelvingFk = 'FUE'
					GROUP BY itemFk	
			 ) alt ON alt.itemFk = v.item_id
		JOIN vn.item i ON i.id = alt.itemFk
		LEFT JOIN (
				SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as venta
					FROM vn2008.item_out
					WHERE dat BETWEEN CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(curdate()))
						AND warehouse_id  = 1
					GROUP BY item_id
			 ) sale ON sale.item_id = alt.itemFk
		LEFT JOIN (
				SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as compra
					FROM vn2008.item_entry_in
					WHERE dat BETWEEN CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(curdate()))
						AND warehouse_id  = 1
                        AND i.isVirtualStock is FALSE
					GROUP BY item_id
			 ) buy ON buy.item_id = alt.itemFk
		LEFT JOIN (
				SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as traslado
					FROM vn2008.item_entry_out
					WHERE dat BETWEEN CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(curdate()))
						AND warehouse_id  = 1
					GROUP BY item_id
			 ) mov ON mov.item_id = alt.itemFk
			 
		WHERE v.warehouse_id = 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 `itemGetVisibleAvailable` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemGetVisibleAvailable`(
	vItem INT,
    vDate DATE,
    vWarehouse TINYINT,
    vRefresh BOOL)
BEGIN
	DECLARE vVisibleCalc INT;
    DECLARE vAvailableCalc INT;
    
    -- FIXME: Android app is always passing %TRUE for #vRefresh, this leads to DB performance issues
	CALL cache.visible_refresh(vVisibleCalc, vRefresh, vWarehouse);
    CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/, vWarehouse, vDate);

	SELECT i.id, i.longName, i.box, i.typeFk, 
				i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8,
				ip.code,   ip.reserve,
				v.visible,
				av.available
  		FROM vn.item i 
			LEFT JOIN vn.itemPlacement ip
				ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse
			LEFT JOIN cache.visible v
				ON v.item_id = i.id AND v.calc_id = vVisibleCalc
			LEFT JOIN cache.available av
				ON av.item_id = i.id AND av.calc_id = vAvailableCalc
		WHERE (vItem IS NULL OR i.id = 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 */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemLastEntries` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemLastEntries`(IN `vItem` INT, IN `vDays` DATE)
BEGIN
	SELECT
		w.id AS warehouseFk,
        w.name AS warehouse,
		tr.landed,
		b.entryFk,
		b.isIgnored,
		b.price2, 
		b.price3,
		b.stickers,
		b.packing,
		b.`grouping`,
        b.groupingMode,
		i.stems,
		b.quantity,
		b.buyingValue,
		b.packageFk ,
		s.id AS supplierFk,
        s.name AS supplier
	FROM itemType it
	RIGHT JOIN (entry e 
			LEFT JOIN supplier s ON s.id = e.supplierFk
			RIGHT JOIN buy b ON b.entryFk = e.id
			LEFT JOIN item i ON i.id = b.itemFk
			LEFT JOIN ink ON ink.id = i.inkFk 
			LEFT JOIN travel tr ON tr.id = e.travelFk
			LEFT JOIN warehouse w ON w.id = tr.warehouseInFk
			LEFT JOIN origin o ON o.id = i.originFk
			) ON it.id = i.typeFk
	LEFT JOIN edi.ekt ek ON b.ektFk = ek.id
	WHERE b.itemFk = vItem And tr.shipped BETWEEN  vDays AND CURDATE() 
	ORDER BY tr.landed DESC , b.id DESC;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemPlacementFromTicket` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemPlacementFromTicket`(vTicket INT)
BEGIN
/**
 * Llama a itemPlacementUpdateVisible 
 * de los articulos de la tabla temporal tmp.itemPlacement(itemFk)
 * @treturn tmp.itemPlacement
 * @param vTicket Id del Ticket
 */

    DROP TEMPORARY TABLE IF EXISTS tmp.itemPlacement;
    CREATE TEMPORARY TABLE tmp.itemPlacement
        (PRIMARY KEY (itemFk))
		ENGINE = MEMORY
		SELECT s.itemFk
			FROM ticket t
				JOIN sale s ON s.ticketFk = t.id
			WHERE t.id = vTicket;
            
	CALL itemPlacementUpdateVisible();
    
	DROP TEMPORARY TABLE tmp.itemPlacement;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemPlacementReloadVisible` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemPlacementReloadVisible`()
BEGIN
/**
 * Reemplaza únicamente el campo itemPlacement.pickable
 * restando al cache.visible los valores de las tablas
 * itemShelving y los tickets con estado impreso 
 * que aun no han sido preparados.
 */
 
	DECLARE vCalc INT;
	DECLARE vTodayIni DATE DEFAULT CURDATE();
    DECLARE vTodayEnd DATETIME DEFAULT util.dayend(vTodayIni);
    DECLARE vproductionOrderPrinted INT DEFAULT 4;
    DECLARE vWarehouseSillaFv INT DEFAULT 1;
    
	UPDATE itemPlacement SET pickable = 0;
    
	CALL cache.visible_refresh(vCalc, FALSE, vWarehouseSillaFv);
-- SELECT * FROM cache.visible v;
    DROP TEMPORARY TABLE IF EXISTS tmp.itemShelving;
    CREATE TEMPORARY TABLE tmp.itemShelving
		SELECT itemFk, IFNULL(SUM(visible),0) visible
			FROM itemShelving its 
			GROUP BY its.itemFk;
-- SELECT * FROM tmp.itemShelving;
	DROP TEMPORARY TABLE IF EXISTS tmp.itemPlacement;
    CREATE TEMPORARY TABLE tmp.itemPlacement
		SELECT s.itemFk, cast(SUM(s.quantity) AS UNSIGNED) visible
			FROM ticket t 
				JOIN ticketState ts ON ts.ticketFk = t.id AND productionOrder = vproductionOrderPrinted
				JOIN sale s ON s.ticketFk = t.id
			WHERE t.shipped BETWEEN vTodayIni AND vTodayEnd
			GROUP BY s.itemFk;
-- SELECT * FROM tmp.itemPlacement;   

/*SELECT v.item_id, vWarehouseSillaFv, v.visible - IFNULL(tis.visible,0) - IFNULL(tip.visible,0)
			FROM cache.visible v
				LEFT JOIN tmp.itemShelving tis ON tis.itemFk = v.item_id
				LEFT JOIN tmp.itemPlacement tip ON tip.itemFk = v.item_id
			WHERE v.calc_id = vCalc;
            */
    INSERT INTO itemPlacement(itemFk, warehouseFk, pickable)
		SELECT v.item_id, vWarehouseSillaFv, v.visible - IFNULL(tis.visible,0) - IFNULL(tip.visible,0)
			FROM cache.visible v
				LEFT JOIN tmp.itemShelving tis ON tis.itemFk = v.item_id
				LEFT JOIN tmp.itemPlacement tip ON tip.itemFk = v.item_id
			WHERE v.calc_id = vCalc
	ON DUPLICATE KEY UPDATE pickable = VALUES(pickable);
    
	DROP TEMPORARY TABLE tmp.itemShelving;
	DROP TEMPORARY TABLE tmp.itemPlacement;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemPlacementSave` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemPlacementSave`(vCode VARCHAR(22), vPlacement VARCHAR(10), vWarehouseFk INT )
BEGIN

    DECLARE vItemFk INT;
    
    SET vItemFk = barcodeToItem(vCode);
    
    IF ASCII(vPlacement) > 57 THEN

		INSERT INTO itemPlacement(itemFk, warehouseFk, reserve,pickable)
			VALUES(vItemFk, vWarehouseFk, vPlacement,0)
		ON DUPLICATE KEY UPDATE reserve = vPlacement;
	ELSE
		INSERT INTO itemPlacement(itemFk, warehouseFk, code)
			VALUES(vItemFk, vWarehouseFk, vPlacement)
		ON DUPLICATE KEY UPDATE code = vPlacement;
	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 `itemPlacementSupplyAiming` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemPlacementSupplyAiming`(vShelvingFk VARCHAR(10), quantity INT, vItemFk INT)
BEGIN

	SELECT 	ish.itemFk,
			ish.longName,
            ish.size,
            ish.subName,
			ish.itemShelvingFk,
            ish.shelving,
            ish.stock,
            LEAST(ish.stock,quantity) as total,
            CONCAT(
					CAST(LEAST(ish.stock,quantity) / ish.packing AS DECIMAL(10,0)),
                    ' x ',
                    ish.packing,
                    IF	(	
						LEAST(ish.stock,quantity) MOD ish.packing,
						CONCAT(' + ',CAST(LEAST(ish.stock,quantity) MOD ish.packing AS DECIMAL(10,0))),
                        ''
                        ),
                    ' = ',
                    LEAST(ish.stock,quantity)
				   ) as proposal
		FROM vn.itemShelvingPlacementSupplyStock ish
        WHERE ish.shelving = vShelvingFk COLLATE utf8_general_ci
			AND ish.itemFk = vItemFk;

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

	UPDATE vn.itemPlacementSupply 
    SET priority = 10
    WHERE id = vId;

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

	DECLARE vId INT;
    
    SELECT id INTO vId
		FROM vn.itemPlacementSupplyList ipsl
		WHERE Saldo > 0
			AND (repoUserFk is NULL OR repoUserFk = getUser())
        ORDER BY priority DESC, parking DESC, created
        LIMIT 1;
	
    UPDATE vn.itemPlacementSupply
		SET repoUserFk = getUser()
        WHERE id = vId;
        
    SELECT * FROM vn.itemPlacementSupplyList 
		WHERE id = vId;

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

	SELECT shelving, parking, sum(stock) as stockTotal,created
        FROM
			(
			SELECT  *
				FROM vn.itemShelvingPlacementSupplyStock
				WHERE itemFk = vItemFk
				ORDER BY priority DESC, created
			) sub
		GROUP BY shelving;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemPlacementUpdateVisible` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemPlacementUpdateVisible`()
BEGIN
/**
 * Reemplaza únicamente el campo itemPlacement.pickable
 * de los articulos de la tabla temporal tmp.itemPlacement(itemFk)
 * restando al cache.visible los valores de las tablas
 * itemShelving y los tickets con estado impreso 
 * que aun no han sido preparados.
 */
	DECLARE vCalc INT;
	DECLARE vTodayIni DATE DEFAULT CURDATE();
    DECLARE vTodayEnd DATETIME DEFAULT util.dayend(vTodayIni);
    DECLARE vproductionOrderPrinted INT DEFAULT 4;
    DECLARE vWarehouseSillaFv INT DEFAULT 1;
    
	UPDATE itemPlacement SET pickable = 0;
    
	CALL cache.visible_refresh(vCalc, FALSE, vWarehouseSillaFv);
SELECT * FROM cache.visible v;
    DROP TEMPORARY TABLE IF EXISTS tmp.itemShelving;
    CREATE TEMPORARY TABLE tmp.itemShelving
		SELECT its.itemFk, IFNULL(SUM(visible),0) visible
			FROM itemShelving its
				JOIN tmp.itemPlacement tip ON tip.itemFk = its.itemFk
			GROUP BY its.itemFk;
SELECT * FROM tmp.itemShelving;

SELECT s.itemFk, cast(SUM(s.quantity) AS UNSIGNED) visible
			FROM ticket t
				JOIN ticketState ts ON ts.ticketFk = t.id AND productionOrder = vproductionOrderPrinted
				JOIN sale s ON s.ticketFk = t.id
                JOIN tmp.itemPlacement tip ON tip.itemFk = s.itemFk
			WHERE t.shipped BETWEEN vTodayIni AND vTodayEnd
			GROUP BY s.itemFk;
            
	DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
    CREATE TEMPORARY TABLE tmp.ticket
		SELECT s.itemFk, cast(SUM(s.quantity) AS UNSIGNED) visible
			FROM ticket t
				JOIN ticketState ts ON ts.ticketFk = t.id AND productionOrder = vproductionOrderPrinted
				JOIN sale s ON s.ticketFk = t.id
                JOIN tmp.itemPlacement tip ON tip.itemFk = s.itemFk
			WHERE t.shipped BETWEEN vTodayIni AND vTodayEnd
			GROUP BY s.itemFk;
SELECT * FROM tmp.ticket;   

SELECT v.item_id, vWarehouseSillaFv, v.visible - IFNULL(tis.visible,0) - IFNULL(tik.visible,0)
			FROM cache.visible v
				LEFT JOIN tmp.itemShelving tis ON tis.itemFk = v.item_id
				LEFT JOIN tmp.ticket tik ON tik.itemFk = v.item_id
			WHERE v.calc_id = vCalc;
            
    INSERT INTO itemPlacement(itemFk, warehouseFk, pickable)
		SELECT v.item_id, vWarehouseSillaFv, v.visible - IFNULL(tis.visible,0) - IFNULL(tik.visible,0)
			FROM cache.visible v
				LEFT JOIN tmp.itemShelving tis ON tis.itemFk = v.item_id
				LEFT JOIN tmp.ticket tik ON tik.itemFk = v.item_id
			WHERE v.calc_id = vCalc
	ON DUPLICATE KEY UPDATE pickable = VALUES(pickable);
    
	DROP TEMPORARY TABLE tmp.itemShelving;
	DROP TEMPORARY TABLE tmp.ticket;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemRefreshTags` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemRefreshTags`(IN vItem INT)
BEGIN
/**
 * Actualiza la tabla item, los campos "cache" de tags
 *
 * @param vItem El id del articulo. Si es NULL, equivale a todos.
 **/
 	DECLARE vInkId VARCHAR(3) DEFAULT NULL;
	DECLARE vSize INT DEFAULT NULL;
    DECLARE vOriginId INT DEFAULT NULL;
	DECLARE vProducerId INT DEFAULT NULL;
    DECLARE vStems INT DEFAULT NULL;
   
	UPDATE item i
			LEFT JOIN itemTag it1 ON it1.priority = 1 AND it1.itemFk = i.id
			LEFT JOIN itemTag it2 ON it2.priority = 2 AND it2.itemFk = i.id
			LEFT JOIN itemTag it3 ON it3.priority = 3 AND it3.itemFk = i.id
		SET i.longName = CONCAT_WS(' ', it1.`value`, it2.`value`, it3.`value`)
            WHERE (vItem IS NULL OR vItem = i.id);

	UPDATE item i
			LEFT JOIN itemTag it1 ON it1.priority = 1 AND it1.itemFk = i.id
			LEFT JOIN tagAbbreviation ta1 ON ta1.`value` = it1.`value`
			LEFT JOIN itemTag it2 ON it2.priority = 2 AND it2.itemFk = i.id
            LEFT JOIN tagAbbreviation ta2 ON ta2.`value` = it2.`value`
			LEFT JOIN itemTag it3 ON it3.priority = 3 AND it3.itemFk = i.id
            LEFT JOIN tagAbbreviation ta3 ON ta3.`value` = it3.`value`
		SET i.`name` = CONCAT_WS(' ', 
						IFNULL(ta1.abbreviation,it1.`value`), 
                        IFNULL(ta2.abbreviation,it2.`value`), 
                        IFNULL(ta3.abbreviation,it3.`value`))
            WHERE (vItem IS NULL OR vItem = i.id);
          
	UPDATE item i
			LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 4
		SET i.subName = it.`value`
        WHERE (vItem IS NULL OR vItem = i.id);

	UPDATE item i
			LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 5
			LEFT JOIN tag t ON t.id = it.tagFk
		SET tag5 = t.name, value5 = it.`value`
		WHERE (vItem IS NULL OR vItem = i.id);
 
	UPDATE item i
			LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 6
			LEFT JOIN tag t ON t.id = it.tagFk
		SET tag6 = t.name, value6 = it.`value`
		WHERE (vItem IS NULL OR vItem = i.id);
           
	UPDATE item i
			LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 7
			LEFT JOIN tag t ON t.id = it.tagFk 
		SET i.tag7 = t.name, i.value7 = it.`value`
		WHERE (vItem IS NULL OR vItem = i.id);
                        
	UPDATE item i
			LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 8
			LEFT JOIN tag t ON t.id = it.tagFk
		SET tag8 = t.name, value8 = it.`value`
		WHERE (vItem IS NULL OR vItem = i.id);
                        
	UPDATE item i
			LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 9
			LEFT JOIN tag t ON t.id = it.tagFk
		SET tag9 = t.name, value9 = it.`value`
		WHERE (vItem IS NULL OR vItem = i.id);
            
	UPDATE item i
			LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 10
			LEFT JOIN tag t ON t.id = it.tagFk
		SET tag10 = t.name, value10 = it.`value`
		WHERE (vItem IS NULL OR vItem = i.id);
   
	IF vItem IS NOT NULL THEN
		-- Al insertar el tag color se modifica también el antiguo campo color
		SELECT i.id INTO vInkId FROM ink i
				JOIN itemTag it ON it.tagFk = 1 AND i.`name` = it.`value`
			WHERE vItem = it.itemFk
            LIMIT 1;
			
		IF vInkId > '' THEN 
			UPDATE item SET inkFk = vInkId WHERE id = vItem;
		END IF;   
		
		-- Al insertar el tag origen se modifica también en la tabla item
		SELECT o.id INTO vOriginId FROM origin o
				JOIN itemTag it ON it.tagFk = 35 AND o.`name` = it.`value`
            WHERE vItem = it.itemFk
            LIMIT 1;
        
		IF vOriginId > '' THEN 
			UPDATE item SET originFk = vOriginId WHERE id = vItem;
		END IF;
        
        -- Al insertar el tag medida se modifica también en la tabla item
		SELECT it.`value` INTO vSize 
			FROM itemTag it
            WHERE vItem = it.itemFk AND it.tagFk IN (4, 8)
            LIMIT 1;
        
		IF vSize > '' THEN 
			UPDATE item SET size = vSize WHERE id = vItem;
		END IF;
	
        -- Al insertar el tag productor se modifica también en la tabla item
		SELECT p.id INTO vProducerId FROM producer p
			JOIN itemTag it ON it.tagFk = 37 AND p.`name` = it.`value`
            WHERE vItem = it.itemFk
            LIMIT 1;
        
		IF vProducerId > '' THEN 
			UPDATE item SET producerFk = vProducerId WHERE id = vItem;
		END IF;
        
         -- Al insertar el tag tallos se modifica también en la tabla item
		SELECT CAST(it.`value` as signed) INTO vStems 
			FROM itemTag it
            WHERE vItem = it.itemFk AND it.tagFk = 23
            LIMIT 1;
        
		IF vStems > 0 THEN 
			UPDATE item SET stems = vStems WHERE id = vItem;
		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 `itemSaveMin` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemSaveMin`(min INT,vBarcode VARCHAR(22))
BEGIN

	DECLARE vItemFk INT;
    SELECT vn.barcodeToItem(vBarcode) INTO vItemFk;
    
    UPDATE vn.item SET minimum = min WHERE   id = vItemFk;
	


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemSearchShelving` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemSearchShelving`(IN `vShelvingFk` VARCHAR(3))
BEGIN

	SELECT p.column as col , p.`row` 
    FROM vn.shelving s 
    INNER JOIN parking p 
    ON s.parkingFk = p.id 
    WHERE s.code = vShelvingFk;
	

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemSetNicho` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemSetNicho`(IN `vPlacement` VARCHAR(30), IN `vReserve` VARCHAR(30), IN `vBarcode` INT, IN `vWarehouse` INT)
BEGIN
	DECLARE vItemFk INT DEFAULT barcodeToItem(vBarcode);

INSERT INTO itemPlacement
            SET itemFk = vItemFk,
                warehouseFk = vWarehouse,
                reserve = vReserve ,
                code = vPlacement
            ON DUPLICATE KEY UPDATE
                reserve = IFNULL(vReserve,reserve),
                code = IFNULL(vPlacement,code);


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemSetOnlyNicho` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemSetOnlyNicho`(IN `vPlacement` VARCHAR(30), IN `vBarcode` INT, IN `vWarehouse` INT)
BEGIN
	DECLARE vItemFk INT DEFAULT barcodeToItem(vBarcode);

INSERT INTO itemPlacement
            SET itemFk = vItemFk,
                warehouseFk = vWarehouse,
                code = vPlacement
            ON DUPLICATE KEY UPDATE
                code = IFNULL(vPlacement,code);


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemSetReserva` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemSetReserva`(IN `vReserve` VARCHAR(30),IN `vBarcode` INT, IN `vWarehouse` INT)
BEGIN
	DECLARE vItemFk INT DEFAULT barcodeToItem(vBarcode);

INSERT INTO itemPlacement
            SET itemFk = vItemFk,
                warehouseFk = vWarehouse,
                reserve = vReserve
            ON DUPLICATE KEY UPDATE
                reserve = IFNULL(vReserve,reserve);

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

	DELETE FROM vn.itemShelving WHERE id = vId;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingEdit` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingEdit`(vVisible INT,vPacking INT,vId INT)
BEGIN

	UPDATE vn.itemShelving SET available = vVisible, visible = vVisible, packing = vPacking WHERE id = vId;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingList` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingList`(IN `vShelvingFk` VARCHAR(8))
BEGIN

	/*MODIFICADA POR QUIQUE: OBTENEMOS DEEP Y PARKING*/
	SELECT ish.itemFk as item, 
		   IFNULL(i.longName, CONCAT(i.name, ' ',i.size)) as description, 
           ish.visible as visible,
           ceil(ish.visible/ish.packing) as stickers,
           ish.packing as packing,
           p.`column` as col,
           p.`row` as `row`,
           ish.id,
           s.priority
		FROM vn.itemShelving ish
			JOIN vn.item i ON i.id = ish.itemFk
			INNER JOIN vn.shelving s ON vShelvingFk = s.code COLLATE utf8_unicode_ci
            LEFT JOIN vn.parking p ON s.parkingFk = p.id
		WHERE ish.shelvingFk COLLATE utf8_unicode_ci =vShelvingFk COLLATE utf8_unicode_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 `itemShelvingMake` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingMake`(IN `vShelvingFk` VARCHAR(8), IN `vBarcode` VARCHAR(22), IN `vShelve` VARCHAR(2), IN `vDeep` INT, IN `vQuantity` INT, IN `vPackagingFk` VARCHAR(10), IN `vGrouping` INT, IN `vPacking` INT, IN `vWarehouseFk` INT, IN `vLevel` INT)
BEGIN
	
    
    
    DECLARE vItemFk INT;
    
    
    
    SELECT vn.barcodeToItem(vBarcode) INTO vItemFk;
    

	SELECT itemFk INTO vItemFk
		FROM vn.buy b
        WHERE b.id = vItemFk;
        
        
	IF (SELECT COUNT(*) FROM vn.shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN
    
		INSERT IGNORE INTO vn.parking(`code`) VALUES(vShelvingFk);
        INSERT INTO vn.shelving(`code`, parkingFk) 
			SELECT vShelvingFk, id
				FROM vn.parking 
                WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci;
    
    END IF;
    
	
	INSERT INTO itemShelving( itemFk,
							  shelvingFk, 
                              shelve, 
                              deep, 
                              quantity, 
                              visible, 
                              available,
                              `grouping`,
                              packing, 
                              packagingFk,
                              level)
		SELECT
				vItemFk,
                vShelvingFk,
                vShelve,
                vDeep,
                vQuantity,
                vQuantity,
                vQuantity,
                IF(vGrouping = 0, IFNULL(b.packing, vPacking), vGrouping) as `grouping`,
                IF(vPacking = 0, b.packing, vPacking) as packing,
                IF(vPackagingFk = '', b.packageFk, vPackagingFk) as packaging,
                vLevel
			FROM vn.item i
				LEFT JOIN bi.Last_buy_id lb ON i.id = lb.Id_Article AND lb.warehouse_id = vWarehouseFk
				LEFT JOIN vn.buy b ON b.id = lb.Id_Compra
			WHERE i.id = vItemFk;
                
			
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingMakeFromDate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingMakeFromDate`(IN `vShelvingFk` VARCHAR(8), IN `vBarcode` VARCHAR(22), IN `vShelve` VARCHAR(2), IN `vDeep` INT, IN `vQuantity` INT, IN `vPackagingFk` VARCHAR(10), IN `vGrouping` INT, IN `vPacking` INT, IN `vWarehouseFk` INT, IN `vLevel` INT,`vCreated` VARCHAR(22))
BEGIN
	
    
    
    DECLARE vItemFk INT;
    
    
    
    SELECT vn.barcodeToItem(vBarcode) INTO vItemFk;
    

	SELECT itemFk INTO vItemFk
		FROM vn.buy b
        WHERE b.id = vItemFk;
        
        
	IF (SELECT COUNT(*) FROM vn.shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN
    
		INSERT IGNORE INTO vn.parking(`code`) VALUES(vShelvingFk);
        INSERT INTO vn.shelving(`code`, parkingFk) 
			SELECT vShelvingFk, id
				FROM vn.parking 
                WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci;
    
    END IF;
    
	
	INSERT INTO itemShelving( itemFk,
							  shelvingFk, 
                              shelve, 
                              deep, 
                              quantity, 
                              visible, 
                              available,
                              created,
                              `grouping`,
                              packing, 
                              packagingFk,
                              level)
		SELECT
				vItemFk,
                vShelvingFk,
                vShelve,
                vDeep,
                vQuantity,
                vQuantity,
                vQuantity,
                vCreated,
                IF(vGrouping = 0, IFNULL(b.packing, vPacking), vGrouping) as `grouping`,
                IF(vPacking = 0, b.packing, vPacking) as packing,
                IF(vPackagingFk = '', b.packageFk, vPackagingFk) as packaging,
                vLevel
			FROM vn.item i
				LEFT JOIN bi.Last_buy_id lb ON i.id = lb.Id_Article AND lb.warehouse_id = vWarehouseFk
				LEFT JOIN vn.buy b ON b.id = lb.Id_Compra
			WHERE i.id = vItemFk;
                
			
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingMatch` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingMatch`(vEntryFk INT)
BEGIN

	SELECT i.id, i.longName, i.size, i.subName, b.stickers, ish.etiquetas
		FROM item i
		LEFT JOIN (
					SELECT itemFk, sum(stickers) AS stickers
						FROM buy
						WHERE entryFk = vEntryFk
						GROUP BY itemFk
				  ) b ON b.itemFk = i.id
		LEFT JOIN (
					SELECT itemFk, sum(cast(quantity / packing AS DECIMAL(10,0))) AS etiquetas 
						FROM itemShelving ish
							JOIN shelving sh ON sh.code = ish.shelvingFk
                            LEFT JOIN parking pk ON pk.id = sh.parkingFk
						WHERE created > CURDATE()
							AND IFNULL(pk.`column`,0) < 700
						GROUP BY itemFk
				  ) ish ON ish.itemFk = id
		WHERE b.stickers OR ish.etiquetas;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingPlacementSupplyAdd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingPlacementSupplyAdd`(vItemShelvingFk INT, vItemPlacementSupplyFk INT, vQuantity INT)
BEGIN

	INSERT INTO vn.itemShelvingPlacementSupply(	itemShelvingFk, 
												itemPlacementSupplyFk, 
                                                quantity, 
                                                userFk)
		VALUES (	vItemShelvingFk,
					vItemPlacementSupplyFk,
                    vQuantity,
                    getUser());
                    
		UPDATE vn.itemShelving  
		SET  quantity = quantity - vQuantity,
        visible = visible - vQuantity,
        available = available - vQuantity
		WHERE id = vItemShelvingFk;
                    

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

	DECLARE vVisibleCache INT;

	CALL cache.visible_refresh (vVisibleCache, FALSE, 1);
		
	SELECT 	t.id as ticketFk, 
		CAST(s.quantity AS DECIMAL(10,0)) as Cantidad, 
        s.itemFk, 
        s.concept, 
        v.visible - GREATEST(0,iss.visible - IFNULL(sub3.transit,0)) as Nicho, 
        i.subName,
        GREATEST(0,iss.visible - IFNULL(sub3.transit,0)) as Altillo, 
        s.id as saleFk
		FROM vn.ticket t 
			JOIN vn.ticketState tst ON tst.ticketFk = t.id
			JOIN vn.sale s ON s.ticketFk = t.id
			JOIN vn.item i ON i.id = s.itemFk
			JOIN cache.visible v ON s.itemFk = v.item_id AND v.calc_id = vVisibleCache
			LEFT JOIN vn2008.Movimientos_mark mm ON mm.Id_Movimiento = s.id AND mm.stateFk = 26
			JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id    
            LEFT JOIN
			(SELECT itemFk, sum(saldo) as transit 
				FROM vn.itemPlacementSupplyList 
                WHERE saldo > 0 
                GROUP BY itemFk) sub3 ON sub3.itemFk = i.id
		WHERE v.visible - GREATEST(0,iss.visible)  < s.quantity
			AND s.isPicked = FALSE 
			AND s.reserved = FALSE
			AND t.shipped BETWEEN CURDATE() AND util.dayend(CURDATE()) 
			AND tst.productionOrder < 6
			AND t.warehouseFk = vWarehouseFk
			AND mm.Id_Movimiento 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 `itemShelvingRadar` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingRadar`()
BEGIN

	DECLARE vWarehouseFk INT DEFAULT 1;
    DECLARE vCalcTicketShippingFk INT;
    DECLARE vCalcVisibleFk INT;
    DECLARE vCalcAvailableFk INT;
    
    CALL cache.ticketShippingRefresh(vCalcTicketShippingFk, FALSE, 1);
	CALL cache.visible_refresh(vCalcVisibleFk, TRUE, 1);
    CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, CURDATE());
    
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketState;
    CREATE TEMPORARY TABLE tmp.ticketState
    SELECT * FROM vn.ticketState
		WHERE updated >= TIMESTAMPADD(WEEK, -1, CURDATE())
        AND productionOrder < 6;
    
	DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar;
	CREATE TEMPORARY TABLE  tmp.itemShelvingRadar
	SELECT  *,
				@saldo:= CAST(IF(itemFk != @item, visibleTotal - Altillo, @saldo) - quantity AS DECIMAL(10,0)) as saldo,
				@item:= itemFk as item
			FROM
			(
				
				SELECT * FROM
				(
				SELECT 	IF(tst.updated AND st.`order` BETWEEN 4 AND 5 , HOUR(tst.updated), tsh.shippingHour) as Hora, 
						IF(tst.updated AND st.`order` BETWEEN 4 AND 5, MINUTE(tst.updated), tsh.shippingMinute) as Minuto, 
						s.itemFk, 
						i.longName as concept, 
						s.quantity, 
						GREATEST(0,iss.visible) as Altillo, 
						v.visible as visibleTotal,
						i.minimum * IFNULL(iss.packing,999) as minimum,
						i.size,
						ip.code as nicho,
						i.upToDown,
                        i.subName
					FROM tmp.ticketState tst 
						LEFT JOIN vn.state st ON st.id = tst.stateFk 
						JOIN vn.sale s ON s.ticketFk = tst.ticketFk
						JOIN vn.item i ON i.id = s.itemFk
						LEFT JOIN vn.itemPlacement ip ON ip.itemFk = i.id AND ip.warehouseFk = vWarehouseFk
						JOIN cache.visible v ON v.calc_id = vCalcVisibleFk AND v.item_id = s.itemFk
                        JOIN cache.ticketShipping tsh ON tsh.calc_id = vCalcTicketShippingFk AND tsh.ticketFk = tst.ticketFk
						JOIN vn.itemShelvingStock iss ON iss.itemFk = s.itemFk
						WHERE tst.productionOrder < 5
				
					UNION ALL
                    
                    SELECT 	25 as Hora, 
						0 as Minuto, 
						iss.itemFk, 
						i.longName as concept, 
						0 as quantity, 
						iss.visible as Altillo, 
						GREATEST(0,v.visible) as visibleTotal,
						i.minimum * IFNULL(iss.packing,999) as minimum,
						i.size,
						ip.code as nicho,
						i.upToDown,
                        i.subName
					FROM vn.itemShelvingStock iss
						JOIN vn.item i ON i.id = iss.itemFk
						LEFT JOIN vn.itemPlacement ip ON ip.itemFk = i.id AND ip.warehouseFk = vWarehouseFk
						JOIN cache.visible v ON v.calc_id = vCalcVisibleFk AND v.item_id = iss.itemFk
						
				) sub
				ORDER BY 	itemFk  , 
							Hora, 
							Minuto
				
			) sub2;
			
		   
	  
	DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadarMin;
	CREATE TEMPORARY TABLE tmp.itemShelvingRadarMin
	SELECT *, min(saldo) as minSaldo  , min(saldo) as minSaldo2
			FROM tmp.itemShelvingRadar 
			GROUP BY itemFk;
	  
			
			
	SELECT 	Hora, 
			Minuto, 
			i.id as itemFk, 
			concept, 
			quantity, 
			Altillo - IFNULL(sub3.saldo,0) as Altillo, 
			visibleTotal, 
			sub2.minimum, 
			i.size, 
			nicho,
			sub2.saldo,
			saldoFinal,
            i.upToDown,
			IF(saldoFinal = 1, minSaldo, sub2.saldo) as primerNegativo, 
            visibleTotal - Altillo as visibleEnNicho, 
			min(maxSaldo) as FinalDia ,
            i.subName as producer,
            ca.available,
            sub3.saldo as transit
		FROM item i
        LEFT JOIN
			(
				SELECT * FROM
				(
					SELECT *, 0 as minSaldo, 1000000 as maxSaldo, FALSE as saldoFinal
					FROM tmp.itemShelvingRadar
					WHERE saldo <= 0
					
					UNION ALL
					
					SELECT *, TRUE as saldoFinal
					FROM tmp.itemShelvingRadarMin
					GROUP BY itemFk
				) sub 
				ORDER BY itemFk, saldoFinal, Hora, Minuto
			) sub2 ON sub2.itemFk = i.id
            LEFT JOIN cache.available ca ON i.id = ca.item_id AND ca.calc_id = vCalcAvailableFk
		LEFT JOIN
			(SELECT itemFk, sum(saldo) as saldo 
				FROM vn.itemPlacementSupplyList 
                WHERE saldo > 0 
                GROUP BY itemFk) sub3 ON sub3.itemFk = i.id
			GROUP BY i.id
			HAVING saldo <= 0 OR saldoFinal ;
		  
 
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingRadar_beta` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingRadar_beta`()
BEGIN

	DECLARE vWarehouseFk INT DEFAULT 1;
    DECLARE vCalcTicketShippingFk INT;
    DECLARE vCalcVisibleFk INT;
    DECLARE vCalcAvailableFk INT;
    
    CALL cache.ticketShippingRefresh(vCalcTicketShippingFk, FALSE, 1);
	CALL cache.visible_refresh(vCalcVisibleFk, TRUE, 1);
    CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, CURDATE());
    
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketState;
    CREATE TEMPORARY TABLE tmp.ticketState
    SELECT * FROM vn.ticketState
		WHERE updated >= TIMESTAMPADD(WEEK, -1, CURDATE())
        AND productionOrder < 6;
    
	DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar;
	CREATE TEMPORARY TABLE  tmp.itemShelvingRadar
	SELECT  *,
				@saldo:= CAST(IF(itemFk != @item, visibleTotal - Altillo, @saldo) - quantity AS DECIMAL(10,0)) as saldo,
				@item:= itemFk as item
			FROM
			(
				
				SELECT * FROM
				(
				SELECT 	IF(tst.updated AND st.`order` BETWEEN 4 AND 5 , HOUR(tst.updated), tsh.shippingHour) as Hora, 
						IF(tst.updated AND st.`order` BETWEEN 4 AND 5, MINUTE(tst.updated), tsh.shippingMinute) as Minuto, 
						s.itemFk, 
						i.longName as concept, 
						s.quantity, 
						iss.visible as Altillo, 
						v.visible as visibleTotal,
						i.minimum * IFNULL(iss.packing,999) as minimum,
						i.size,
						ip.code as nicho,
						i.upToDown,
                        i.subName
					FROM tmp.ticketState tst 
						LEFT JOIN vn.state st ON st.id = tst.stateFk 
						JOIN vn.sale s ON s.ticketFk = tst.ticketFk
						JOIN vn.item i ON i.id = s.itemFk
						LEFT JOIN vn.itemPlacement ip ON ip.itemFk = i.id AND ip.warehouseFk = vWarehouseFk
						JOIN cache.visible v ON v.calc_id = vCalcVisibleFk AND v.item_id = s.itemFk
                        JOIN cache.ticketShipping tsh ON tsh.calc_id = vCalcTicketShippingFk AND tsh.ticketFk = tst.ticketFk
						JOIN vn.itemShelvingStock_beta iss ON iss.itemFk = s.itemFk
						WHERE tst.productionOrder < 5
				
					UNION ALL
                    
                    SELECT 	25 as Hora, 
						0 as Minuto, 
						iss.itemFk, 
						i.longName as concept, 
						0 as quantity, 
						iss.visible as Altillo, 
						v.visible as visibleTotal,
						i.minimum * IFNULL(iss.packing,999) as minimum,
						i.size,
						ip.code as nicho,
						i.upToDown,
                        i.subName
					FROM vn.itemShelvingStock_beta iss
						JOIN vn.item i ON i.id = iss.itemFk
						LEFT JOIN vn.itemPlacement ip ON ip.itemFk = i.id AND ip.warehouseFk = vWarehouseFk
						JOIN cache.visible v ON v.calc_id = vCalcVisibleFk AND v.item_id = iss.itemFk
						
				) sub
				ORDER BY 	itemFk  , 
							Hora, 
							Minuto
				
			) sub2;
			
		   
	  
	DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadarMin;
	CREATE TEMPORARY TABLE tmp.itemShelvingRadarMin
	SELECT *, min(saldo) as minSaldo  , min(saldo) as minSaldo2
			FROM tmp.itemShelvingRadar 
			GROUP BY itemFk;
	  
			
			
	SELECT 	Hora, 
			Minuto, 
			itemFk, 
			concept, 
			quantity, 
			Altillo, 
			visibleTotal, 
			sub2.minimum, 
			i.size, 
			nicho,
			saldo,
			saldoFinal,
            i.upToDown,
			IF(saldoFinal = 1, minSaldo, saldo) as primerNegativo, 
            visibleTotal - Altillo as visibleEnNicho, 
			min(maxSaldo) as FinalDia ,
            i.subName as producer,
            ca.available
		FROM item i
        LEFT JOIN
			(
				SELECT * FROM
				(
					SELECT *, 0 as minSaldo, 1000000 as maxSaldo, FALSE as saldoFinal
					FROM tmp.itemShelvingRadar
					WHERE saldo <= 0
					
					UNION ALL
					
					SELECT *, TRUE as saldoFinal
					FROM tmp.itemShelvingRadarMin
					GROUP BY itemFk
				) sub 
				ORDER BY itemFk, saldoFinal, Hora, Minuto
			) sub2 ON sub2.itemFk = id
            LEFT JOIN cache.available ca ON i.id = ca.item_id AND ca.calc_id = vCalcAvailableFk
			GROUP BY itemFk
			HAVING saldo <= 0 OR saldoFinal ;
		  
 
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingRadar_Entry` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingRadar_Entry`(vEntryFk INT)
BEGIN

	DECLARE vWarehouseFk INT DEFAULT 1;
    DECLARE vCalcVisibleFk INT;
    DECLARE vCalcAvailableFk INT;
    DECLARE vTodayDayEnd DATETIME DEFAULT util.dayEnd(CURDATE());
    
	CALL cache.visible_refresh(vCalcVisibleFk, FALSE, 1);
    CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, CURDATE());
    
    DROP TEMPORARY TABLE IF EXISTS tmp.item;
    CREATE TEMPORARY TABLE tmp.item
    ENGINE = MEMORY
    SELECT DISTINCT itemFk
		FROM vn.buy 
        WHERE entryFk = vEntryFk;
        
	DROP TEMPORARY TABLE IF EXISTS tmp.item2;
    CREATE TEMPORARY TABLE tmp.item2
    ENGINE = MEMORY
    SELECT *
		FROM tmp.item;
    
    SELECT 	i.id as itemFk, 
			i.minimum,
            CAST(IFNULL(v.visible,0) - IFNULL(iss.visible,0) AS DECIMAL(10,0)) as enNicho,
			CAST(IFNULL(a.available,0) AS DECIMAL(10,0))  as disponible,
            CAST(IFNULL(v.visible,0) - IFNULL(iss.visible,0) - ts.todaySold AS DECIMAL(10,0))  as finalDia
    FROM vn.item i
		JOIN tmp.item ti ON ti.itemFk = i.id
        LEFT JOIN cache.visible v ON v.calc_id = vCalcVisibleFk AND v.item_id = i.id
        LEFT JOIN cache.available a ON i.id = a.item_id AND a.calc_id = vCalcAvailableFk
        LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = i.id
        LEFT JOIN (	SELECT s.itemFk, sum(s.quantity) as todaySold
						FROM vn.sale s
							JOIN tmp.item2 ti ON ti.itemFk = s.itemFk
                            JOIN vn.ticket t ON t.id = s.ticketFk
                            LEFT JOIN vn.ticketState tst  ON tst.ticketFk = t.id
						WHERE t.shipped BETWEEN CURDATE() AND vTodayDayEnd
							AND t.warehouseFk = vWarehouseFk
                            AND IFNULL(tst.productionOrder,0) < 5
						GROUP BY s.itemFK
				) ts ON ts.itemFk = i.id;
    
  
	DROP TEMPORARY TABLE tmp.item;
    DROP TEMPORARY TABLE tmp.item2;
 
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSaleAdd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingSaleAdd`(vItemShelvingFk INT, saleFk INT, vQuantity INT)
BEGIN

	INSERT INTO vn.itemShelvingSale(	itemShelvingFk, 
												saleFk, 
                                                quantity, 
                                                userFk)
		VALUES (	vItemShelvingFk,
					saleFk,
                    vQuantity,
                    getUser());

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSaleSupplyAdd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingSaleSupplyAdd`(vItemShelvingFk INT, saleFk INT, vQuantity INT,idMovimiento INT)
BEGIN

	INSERT INTO vn.itemShelvingSale(	itemShelvingFk, 
												saleFk, 
                                                quantity, 
                                                userFk)
		VALUES (	vItemShelvingFk,
					saleFk,
                    vQuantity,
                    getUser());
                    
       UPDATE vn.itemShelving  
		SET  quantity = quantity - vQuantity,
        visible = visible - vQuantity,
        available = available - vQuantity
		WHERE id = vItemShelvingFk;
        
        UPDATE vn2008.Movimientos_mark     
		SET  valor = 1
		WHERE Id_Movimiento = idMovimiento;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingTicketSource` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingTicketSource`(vTicketFk INT)
BEGIN
	DECLARE vCalcFk INT;
    DECLARE vWarehouseFk INT;
    
    SELECT warehouseFk INTO vWarehouseFk
		FROM vn.ticket
        WHERE id = vTicketFk;
    SET vCalcFk = cache.ticketShippingCalcIdGet(vWarehouseFk);

	SELECT  
			s.id, 
			ubication, 
			s.quantity, 
			sis.quantity as Reserved, 
			s.itemFk,  
			s.concept, 
			s.ticketFk, 
			s.isPicked,
			ish.packing,
			FLOOR(sis.quantity / ish.packing) as stickers,
			sis.quantity MOD ish.packing as rest,
            ts.shippingHour, 
            ts.shippingMinute 
		FROM vn.saleItemShelving sis  
			JOIN vn.itemShelving ish ON ish.id = sis.itemShelvingFk  
			JOIN vn.sale s ON s.id = sis.saleFk  
            JOIN cache.ticketShipping ts ON ts.calc_id = vCalcFk AND ts.ticketFk = vTicketFk
		WHERE s.ticketFk = vTicketFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingTransfer` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingTransfer`(vItemFk INT,shelvingFkO VARCHAR(22),shelvingFkD VARCHAR(22),vQuantity INT)
BEGIN

	DECLARE vPacking INT;
    DECLARE vDate VARCHAR(22);

	SELECT packing  INTO vPacking
    FROM vn.itemShelving
    WHERE shelvingFk = shelvingFkO COLLATE utf8_unicode_ci AND itemFk = vItemFk
    LIMIT 1;
    
    SELECT created  INTO vDate
    FROM vn.itemShelving
    WHERE shelvingFk = shelvingFkO COLLATE utf8_unicode_ci AND itemFk = vItemFk
    LIMIT 1;

    UPDATE vn.itemShelving
    SET quantity = quantity - ( vPacking * vQuantity ),
			visible = visible - ( vPacking * vQuantity ),
			available = available - ( vPacking * vQuantity )
	 WHERE shelvingFk = shelvingFkO COLLATE utf8_unicode_ci AND itemFk = vItemFk;
     
	CALL vn.itemShelvingMakeFromDate(shelvingFkD,vItemFk,'A',0,( vPacking * vQuantity ),'',0,vPacking,1,1,vDate); 

	SELECT 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 `itemStockUpdate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemStockUpdate`(
	vItemFk INT, 
	vWarehouseFk INT, 
	vNewVisible INT, 
	vIsTrash BOOLEAN)
BEGIN

	DECLARE vTicketFk INT;
    DECLARE vClientFk INT;
    DECLARE vCompanyVnlFk INT DEFAULT 442; 
    DECLARE vVisible INT DEFAULT 0;
    DECLARE vCalc INT;
    DECLARE vCurrentTime VARCHAR(5);
    
    /*MODIFICADO POR KIKE*/
    /*PRIMERO LLAMAMOS A VISIBLE REFRESH Y OBTENEMOS EL VCALC PARA OBTENER EL VISIBLE */
    CALL cache.visible_refresh(vCalc, FALSE, vWarehouseFk);
    
    SELECT IFNULL(visible,0) INTO vVisible
		FROM cache.visible
		WHERE calc_id = vCalc 
			AND item_id = vItemFk;
    
    SELECT IF(vIsTrash,200,400) INTO vClientFk;
    
    SELECT t.id INTO vTicketFk
		FROM vn.ticket t
			JOIN vn.address a ON a.id=t.addressFk 
        WHERE t.warehouseFk = vWarehouseFk
			AND t.clientFk = vClientFk
            AND date(t.shipped) = CURDATE()
            AND a.isDefaultAddress
	LIMIT 1;        
 
    IF vTicketFk IS NULL THEN 
    
		CALL vn.ticketCreate(vClientFk, CURDATE(), vWarehouseFk, vCompanyVnlFk, NULL, NULL, NULL, CURDATE(), vTicketFk);
    
    END IF;
    
    INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount)
		SELECT vTicketFk, vItemFk,  CONCAT(vn.getWorkerCode(), " ",LEFT(CAST(NOW() AS TIME),5)," " , longName), vVisible - vNewVisible,0,0
			FROM vn.item 
            WHERE id = vItemFk;
            
	UPDATE cache.visible 
		SET visible = vNewVisible
        WHERE calc_id = vCalc 
			AND item_id = vItemFk;
        
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemTagArrangedUpdateKk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemTagArrangedUpdateKk`(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);
/*
    UPDATE itemTagArranged
		SET 
			tag1 = NULL, val1 = NULL,
			tag2 = NULL, val2 = NULL,
			tag3 = NULL, val3 = NULL,
			tag4 = NULL, val4 = NULL,
			tag5 = NULL, val5 = NULL,
			tag6 = NULL, val6 = NULL
		WHERE vItem = itemFk;
	*/
	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 */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemTagMake` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemTagMake`(vItemFk INT)
BEGIN

/* 	* Crea los tags usando la tabla plantilla itemTag 
	* y si no existe a partir de la ficha del artículo.
	* @param vItemFk El item al que se le añaden los tags
*/
	DECLARE vInk VARCHAR(50);
    DECLARE vSize INTEGER;
    DECLARE vCategory VARCHAR(3);
    DECLARE vProducer VARCHAR(50);
    DECLARE vOrigin VARCHAR(20);
    DECLARE vTypeFk INTEGER;
    
	DELETE FROM itemTag 
		WHERE itemFk = vItemFk;
  
	SELECT typeFk INTO vTypeFk 
		FROM item
        WHERE id = vItemFk;
        
	INSERT INTO itemTag(itemFk, tagFk, value, priority)
		SELECT vItemFk, itt.tagFk, NULL, itt.priority
			FROM itemTag it
				LEFT JOIN itemTypeTag itt ON itt.itemTypeFk = vTypeFk
			WHERE it.itemFk = vItemFk;
	
    IF (SELECT COUNT(*) FROM itemTag WHERE itemFk = vItemFk LIMIT 1) = 0 THEN

		SELECT ik.name, i.size, i.category, p.name, o.name 
				INTO vInk, vSize, vCategory, vProducer, vOrigin
			FROM item i
				LEFT JOIN ink ik ON ik.id = i.inkFk
                LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible
                LEFT JOIN origin o ON o.id = i.originFk
			WHERE i.id = vItemFk;
            
		INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority)
			VALUES(vItemFk, 1, vInk, 1);
                      
		INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority)
			VALUES (vItemFk, 8, vSize, 2);

		INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority)
			VALUES(vItemFk, 47, vCategory, 3);

		INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority)
			VALUES(vItemFk, 37, vProducer, 4);
	   
		INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority)
			VALUES(vItemFk, 35, vOrigin, 5);
	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 `itemTagReorder` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemTagReorder`(itemTypeFk INT)
BEGIN

DECLARE vDone BOOL DEFAULT FALSE;
    DECLARE vItem INT;
    
	DECLARE cur CURSOR FOR
		SELECT id
			FROM upda;
            
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;  
    
	SET @isTriggerDisabled = TRUE;
    
	DROP TEMPORARY TABLE IF EXISTS upda;
	create temporary table upda
		SELECT DISTINCT i.id
			FROM vn.item i 
				WHERE i.typeFk = itemTypeFk;

	UPDATE itemTag it
			JOIN item i ON i.id = it.itemFk
            JOIN itemTypeTag itt ON itt.itemTypeFk = i.typeFk AND itt.tagFk = it.tagFk
		SET it.priority = itt.priority
		WHERE itt.itemTypeFk = itemTypeFk;
        
   OPEN cur;
    proc: LOOP
		SET vDone = FALSE;
		FETCH cur INTO vItem;
        IF vDone THEN
			LEAVE proc;
		END IF;
		CALL vn.itemRefreshTags(vItem); 
	END LOOP;
    CLOSE cur;
	SET @isTriggerDisabled = 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 `itemTagReorderByName` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemTagReorderByName`(vName VARCHAR(255))
BEGIN

DECLARE vDone BOOL DEFAULT FALSE;
    DECLARE vItem INT;
    
	DECLARE cur CURSOR FOR
		SELECT id
			FROM upda;
            
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;  
    
	SET @isTriggerDisabled = TRUE; 
       
	DROP TEMPORARY TABLE IF EXISTS upda;
	CREATE TEMPORARY TABLE upda
		SELECT DISTINCT i.id
			FROM vn.item i 
				WHERE i.name LIKE CONCAT(vName,'%');

	UPDATE itemTag it
			JOIN item i ON i.id = it.itemFk
            JOIN itemTypeTag itt ON itt.itemTypeFk = i.typeFk AND itt.tagFk = it.tagFk
		SET it.priority = itt.priority
		WHERE itt.itemTypeFk = itemTypeFk;
        
   OPEN cur;
    proc: LOOP
		SET vDone = FALSE;
		FETCH cur INTO vItem;
        IF vDone THEN
			LEAVE proc;
		END IF;
		CALL vn.itemRefreshTags(vItem); 
	END LOOP;
    CLOSE cur;
	SET @isTriggerDisabled = 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 `itemTagReplace` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemTagReplace`(fromItemFk INT, toItemFk INT)
BEGIN


	DELETE FROM itemTag 
		WHERE itemFk = toItemFk;
        
	INSERT INTO itemTag(itemFk, tagFk, value, priority)
		SELECT toItemFk, tagFk, value, priority
			FROM itemTag
			WHERE itemFk = fromItemFk;
            
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemTopSeller` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemTopSeller`()
BEGIN
	DECLARE vCategoryFk INTEGER;
	DECLARE vDone INT DEFAULT FALSE;
	DECLARE rs CURSOR FOR
		 SELECT DISTINCT id
		  FROM  vn.itemCategory
		  WHERE merchandise <> FALSE;
          
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
	DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN  
	RESIGNAL;
	END;

	DROP TABLE IF EXISTS tmp.topSellerMin;
	CREATE TEMPORARY TABLE tmp.topSellerMin ENGINE = MEMORY
		SELECT s.itemFk, SUM(s.quantity) AS total, v.tipo_id typeFk
			FROM vn.sale s
				INNER JOIN bs.ventas v ON v.Id_Movimiento = s.id
			WHERE v.fecha BETWEEN TIMESTAMPADD(DAY, - 7, CURDATE()) AND CURDATE()
			GROUP BY s.itemFk;
        
	DROP TABLE IF EXISTS tmp.topSeller;
	CREATE TEMPORARY TABLE tmp.topSeller   
		(   
			`id` int(11) NOT NULL DEFAULT '0',
			`typeFk` smallint(5) unsigned NOT NULL,
			`itemCategoryFk` int(10) unsigned NOT NULL,
			`total` bigint(21) NOT NULL DEFAULT '0'
		) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
		
	OPEN rs;
	 read_loop: LOOP
		FETCH rs INTO vCategoryFk;
		
		IF vDone THEN
			LEAVE read_loop;
		END IF;
		
		INSERT INTO tmp.topSeller
			SELECT  tsm.itemFk, tsm.typeFk, it.categoryFk, tsm.total
			FROM tmp.topSellerMin tsm
				INNER JOIN vn.itemType it ON  it.id = tsm.typeFk
			WHERE it.categoryFk = vCategoryFk
			ORDER BY  tsm.itemFk ,tsm.total DESC
			LIMIT 5; 

	END LOOP;
	CLOSE rs;
    
    SELECT i.name ,i.id, i.image, i.typeFk, it.categoryFk AS itemCategoryFk,
		ic.name AS itemCategoryName, it.name AS itemTypeName, ts.total
		FROM tmp.topSeller ts
			INNER JOIN vn.item i ON i.id = ts.id
			INNER JOIN vn.itemType it ON  it.id = ts.typeFk
			INNER JOIN vn.itemCategory ic ON ic.id = it.categoryFk;
    
    DROP TABLE IF EXISTS topSellerMin;
    DROP TABLE IF EXISTS tmp.topSeller;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemUpdateTag` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemUpdateTag`(IN vItem BIGINT)
BEGIN


UPDATE item i
JOIN producer p ON p.id = i.producerFk
SET i.subName = p.name
WHERE p.isVisible
AND (vItem IS NULL OR vItem = i.id);

UPDATE item i
JOIN itemTag it ON it.itemFk = i.id
JOIN tag t ON t.id = it.tagFk
SET tag5 = t.name, value5 = it.value
WHERE it.priority = 1
AND (vItem IS NULL OR vItem = i.id);

UPDATE item i
JOIN itemTag it ON it.itemFk = i.id
JOIN tag t ON t.id = it.tagFk
SET tag6 = t.name, value6 = it.value
WHERE it.priority = 2
AND (vItem IS NULL OR vItem = it.itemFk);

UPDATE item i 
JOIN itemTag it ON it.itemFk = i.id
JOIN tag t ON t.id = it.tagFk
SET tag7 = t.name, value7 = it.value
WHERE it.priority = 3
AND (vItem IS NULL OR vItem = it.itemFk);

UPDATE item i
JOIN itemTag it ON it.itemFk = i.id
JOIN tag t ON t.id = it.tagFk
SET tag8 = t.name, value8 = it.value
WHERE it.priority = 4
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 */ ;
/*!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
 */
    
    CALL logAddWithUser(vOriginFk, account.userGetId(), vActionCode, vEntity, vDescription);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `logAddWithUser` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `logAddWithUser`(vOriginFk INT, vUserId 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(255) DEFAULT CONCAT(IFNULL(vEntity, ''), 'Log');

	SET @sqlQuery = CONCAT(
		'INSERT INTO vn.', vTableName, ' SET originFk = ?, userFk = ?, action = ?, description = ?'
		);
	SET @originFk = vOriginFk;
	SET @userFk = vUserId;
	SET @action = vActionCode;
	SET @description = vDescription;

	PREPARE stmt FROM @sqlQuery;
	EXECUTE stmt USING @originFk, @userFk, @action, @description;
	DEALLOCATE PREPARE stmt;

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

	DECLARE newItemFk INT;
    
	SELECT getNewItemId() INTO newItemFk;
    
	INSERT INTO item(id,name,typeFk,originFk)
		SELECT newItemFk, 'Nuevo artículo', 78,39;
        
	SELECT newItemFk;


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

	DECLARE vWorkerIsExcluded BOOLEAN;
	DECLARE vFromDated DATE;
    DECLARE vToDated DATE DEFAULT TIMESTAMPADD(DAY,1,CURDATE());

	SELECT COUNT(*) INTO vWorkerIsExcluded
		FROM bs.manaSpellersExcluded
		WHERE workerFk = worker;
    
	IF NOT vWorkerIsExcluded THEN

		SELECT max(dated) INTO vFromDated 
			FROM clientManaCache;
            
        REPLACE bs.workerMana (workerFk, amount)
			SELECT worker, sum(mana) FROM 
			(
				SELECT s.quantity * sc.value as mana
					FROM ticket t
						JOIN address a ON a.id = t.addressFk
						JOIN client c ON c.id = a.clientFk
						JOIN sale s ON s.ticketFk = t.id
						JOIN saleComponent sc ON sc.saleFk = s.id
					WHERE c.salesPersonFk =  worker AND componentFk IN (39, 37) -- maná auto y maná
						AND t.shipped > vFromDated AND t.shipped < vToDated

				UNION ALL

				SELECT  - r.amountPaid
					FROM receipt r
						JOIN client c ON c.id = r.clientFk
					WHERE c.salesPersonFk = worker AND bankFk = 66
						AND payed > vFromDated
				
				UNION ALL
				
				SELECT g.amount
					FROM greuge g
						JOIN client c ON c.id = g.clientFk
					WHERE c.salesPersonFk = worker AND g.greugeTypeFk = 3 -- Maná
						AND g.shipped > vFromDated and g.shipped < CURDATE()
				
				UNION ALL
				
				SELECT mana
					FROM clientManaCache cc
						JOIN client c ON c.id = cc.clientFk
					WHERE c.salesPersonFk = worker AND cc.dated = vFromDated
			) sub;
	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 `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 vn.ticketLog tl
			JOIN vn2008.Tickets_to_fusion t ON t.Id_Ticket = tl.originFk
			SET tl.originFk = 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;
            
		UPDATE vn2008.Ordenes o
			RIGHT JOIN vn2008.Tickets_to_fusion t ON t.Id_Ticket = o.ticketFk
			SET o.ticketFk = 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);
		
	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              = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nestAdd`(IN `vScheme` VARCHAR(45), IN `vTable` VARCHAR(45), IN `vParentFk` INT, IN `vChild` VARCHAR(100))
BEGIN
	DECLARE vSql TEXT;
	DECLARE vTableClone VARCHAR(45);

	SET vTableClone = CONCAT(vTable, 'Clone');
   
	CALL util.exec(CONCAT('DROP TEMPORARY TABLE IF EXISTS tmp.', vTableClone));
	CALL util.exec(CONCAT(
		'CREATE TEMPORARY TABLE tmp.', vTableClone,
		'	ENGINE = MEMORY'
		'	SELECT * FROM ', vScheme, '.', vTable
  	));

    -- 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, 'tmp', vTableClone, 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, 'tmp', vTableClone, 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;
   
   CALL util.exec(CONCAT('DROP TEMPORARY TABLE tmp.', vTableClone));
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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              = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nestLeave`(vScheme VARCHAR(45), vTable VARCHAR(45), vParentFk INT)
BEGIN
	DROP TEMPORARY TABLE IF EXISTS tmp.tree;
	
    CALL util.exec(CONCAT(
		'CREATE TEMPORARY TABLE tmp.tree ',
			'SELECT 
					node.id, 
					node.name,
					node.lft, 
					node.rgt, 
					node.depth, 
					node.sons
				FROM ',
					vScheme, '.', vTable, ' AS node, ',
					vScheme, '.', vTable, ' AS parent ',
				'WHERE 
					node.lft BETWEEN parent.lft AND parent.rgt 
					AND node.depth = parent.depth + 1
					AND parent.id = ', vParentFk, ' '
				'GROUP BY node.id
				ORDER BY node.lft'));
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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              = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nestTree`(
	vSourceSchema VARCHAR(45), 
	vSourceTable VARCHAR(45), 
	vDestinationSchema VARCHAR(45), 
	vDestinationTable VARCHAR(45))
BEGIN
	DECLARE vTableClone VARCHAR(45);

	SET vTableClone = CONCAT(vSourceTable, 'Clone');
   
	CALL util.exec(CONCAT('DROP TEMPORARY TABLE IF EXISTS tmp.', vTableClone));
	CALL util.exec(CONCAT(
		'CREATE TEMPORARY TABLE tmp.', vTableClone,
		'	ENGINE = MEMORY'
		'	SELECT * FROM ', vSourceSchema, '.', vSourceTable
  	));

	CALL util.exec(CONCAT(
		'DROP TABLE IF EXISTS ', vDestinationSchema, '.', vDestinationTable));
    CALL util.exec(CONCAT(
		'CREATE TABLE ', vDestinationSchema, '.', vDestinationTable,
			' SELECT 
					node.id, 
                    node.name,
					node.lft, 
					node.rgt, 
					COUNT(parent.id) - 1 depth, 
					CAST((node.rgt - node.lft - 1) / 2 as DECIMAL) as sons
				FROM ',
					vSourceSchema, '.', vSourceTable, ' AS node,',
					'tmp.', vTableClone, ' AS parent ',
				'WHERE node.lft 
					BETWEEN parent.lft AND parent.rgt 
				GROUP BY node.id
				ORDER BY node.lft'));
			
	CALL util.exec(CONCAT('DROP TEMPORARY TABLE tmp.', vTableClone));
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `nextShelvingCodeMake` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nextShelvingCodeMake`()
BEGIN

	DECLARE newShelving VARCHAR(3);
    DECLARE vCode VARCHAR(3);
    
    SELECT MAX(code) INTO vCode
		FROM vn.shelving
        WHERE isPrinted = FALSE;
	
    SET @a1 := ASCII(MID(vCode,1,1));
    SET @a2 := ASCII(MID(vCode,2,1));
    SET @a3 := ASCII(MID(vCode,3,1)) + 1;
    
    IF @a3 > 90 THEN
    
		SET @a3 = 65;
        SET @a2 = @a2 + 1;
        
        IF @a2 > 90 THEN
        
			SET @a2 = 65;
            SET @a1 = @a1 + 1;
            
            IF @a1 > 90 THEN
            
				SET @a1 = 65;
            
            END IF;
        
        END IF;
    
    END IF;

	SET newShelving = CHAR(@a1,@a2,@a3 USING utf8);
    
	INSERT INTO vn.shelving(code) VALUES(newShelving);

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!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 `orderCreate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `orderCreate`(
    vLanded DATE,
    vAgencyMode INT,
    vAddress INT,
    vSourceApp VARCHAR(10),
    OUT vOrderId INT)
BEGIN

	DECLARE vDeliveryMethod INT;
	DECLARE vClient INT;
    
    SELECT deliveryMethodFk INTO vDeliveryMethod
		FROM vn.agencyMode 
        WHERE id = vAgencyMode;
	
    SELECT clientFk INTO vClient
		FROM vn.address
        WHERE id = vAddress;
    
	INSERT INTO hedera.order(date_send,customer_id,delivery_method_id,agency_id,address_id,source_app)
		VALUES(	vLanded,vClient ,vDeliveryMethod,vAgencyMode ,vAddress ,vSourceApp);

	SET vOrderId = LAST_INSERT_ID();

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

	DELETE FROM hedera.`order` where id = vId;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `orderListCreate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `orderListCreate`(
    vLanded DATE,
    vAgencyMode INT,
    vAddress INT,
    vSourceApp VARCHAR(10))
BEGIN

    DECLARE vOrderId INT;
    CALL vn.orderCreate(vLanded,vAgencyMode,vAddress,vSourceApp,vOrderId);
    SELECT vOrderId;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `orderListVolume` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `orderListVolume`(IN vOrderId INT)
BEGIN

	SELECT 
			o.id,
            o.itemFk,
            i.description,
            o.amount,
			round(r.cm3 * i.compression * o.amount / 1000000,3) as volume
                FROM hedera.orderRow o
					JOIN vn.item i ON i.id = o.itemFk
                    JOIN bi.rotacion r ON r.Id_Article = o.itemFk AND r.warehouse_id = o.warehouseFk
                WHERE o.orderFk = vOrderId;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 packaging 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
                AND t.companyFk = vCompany;

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

	UPDATE vn2008.Movimientos_mark mm
		JOIN vn2008.Movimientos m ON m.Id_Movimiento = mm.Id_Movimiento
        SET mm.valor = 2 -- Impreso
        WHERE mm.valor = 1 -- Listo para imprimir
        AND mm.stateFk = 9 -- Encajando
        AND m.Id_Ticket = ticketFk;
        
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `packingListSwitch` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `packingListSwitch`(saleFk INT)
BEGIN

	DECLARE valueFk INT;
    DECLARE encajando INT DEFAULT 9;
    DECLARE accionEncajado INT DEFAULT 5;
    
    SELECT valor INTO valueFk 
		FROM vn2008.Movimientos_mark 
		WHERE Id_Movimiento = saleFk 
			AND stateFk = encajando;
            
	SET valueFk = (IFNULL(valueFk,0) + 1) MOD 3;
	
	REPLACE vn2008.Movimientos_mark(Id_Movimiento, valor, Id_Trabajador, Id_Accion, stateFk) 
		VALUES(saleFk,valueFk,getWorker(),accionEncajado,encajando);


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `payRoll` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `payRoll`(IN vFromDated DATE, IN vToDated DATE, IN vFromPaid DATE, IN vToPaid DATE)
BEGIN

	SET @userFk := 0;
    
	SELECT CONCAT(w.lastName,', ',w.firstname) AS Trabajador, 
			CAST(Sum((wj.total + wj.permission + wj.lunch)* wj.priceOrdinaryHour + wj.hollyday * wj.priceHollydayHour 
				 + wj.nocturn * wj.priceNocturnHour
                 + wj.extra * wj.priceExtraHour)  AS DECIMAL(10,2)) AS salario,
			 CAST(Sum(wj.permission)  AS DECIMAL(10,2)) AS permission,
			 CAST(Sum(wj.total)  AS DECIMAL(10,2)) AS total,
			 CAST(Sum(wj.nocturn)  AS DECIMAL(10,2)) AS nocturn, 
			 CAST(Sum(wj.hollyday)  AS DECIMAL(10,2)) AS hollyday, 
			 CAST(Sum(wj.lunch)  AS DECIMAL(10,2)) AS lunch, 
			 CAST(Sum(wj.extra)  AS DECIMAL(10,2)) AS extra, 
			 CAST(Sum(wj.contractJourney)  AS DECIMAL(10,2)) AS contractJourney, 
			 d.name AS departamento, 
			 CAST(Sum((wj.contractJourney + wj.permission) * wj.priceOrdinaryHour) AS DECIMAL(10,2)) AS teorico, 
			 CAST(Sum((wj.lunch + wj.permission + wj.total) * wj.priceordinaryhour)  AS DECIMAL(10,2)) AS practico, 
			 CAST(Sum(wj.nocturn * wj.pricenocturnhour)  AS DECIMAL(10,2)) AS nocturno, 
			 CAST(Sum(wj.hollyday * wj.priceHollydayHour)  AS DECIMAL(10,2)) AS festivos, 
			 CAST(Sum(wj.extra * wj.priceextrahour)  AS DECIMAL(10,2)) AS extras, 
			 MAX(wj.businessFk) as businessFk, 
			 Min(b.date_start) AS fromDated, 
			 Max(b.date_end) AS toDated, 
			 blp.importepactado,
             bl.porhoras,
             IF(wj.userFk != @userFk, CAST(IFNULL(a.Anticipos,0) AS DECIMAL(10,2)), 0) AS Anticipos,
             IF(wj.userFk != @userFk, CAST(IFNULL(se.SaldoEuros,0) AS DECIMAL(10,2)), 0) AS SaldoEuros,
             @userFk := wj.userFk as userFk
             
	FROM vn.worker w 
        JOIN vn.workerJourney wj ON w.userFk = wj.userFk
        JOIN postgresql.business_labour bl ON bl.business_id = wj.businessFk
		JOIN vn2008.department d ON bl.department_id = d.department_id
        JOIN postgresql.business_labour_payroll blp ON bl.business_id = blp.business_id
        JOIN postgresql.business b ON b.business_id = wj.businessFk
        LEFT JOIN 
			(SELECT userFk, sum(debe) as Anticipos
				FROM postgresql.income_employee ie
					JOIN postgresql.person pe ON ie.person_id = pe.person_id
					JOIN vn.worker w ON w.id = pe.id_trabajador
				WHERE odbc_date BETWEEN vFromPaid AND vToPaid
					AND id_incomeType = 14 -- Salario
				GROUP BY userFk
			) a ON a.userFk = wj.userFk
		LEFT JOIN 
			(SELECT userFk, sum(debe) - sum(haber) as SaldoEuros
				FROM postgresql.income_employee ie
					JOIN postgresql.person pe ON ie.person_id = pe.person_id
					JOIN vn.worker w ON w.id = pe.id_trabajador
				GROUP BY userFk
			) se ON se.userFk = wj.userFk
	WHERE wj.dated BETWEEN vFromDated AND vToDated
	GROUP BY wj.userFk
	ORDER BY w.lastName, w.firstname;


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

	DECLARE vCalcFk INT;
    
	-- CALL vn.ticketDepartureMake;
    CALL cache.ticketShippingRefresh(vCalcFk, FALSE, 1);
    
    
    SELECT isa.*, 
            cast(max(isa.quantity mod isa.packing) as DECIMAL(10,0)) as picos,
			sum(isa.available) as totalAvailable, 
            tsh.shippingHour Hora, 
            tsh.shippingMinute Minuto, 
            i.subName
		FROM vn.itemShelvingAvailable isa
        JOIN vn.item i ON i.id = isa.itemFk
        LEFT JOIN cache.ticketShipping tsh ON tsh.ticketFk = isa.ticketFk
        WHERE tsh.calc_id = vCalcFk AND MOD(TRUNCATE(isa.quantity,0), isa.packing)= 0
        AND isa.sectorProdPriority <= 3
        GROUP BY saleFk
        HAVING isa.quantity <= totalAvailable;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!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 vOriginTicket INT, OUT vNewTicket INT)
BEGIN
	
	DECLARE vDone BIT DEFAULT 0;
	DECLARE vCustomer MEDIUMINT;
	DECLARE vNewShipped DATE;
	DECLARE vWarehouse TINYINT;
	DECLARE vCompany MEDIUMINT;
	DECLARE vAddress MEDIUMINT;
    DECLARE vRefundAgencyMode INT DEFAULT 23;
    DECLARE vItemFk INT;
    DECLARE vQuantity DECIMAL (10,2);
    DECLARE vConcept VARCHAR(50);
    DECLARE vPrice DECIMAL (10,2);
    DECLARE vDiscount TINYINT;
	DECLARE vSaleNew INT;
    DECLARE vSaleMain INT;
    
    DECLARE vRsMainTicket CURSOR FOR
		SELECT id, itemFk, - quantity, concept, price, discount
			FROM vn.sale 
            WHERE ticketFk = vOriginTicket;
    
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1;
	
	SELECT clientFk, TIMESTAMPADD(DAY, 1,shipped), warehouseFk, companyFk, addressFk 
			INTO vCustomer, vNewShipped, vWarehouse, vCompany, vAddress
		FROM ticket 
        WHERE id = vOriginTicket;

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

	SET vDone := 0;	
	OPEN vRsMainTicket ;
    FETCH vRsMainTicket INTO vSaleMain, vItemFk, vQuantity, vConcept, vPrice, vDiscount;

	WHILE NOT vDone DO
    
		INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price, discount)
			VALUES( vNewTicket, vItemFk, vQuantity, vConcept, vPrice, vDiscount );
            
        SET vSaleNew = LAST_INSERT_ID();
        
        INSERT INTO vn.saleComponent(saleFk,componentFk,`value`) 
        SELECT vSaleNew,componentFk,`value`  
			FROM vn.saleComponent 
            WHERE saleFk = vSaleMain;
        
		FETCH vRsMainTicket INTO vSaleMain, vItemFk, vQuantity, vConcept, vPrice, vDiscount;
        
	END WHILE;
	CLOSE vRsMainTicket; 

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `replaceMovimientosMark` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `replaceMovimientosMark`(
	idMovimiento INT,
	detalle INT,
    originalQuantity INT,
    idTrabajador INT,
    stateFk INT,
    originFk INT,
    userFk INT,
    actionString VARCHAR(50),
    description VARCHAR(100))
BEGIN
	REPLACE INTO vn2008.Movimientos_mark(Id_Movimiento, valor, original_quantity, Id_Trabajador, stateFk) 
		VALUES(idMovimiento,detalle,originalQuantity,idTrabajador,stateFk);
    /*INSERT INTO vn.ticketLog (originFk, userFk, action , description) 
		VALUES(originFk, userFk, actionString, description);*/
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `riskAllClients` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `riskAllClients`(maxRiskDate DATE)
BEGIN
	
	DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
    CREATE TEMPORARY TABLE tmp.client_list
    (PRIMARY KEY (Id_Cliente))
		ENGINE = MEMORY
		SELECT id Id_Cliente, null grade FROM vn.client;
    
    CALL vn2008.risk_vs_client_list(maxRiskDate);
    
	SELECT 
		c.RazonSocial,
        c.Id_Cliente,
        c.Credito,
        CAST(r.risk as DECIMAL (10,2)) risk,
        CAST(c.Credito - r.risk as DECIMAL (10,2)) Diferencia,
        c.Id_Pais
	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
		GROUP BY c.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 */ ;
/*!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 < 2
				WHERE t.Fecha BETWEEN CURDATE() AND util.dayend(CURDATE())
                AND t.warehouse_id IN (1,44)
				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),
            rg.ready = IF(rg.freeTickets, FALSE, rg.ready);


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `routeGuessPriority` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `routeGuessPriority`(IN vRuta INT)
BEGIN
/* Usa los valores del ultimo año para adivinar el orden de los tickets en la ruta
 * vRuta id ruta
*/

UPDATE ticket mt
	JOIN (
		SELECT tt.addressFk, ROUND(IFNULL(AVG(t.priority),0),0) AS priority
			FROM ticket t
				JOIN ticket tt ON tt.addressFk = t.addressFk
			WHERE t.shipped > TIMESTAMPADD(YEAR,-1,CURDATE())
				AND tt.routeFk = vRuta
			GROUP BY addressFk
		) sub ON sub.addressFk = mt.addressFk
	SET mt.priority = sub.priority
		WHERE mt.routeFk = vRuta;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `routeUpdateM3` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `routeUpdateM3`(vRoute INT)
BEGIN

	UPDATE vn.route r
		JOIN (SELECT Id_Ruta, SUM(volume) AS m3
					FROM vn2008.v_Movimientos_Volumen_shipping_charge  
					WHERE Id_Ruta = vRoute
			 ) v ON v.Id_Ruta = r.id
		SET r.m3 = v.m3;
        
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `rutasAnalyze` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!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 `rutasAnalyze`(vYear INT, vMonth INT)
BEGIN


/* Analiza los costes de las rutas de reparto y lo almacena en la tabla Rutas_Master
*  
* PAK 15/4/2019
*/

	DELETE FROM bi.rutasBoard
		WHERE year = vYear AND month = vMonth;
   
   -- Rellenamos la tabla con los datos de las rutas, especialmente con los bultos "virtuales"
    INSERT INTO bi.rutasBoard(  year,
								month,
								warehouse_id,
								Id_Ruta,
								Id_Agencia,
								km,
								Dia,
								Fecha,
								Bultos,
								Matricula,
								Tipo,
                                Terceros)
		SELECT  year,
				month,
				GREATEST(1,warehouse_id),
				Id_Ruta,
				Id_Agencia,
				km,
				Dia,
				Fecha,
				sum(Bultos) as Bultos,
				Matricula,
				Tipo,
                cost
			FROM bi.rutas 
			WHERE year = vYear AND month = vMonth
				
			GROUP BY Id_Ruta;
   
   -- Coste REAL de cada bulto "virtual", de acuerdo con el valor apuntado a mano en la ruta
	UPDATE bi.rutasBoard r
		INNER JOIN vn2008.Rutas_Master rm ON rm.año = r.year AND rm.mes = r.month AND rm.warehouse_id = r.warehouse_id
			SET r.coste_bulto = IF(r.Tipo ='A', r.Terceros, r.km * rm.coste_km ) / r.Bultos
			WHERE r.Bultos > 0
                AND rm.año = vYear
                AND rm.mes = vMonth;
                
	-- Coste PRACTICO de cada bulto, de acuerdo con los componentes de tipo AGENCIA en cada linea de venta 
    
	UPDATE bi.rutasBoard r
		JOIN (
				SELECT t.routeFk, sum(s.quantity * sc.value) practicoTotal
					FROM vn.route r
						JOIN vn.time tm ON tm.dated = r.created
						JOIN vn.ticket t ON t.routeFk = r.id
						JOIN vn.sale s ON s.ticketFk = t.id
						JOIN vn.saleComponent sc ON sc.saleFk = s.id
						JOIN vn.componentRate cr ON cr.id = sc.componentFk
						JOIN vn.componentTypeRate ctr ON ctr.id = cr.componentTypeRate
					WHERE ctr.type = 'agencia'
						AND tm.year = vYear 
						AND tm.month = vMonth
					GROUP BY r.id
			 ) sub ON sub.routeFk = r.Id_Ruta
		SET r.practico = sub.practicoTotal / r.Bultos;
        
	-- Coste TEORICO de una caja "virtual" para cada ruta, teniendo en cuenta que hay carros, pallets, etc
	UPDATE bi.rutasBoard r
		JOIN (
			SELECT  t.routeFk, 
					SUM(az.price/ ebv.ratio)/ count(*) AS BultoTeoricoMedio
				FROM vn.ticket t
					JOIN vn.route r ON r.id = t.routeFk
					JOIN vn.time tm ON tm.dated = r.created
					JOIN vn.expedition e ON e.ticketFk = t.id
					JOIN vn.expeditionBoxVol ebv ON ebv.boxFk = e.isBox
					JOIN vn.address ad ON ad.id = t.addressFk
					JOIN vn.client c ON c.id = ad.clientFk
					JOIN vn.agencyMode am ON am.id = t.agencyModeFk
					JOIN vn.agencyProvince ap ON ap.warehouseFk = t.warehouseFk
						AND ap.provinceFk = ad.provinceFk
						AND ap.agencyFk = am.agencyFk
					JOIN vn.agencyModeZone az ON az.agencyModeFk = t.agencyModeFk
						AND az.zone = ap.zone
						AND t.warehouseFk = az.warehouseFk
						AND az.itemFk = e.isBox
				WHERE  tm.year = vYear 
							AND tm.month = vMonth
				GROUP BY t.routeFk) sub ON r.Id_Ruta = sub.routeFk
		SET r.teorico = sub.BultoTeoricoMedio;
        
   -- La diferencia entre el teorico y el practico se deberia de cobrar en greuges, cada noche
   UPDATE bi.rutasBoard r
		JOIN (
			SELECT  t.routeFk, 
					Sum(g.amount) AS greuge
				FROM vn.ticket t
					JOIN vn.route r ON r.id = t.routeFk
					JOIN vn.time tm ON tm.dated = r.created
					JOIN vn.greuge g ON g.ticketFk = t.id
                    JOIN vn.greugeType gt ON gt.id = g.greugeTypeFk
				WHERE tm.year = vYear 
					AND tm.month = vMonth
                    AND gt.name = 'Diferencia portes'
				GROUP BY t.routeFk) sub ON r.Id_Ruta = sub.routeFk
		SET r.greuge = sub.greuge / r.Bultos;
        
     
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `saleItemShelvingDelete` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingDelete`(vSaleFk INT)
BEGIN

	UPDATE vn.itemShelving ish
		JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id
        SET ish.visible =  sis.quantity + ish.visible,
        ish.available = sis.quantity + ish.visible
        WHERE sis.saleFk = vSaleFk;
        
	DELETE FROM vn.saleItemShelving 
		WHERE saleFk = vSaleFk;
   
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `saleItemShelvingIsPicked` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingIsPicked`(vTicketFk INT, vIsPicked BOOL)
BEGIN

	DECLARE vStateFk INT;
    
    SELECT id INTO vStateFk
		FROM state
		WHERE code = 'PREVIOUS_PREPARATION';

	UPDATE vn.sale s
		JOIN vn.saleItemShelving sis ON sis.saleFk = s.id
        SET s.isPicked = vIsPicked
        WHERE s.ticketFk = vTicketFk;
        
	REPLACE vn2008.Movimientos_mark(Id_Movimiento, Valor, original_quantity, Id_Trabajador,  stateFk) 
		SELECT s.id, s.isPicked, s.quantity, getWorker(), vStateFk
			FROM sale s
				JOIN vn.saleItemShelving sis ON sis.saleFk = s.id
            WHERE s.ticketFk = vTicketFk;
            
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `saleItemShelvingMake` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingMake`(IN `vTicketFk` INT, IN `vSectorFk` INT)
BEGIN
  
    SET @rest:= CAST(0 AS DECIMAL(10,0));
    SET @saleFk := CAST(0 AS DECIMAL(10,0));
    SET @reserved := CAST(0 AS DECIMAL(10,0));
    
    UPDATE vn.itemShelving ish
		JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id
			JOIN sale s ON s.id = sis.saleFk
        SET ish.visible =  sis.quantity + ish.visible,
			ish.available = sis.quantity + ish.visible
        WHERE s.ticketFk = vTicketFk;
        
    DELETE sis.*
		FROM saleItemShelving sis
			JOIN sale s ON s.id = sis.saleFk
		WHERE s.ticketFk = vTicketFk;
    
	INSERT INTO saleItemShelving(	saleFk, 
									itemShelvingFk,
									quantity,
                                    ubication)
		SELECT saleFk, 
			   itemShelvingFk,
               CAST(Reserved as DECIMAL(10,0)) as Reserved,
               ubication
			FROM
				(SELECT saleFk, 
						itemShelvingFk, 
                        ubication,
						@rest := IF(@saleFk = saleFk, @rest, quantity) as Falta,
						@reserved := IF(available < @rest, available, IF(@rest < packing,0,@rest)) as Reserved,
						@rest := @rest - @reserved,
						@saleFk := saleFk
					FROM
						(	SELECT  s.id as saleFk, 
									ish.created,
									ish.id as itemShelvingFk, 
									ish.available,
									s.quantity,
									ish.packing,
                                    CONCAT(p.`column`, '-',p.`row`,': ', sh.code ) as ubication
								FROM vn.sale s
									JOIN vn.ticket t ON t.id = s.ticketFk
									JOIN vn.sector sc ON sc.warehouseFk = t.warehouseFk
									JOIN vn.parking p ON p.sectorFk = sc.id
									JOIN vn.shelving sh ON sh.parkingFk = p.id
									JOIN vn.itemShelving ish ON ish.shelvingFk = sh.code AND ish.itemFk = s.itemFk 
								WHERE t.id = vTicketFk
									AND sc.id = vSectorFk
                                    AND s.quantity MOD ish.packing = 0
                                    AND s.quantity >= ish.packing
								ORDER BY 	s.id, 
											sh.priority DESC, 
											ish.packing DESC, 
											ish.created 
						) sub
				) sub2
		WHERE Reserved > 0;
     
		UPDATE vn.itemShelving ish
			JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id
            JOIN vn.sale s ON s.id = sis.saleFk
            SET ish.available = ish.visible - sis.quantity,
				ish.visible = ish.visible - sis.quantity
            WHERE s.ticketFk = vTicketFk
				AND s.isPicked = FALSE;
            
		CALL vn.saleItemShelvingIsPicked(vTicketFk, 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 `saleMove` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `saleMove`(IN vSaleFk BIGINT, IN vQuantity BIGINT)
BEGIN

		DECLARE vclientFk INT;
		DECLARE vShipped DATE;
		DECLARE vWarehouseFk INT;
		DECLARE vCompanyFk INT;
		DECLARE vAddressFk INT;
		DECLARE vAgencyModeFk INT;
		DECLARE vNewTicket BIGINT;
		DECLARE vNewSale BIGINT;
		DECLARE vLanded DATE;
		DECLARE vDateStart DATETIME;
		DECLARE vDateEnd DATETIME;
		DECLARE vAuxId INT;
        DECLARE vNumLine INT;
        DECLARE vItemFk INT;
 
	 SELECT clientFk,shipped,warehouseFk,companyFk,addressFk,agencyModeFk,landed,t.id
			INTO vclientFk,vShipped,vWarehouseFk,vCompanyFk,vAddressFk,vAgencyModeFk,vLanded,vAuxId
		FROM ticket t
			JOIN sale s ON s.ticketFk=t.id
		WHERE s.id = vSaleFk;
 
 SET vDateStart = TIMESTAMP(vShipped);
 SET vDateEnd = TIMESTAMP(vShipped, '23:59:59');
  
 SELECT t.id INTO vNewTicket
		FROM ticket t 
			JOIN ticketState ts ON ts.ticketFk=t.id
		WHERE t.addressFk = vAddressFk
			AND t.warehouseFk = vWarehouseFk 
		    AND t.agencyModeFk = vAgencyModeFk
		    AND t.landed <=> vLanded
		    AND t.shipped BETWEEN vDateStart AND vDateEnd 
		    AND t.refFk IS NULL
		    AND t.clientFk <> 1118
		    AND t.id <> vAuxId
            AND IFNULL(ts.alertLevel,0) = 0
		LIMIT 1; 

IF vNewTicket IS NULL
	THEN
		CALL ticketCreate(vclientFk , vShipped , vWarehouseFk , vCompanyFk , vAddressFk , vAgencyModeFk , NULL,vLanded , vNewTicket);
		CALL vn2008.bionic_calc_ticket(vNewTicket);
 END IF;

 INSERT INTO ticketTracking(ticketFk, workerFk, stateFk)
  SELECT vNewTicket, getWorker(), s.id
   FROM state s
   WHERE s.code = 'FIXING';
  
 
 /*parche para campapña, eliminar y modificar el front*/
SELECT COUNT(id) INTO vNumLine
		FROM sale s
		WHERE  s.ticketFk = vNewTicket AND s.itemFk = (SELECT itemFk FROM sale WHERE id = vSaleFk);
 
 IF vNumLine = 0 THEN
 
	 INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount) 
		SELECT vNewTicket, itemFk, concept, vQuantity, price, discount
			FROM sale s
			WHERE s.id = vSaleFk;
	 
	 SELECT LAST_INSERT_ID() INTO vNewSale;
	 
	 INSERT INTO saleComponent(saleFk, componentFk, `value`)
		SELECT vNewSale, componentFk, `value`
			FROM saleComponent 
			WHERE saleFk = vSaleFk;
        
ELSE IF vQuantity <> 0 THEN

	SELECT itemFk INTO vItemFk FROM sale WHERE id = vSaleFk;
	UPDATE sale  SET quantity = vQuantity
	WHERE  ticketFk = vNewTicket AND  itemFk = vItemFk;

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

	SELECT  t.clientFk, 
			t.shipped, 
            a.nickname, 
			s.ticketFk,
			s.itemFk, 
			s.quantity, 
			s.concept, 
			s.reserved,
			s.id saleFk,
            i.size,
			i.inkFk,
			i.stems,
			i.image,
			i.subName,
			b.`grouping`,
			ip.code as placement, 
			lpad(ifnull(cooler_path_detail_id, ip.code),5,'0') as path, 
            IF(stPrevious.saleFk,TRUE,FALSE) as isPreviousSelected,
			stPrevious.isChecked as isPrevious,
            stPrepared.isChecked as isPrepared,
            stControled.isChecked as isControled,
            ib.code as barcode
     
	FROM vn.ticket t
		JOIN vn.address a ON a.id = t.addressFk
		JOIN vn.sale s ON s.ticketFk = t.id
        JOIN vn.item i ON i.id = s.itemFk
        LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND ip.warehouseFk = t.warehouseFk
        LEFT JOIN vn2008.cooler_path_detail cpd on left(ip.code,3) = cpd.pasillo 
        LEFT JOIN bi.Last_buy_id lb ON lb.Id_Article = i.id AND lb.warehouse_id = t.warehouseFk
        LEFT JOIN vn.buy b ON b.id = lb.Id_Compra
		LEFT JOIN vn.saleTracking stPrepared ON stPrepared.saleFk = s.id AND stPrepared.stateFk = 14
        LEFT JOIN vn.saleTracking stControled ON stControled.saleFk = s.id AND stControled.stateFk = 8
        LEFT JOIN vn.saleTracking stPrevious ON stPrevious.saleFk = s.id AND stPrevious.stateFk = 26
        LEFT JOIN vn.itemBarcode ib ON ib.itemFk = i.id
        
    WHERE t.id = idT 
    GROUP BY s.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 `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`(vSaleFk INT, vQuantity INT)
BEGIN

	
    DECLARE vNewSaleFk INT;
        
    INSERT INTO vn.sale(itemFk, 
						concept, 
                        price, 
                        discount, 
                        quantity, 
                        ticketFk, 
                        isPriceFixed)
		SELECT 	s.itemFk, 
				i.longName, 
                s.price, 
                s.discount, 
                vQuantity,
                s.ticketFk, 
                s.isPriceFixed 
			FROM vn.sale s
				JOIN vn.item i ON i.id = s.itemFk
				WHERE s.id = vSaleFk;
                
	UPDATE vn.sale s
		JOIN vn.item i ON i.id = s.itemFk
		SET s.quantity = s.quantity - vQuantity, s.concept = i.longName
        WHERE s.id = vSaleFk;
 
	SELECT LAST_INSERT_ID() INTO vNewSaleFk;
             
	INSERT INTO vn.saleComponent(	saleFk, 
									componentFk, 
                                    value)
	SELECT 	vNewSaleFk, 
			componentFk, 
			value
		FROM vn.saleComponent 
		WHERE saleFk = vSaleFk;

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


REPLACE INTO vn.routeLoadWorker(routeFk, workerFk) 
VALUES(routeFk,workerFk);

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `scanTreeCreate`()
BEGIN
	CALL 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,
		ADD PRIMARY KEY(`id`);

	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 expedition e ON e.id = sl.`code`
					JOIN 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 `setPlacementReserve` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `setPlacementReserve`(vItemFk INT, vPlacement VARCHAR(10), vWarehouseFk INT )
BEGIN

	DECLARE vReserve VARCHAR(10);
    DECLARE vReserveOLD VARCHAR(10);
    DECLARE vPlacementOLD VARCHAR(10);
    
    SELECT code, reserve INTO vPlacementOLD, vReserveOLD
		FROM itemPlacement
        WHERE itemFk = vItemFk
			AND warehouseFk = vWarehouseFk;
    
    IF ASCII(vPlacement) > 57 THEN
    
		SET vReserve = vPlacement;
        SET vPlacement = vPlacementOLD;
        
	ELSE
    
		SET vReserve = vReserveOLD;
        
	END IF;
    
    REPLACE itemPlacement(itemFk, warehouseFk, code,reserve)
		VALUES(vItemFk, vWarehouseFk, vPlacement, vReserve);


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `shelvingChange` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `shelvingChange`(IN `vShelvingO` VARCHAR(8), IN `vShelvingD` VARCHAR(8))
BEGIN

     UPDATE vn.itemShelving
     SET shelvingFk =  vShelvingD COLLATE utf8_unicode_ci 
     WHERE shelvingFk = vShelvingO COLLATE utf8_unicode_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 `shelvingPark` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `shelvingPark`(IN `vShelvingFk` VARCHAR(8), IN `vParkingCode` VARCHAR(8))
BEGIN

	DECLARE vParkingFk INT DEFAULT 0;
    DECLARE idParking INT;
    DECLARE vColumn VARCHAR(3);
    DECLARE vRow VARCHAR(2);
    DECLARE vReturn VARCHAR(50);
    
    /*ELIMINAR ESPACIOS*/
    SET vParkingCode = replace(vParkingCode,' ','')  ;
     
	/*SINO EXISTE EL PARKING LO CREAMOS*/
	SELECT id INTO idParking
	FROM vn.parking
	WHERE code = vParkingCode COLLATE utf8_unicode_ci;

	IF idParking IS NULL THEN      
		IF LOCATE('-',vParkingCode) = 4 THEN
			SELECT SUBSTRING_INDEX(vParkingCode,'-',1) INTO vColumn;
			SELECT SUBSTRING_INDEX(vParkingCode,'-',-1) INTO vRow;
			INSERT INTO vn.parking(`column`,`row`,code,sectorFk)
			VALUES(vColumn,vRow,vParkingCode,2);
		END IF;
	END IF;
	/*FIN INSERTAR PARKING*/


	SELECT id INTO vParkingFk
		FROM vn.parking
		WHERE `code` = vParkingCode COLLATE utf8_unicode_ci;
 
	IF length(vShelvingFk) > 6 THEN
    
    
		REPLACE vn.shelving(code, parkingFk, isPrinted, parked)
			VALUES(vShelvingFk, vParkingFk, TRUE, NOW());
            
		CALL vn.ticketStatePrevious(vShelvingFk);
      
    ELSE
    
    
		UPDATE vn.shelving
			SET parkingFk = vParkingFk, parked = NOW()
			WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci;
            
            SELECT (COUNT(*) > 0) AS IsUpdated
			FROM vn.shelving
			WHERE parkingFk = vParkingFk
				AND `code` = vShelvingFk COLLATE utf8_unicode_ci;
		
     END IF;     
     
     
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `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
                    AND isVirtualStock is FALSE
				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 `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 `stowawayBoarding` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `stowawayBoarding`(IN vShipFk INT, IN vStowawayFk INT)
BEGIN
	
	REPLACE stowaway(shipFk, id)
		VALUES (vShipFk, vStowawayFk);
        

	-- Polizón FIXME mostrar en encajado y movil a tiempo real
 /*   INSERT INTO ticketObservation(ticketFk, observationTypeFk, description)
		SELECT vStowawayFk, id, 'POLIZÓN!'
			FROM observationType ot
            WHERE ot.description IN ('Sacador', 'Encajador')
            ON DUPLICATE KEY UPDATE description = CONCAT('POLIZÓN! ',ticketObservation.description);
	-- Nave FIXME mostrar en encajado y movil a tiempo real
    INSERT INTO ticketObservation(ticketFk, observationTypeFk, description)
		SELECT vShipFk, id, CONCAT('POLIZÓN: ', vStowawayFk)
			FROM observationType
            WHERE description IN ('Sacador','Repartidor')
            ON DUPLICATE KEY UPDATE description = CONCAT('POLIZÓN! ',ticketObservation.description);
*/ 
    INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador, Id_Supervisor)
		SELECT id, vShipFk, getWorker(),20
			FROM state
            WHERE code = 'BOARDING'; 
            
	-- FIXME  No crear ticket 98    
	INSERT INTO sale(ticketFk, itemFk, quantity, concept)
		VALUES(vShipFk, 98,1, CONCAT('POLIZÓN! ',vStowawayFk));
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `stowawayUnBoarding` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `stowawayUnBoarding`(vShipFk INT, vStowawayFk INT)
BEGIN
	
    DECLARE vWorker VARCHAR(255);
    
	DELETE FROM stowaway 
		WHERE shipFk = vShipFk AND id = vStowawayFk;
    
    DELETE tt FROM ticketTracking tt
		JOIN state s ON s.id = tt.stateFk
            WHERE code = 'BOARDING' AND ticketFk = vShipFk; 
   	
    DELETE FROM sale 
		WHERE ticketFk = vShipFk AND itemFk = 98 AND concept = CONCAT('POLIZÓN! ',vStowawayFk);         
        
	SELECT u.`name` INTO vWorker 
		FROM account.user u JOIN vn.worker w ON w.userFk = u.id
		WHERE w.id = vn2008.Averiguar_ComercialCliente_IdTicket_Id(vStowawayFk);
            
	SELECT messageSend(vWorker,CONCAT('El ticket: ', vStowawayFk, ' ha dejado de ser un polizón')) INTO @a;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `subordinateGetList` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `subordinateGetList`(vBossFk INT)
BEGIN
	DECLARE vBossId INT;
    DECLARE vDone BOOL;
	DECLARE workerCur CURSOR FOR
		SELECT workerFk 
			FROM tmp.subordinate 
			WHERE NOT isChecked;
            

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
    DECLARE EXIT HANDLER FOR 1062 BEGIN
		CALL util.throw('INFINITE_LOOP');
    END;

	DROP TEMPORARY TABLE IF EXISTS tmp.subordinate;
    
    CREATE TEMPORARY TABLE tmp.subordinate
        (PRIMARY KEY (workerFk))
        ENGINE = MEMORY
		SELECT vBossFk AS workerFk, 0 AS isChecked;
        
    WHILE (SELECT COUNT(*) FROM tmp.subordinate WHERE NOT isChecked) > 0 DO
		OPEN workerCur;
		workerLoop: LOOP
			SET vDone = FALSE;

			FETCH workerCur INTO vBossId;
			
			IF vDone THEN
				LEAVE workerLoop;
			END IF;
		
			INSERT INTO tmp.subordinate 
				SELECT id, 0 
					FROM worker 
					WHERE bossFk = vBossId;
					
			UPDATE tmp.subordinate 
				SET isChecked = 1
				WHERE workerFk = vBossId;
		END LOOP;

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

	SELECT * FROM
		(
		SELECT supplierFk, itemFk, longName, supplier, entryFk, landed, `out`, `in`, almacen
			FROM supplierPackaging
			WHERE supplierFk = vSupplierFk
			AND landed >= vFromDated
			
		UNION ALL
			
		SELECT vSupplierFk, itemFk, longName, supplier, 'anterior', vFromDated, sum(`out`), sum(`in`), NULL
			FROM supplierPackaging
			WHERE supplierFk = vSupplierFk
			AND landed < vFromDated
            GROUP BY itemFk
		) sub
	ORDER BY itemFk, landed;
        
	


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `taxGetRateskk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `taxGetRateskk`(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 `ticketBoxesView` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketBoxesView`(IN vTicketFk INT)
BEGIN
  	
	SELECT  s.id, 
			s.itemFk, 
            s.concept, 
            floor(s.quantity / b.packing) as Cajas, 
            b.packing, 
            s.isPicked, 
            i.size
		FROM ticket t 
			JOIN sale s ON s.ticketFk = t.id
			JOIN item i ON i.id = s.itemFk
			JOIN cache.last_buy lb on lb.warehouse_id = t.warehouseFk AND lb.item_id = s.itemFk
			JOIN buy b on b.id = lb.buy_id
			JOIN packaging p on p.id = b.packageFk
		WHERE s.quantity >= b.packing
			AND t.id = vTicketFk
			AND p.isBox
				GROUP BY s.itemFk;

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

	DECLARE vDateStart DATETIME DEFAULT DATE(vDate);
	DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate);
    
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketBuiltTime;

	CREATE TEMPORARY TABLE tmp.ticketBuiltTime
		ENGINE = MEMORY
	SELECT t.id as ticketFk ,t.shipped, IFNULL(builtTime, vDateEnd) as builtTime
		FROM
        vn.ticket t
        LEFT JOIN
        (
        SELECT ticketFk, builtTime
			FROM
			(
			SELECT 
				Id_Ticket as ticketFk,
				odbc_date as builtTime
				FROM
					vncontrol.inter
					WHERE odbc_date BETWEEN vDateStart AND vDateEnd
				ORDER BY Id_Ticket, odbc_date DESC
			) sub 
            GROUP BY ticketFk
		) sub2 ON sub2.ticketFk = t.id
        WHERE t.shipped BETWEEN vDate AND util.dayEnd(vDate)
			AND t.clientFk NOT IN (50,400,200)
            AND t.companyFk = 442
		
		;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketCalculate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculate`(
    vDate DATE,
    vAddress INT,
    vAgencyMode INT)
proc: BEGIN
/**
 * Calcula los articulos disponibles y sus precios
 * 
 * @param vDate Fecha de recepcion de mercancia
 * @param vAddress Id del consignatario
 * @param vAgencyMode Id de la agencia
 * @return tmp.ticketCalculateItem, tmp.ticketComponentPrice
 **/
 
    DECLARE vAvailableCalc INT;
    DECLARE vShipment DATE;
    DECLARE vAgencyId INT;
    DECLARE vClient INT;
    DECLARE vWarehouseFk SMALLINT;
    DECLARE vDone BOOL;
    DECLARE cTravelTree CURSOR FOR
        SELECT warehouseFk, shipped FROM tmp.agencyHourGetShipped;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
    
    -- Establece los almacenes y las fechas que van a entrar al disponible

    SELECT agencyFk INTO vAgencyId
        FROM agencyMode WHERE id = vAgencyMode;

    SELECT clientFk INTO vClient
        FROM address WHERE id = vAddress;

    CALL vn.agencyHourGetShipped(vDate, vAddress, vAgencyId);

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
    CREATE TEMPORARY TABLE tmp.ticketLot(
      `warehouseFk` smallint(5) unsigned NOT NULL,
      `itemFk` int(11) NOT NULL,
      `available` double DEFAULT NULL,
      `buyFk` int(11) DEFAULT NULL,
      `fix` tinyint(3) unsigned DEFAULT '0',
      KEY `itemFk` (`itemFk`),
      KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH
    ) ENGINE=MEMORY DEFAULT CHARSET=utf8;

    OPEN cTravelTree;

    l: LOOP
        SET vDone = FALSE;
        FETCH cTravelTree INTO  vWarehouseFk, vShipment;

        IF vDone THEN
            LEAVE l;
        END IF;

        CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipment);
        CALL buyUltimate (vWarehouseFk, vShipment);

        INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk)
			SELECT
					vWarehouseFk,
					i.item_id,
					IFNULL(i.available, 0),
					bu.buyFk
				FROM `cache`.available i
					JOIN tmp.item br ON br.itemFk = i.item_id
					LEFT JOIN item it ON it.id = i.item_id
					LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id
				WHERE i.calc_id = vAvailableCalc
					AND it.id != 100    
					AND i.available > 0;
        
        DROP TEMPORARY TABLE tmp.buyUltimate;
    END LOOP;

    CLOSE cTravelTree;

    CALL vn.ticketComponentCalculate(vAddress, vAgencyMode);

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem;
    CREATE TEMPORARY TABLE tmp.ticketCalculateItem
    ENGINE = MEMORY
		SELECT 
				b.itemFk, 
				SUM(b.available) available,
				p.name producer, 
				i.name item, 
				i.size size,  
				i.stems,  
				i.category, 
				i.inkFk,  
				i.image,
				o.code origin, bl.price
			FROM tmp.ticketLot b
				JOIN item i ON b.itemFk = i.id
				LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible
				JOIN origin o ON o.id = i.originFk
				JOIN (
					SELECT MIN(price) price, itemFk
						FROM tmp.ticketComponentPrice
						GROUP BY itemFk
				) bl ON bl.itemFk = b.itemFk
			GROUP BY b.itemFk;
        
	DROP TEMPORARY TABLE 
		tmp.ticketComponent,
		tmp.ticketLot;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketCalculateClon` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateClon`(IN vTicketNew INT, vTicketOld INT)
BEGIN
	/*
	* @vTicketNew id del nuevo ticket clonado
    * @vTicketOld id ticket original, a partir del qual se clonara el nuevo
	* Este procedimiento "rebioniza" una linea, eliminando los componentes existentes e insertandolos de nuevo
	*/
	DECLARE vShipped DATE;
	DECLARE vClient INT;
	DECLARE vWarehouse SMALLINT;
    DECLARE vAgencyMode INT;
    DECLARE vAddress INT;
	DECLARE vLanded DATE;
    DECLARE vAgency INT;

    REPLACE INTO orderTicket(orderFk,ticketFk)
		SELECT orderFk, vTicketNew 
			FROM orderTicket 
            WHERE ticketFk = vTicketOld;
    	
	SELECT t.clientFk , t.warehouseFk, date(t.shipped), t.addressFk, t.agencyModeFk, t.landed, a.agencyFk
		INTO vClient, vWarehouse, vShipped, vAddress, vAgencyMode, vLanded, vAgency
    FROM vn.agencyMode a
		JOIN vn.ticket t ON t.agencyModeFk = a.id
    WHERE t.id = vTicketNew;
    
	DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetShipped;
	CREATE TEMPORARY TABLE tmp.agencyHourGetShipped ENGINE = MEMORY
		SELECT vWarehouse warehouseFk, vShipped shipped, vLanded landed;
    
    CALL buyUltimate(vWarehouse, vShipped);  -- rellena la tabla tmp.buyUltimate con la ultima compra
    
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
    CREATE TEMPORARY TABLE tmp.ticketLot 
	SELECT vWarehouse warehouseFk,NULL available,s.itemFk, bu.buyFk
		FROM sale s
			LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
		WHERE s.ticketFk = vTicketOld GROUP BY s.itemFk;
                
	CALL ticketComponentCalculate(vAddress,vAgencyMode);
    
    -- Bionizamos lineas con Preu = 0
    DROP TEMPORARY TABLE IF EXISTS tmp.sale;
	CREATE TEMPORARY TABLE tmp.sale
				(PRIMARY KEY (saleFk)) ENGINE = MEMORY
			SELECT s.id saleFk, vWarehouse warehouseFk 
				FROM sale s
					JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk =  vTicketNew AND s.price = 0;
                
	CALL ticketComponentUpdateSale(1);
    
    -- Bionizamos lineas con Preu > 0
	DROP TEMPORARY TABLE IF EXISTS tmp.sale;
	CREATE TEMPORARY TABLE tmp.sale
				(PRIMARY KEY (saleFk)) ENGINE = MEMORY
			SELECT s.id saleFk, vWarehouse warehouseFk 
				FROM sale s 
					JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk =  vTicketNew
                    AND s.price > 0;
                
	CALL ticketComponentUpdateSale(6);

	IF vLanded IS NULL THEN
		CALL agencyHourGetLanded(vShipped, vAddress, vAgency,vWarehouse);
        
        UPDATE ticket t
				JOIN tmp.agencyHourGetLanded ah ON t.warehouseFk = ah.warehouseFk 
			SET t.landed = ah.landed 
			WHERE t.id = vTicketNew;
    END IF;
	
	-- Log
    CALL `logAdd`(vTicketNew, 'update', ' ticket' , 'Bioniza Ticket');

	-- Limpieza
	DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate;
    DROP TEMPORARY TABLE IF EXISTS tmp.sale;
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
     DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetShipped;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketCalculateSale` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSale`(IN vSale BIGINT)
proc: BEGIN


	DECLARE vShipped DATE; 
	DECLARE vWarehouse SMALLINT;
    DECLARE vAgencyMode INT;
    DECLARE vAddress INT;
    DECLARE vTicket BIGINT;
    DECLARE vItem BIGINT;
    DECLARE vLanded DATE; 
    DECLARE vTicketFree BOOLEAN DEFAULT TRUE;
    
	SELECT FALSE
			INTO vTicketFree
		FROM vn.ticket t
			JOIN vn.sale s ON s.ticketFk = t.id
			LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id
		WHERE s.id = vSale
			AND (t.refFk != "" OR (ts.alertLevel > 0 AND s.price != 0))
		LIMIT 1;
        
    SELECT ticketFk, itemFk 
			INTO vTicket, vItem 
		FROM sale 
        WHERE id = vSale;
    	
	SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.agencyModeFk, t.landed
			INTO vWarehouse, vShipped, vAddress, vAgencyMode, vLanded
		FROM agencyMode a 
			JOIN ticket t ON t.agencyModeFk = a.id
		WHERE t.id = vTicket;
	
	DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetShipped;
	CREATE TEMPORARY TABLE tmp.agencyHourGetShipped	ENGINE = MEMORY
		SELECT vWarehouse warehouseFk, vShipped shipped, vLanded landed;
    
    CALL buyUltimate (vWarehouse, vShipped);  
    
	DELETE FROM tmp.buyUltimate WHERE itemFk != vItem;
    
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
    CREATE TEMPORARY TABLE tmp.ticketLot 
		SELECT vWarehouse warehouseFk, NULL available, vItem itemFk, buyFk
				FROM tmp.buyUltimate
				WHERE itemFk = vItem;
                
	CALL ticketComponentCalculate(vAddress, vAgencyMode);

    DROP TEMPORARY TABLE IF EXISTS tmp.sale;
	CREATE TEMPORARY TABLE tmp.sale
					(PRIMARY KEY (saleFk)) ENGINE = MEMORY
		SELECT vSale saleFk,vWarehouse warehouseFk;
                
	CALL ticketComponentUpdateSale(IF(vTicketFree,1,6)); 

	
	INSERT INTO vn.ticketLog (originFk, userFk, `action`, description)
		VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale));

	
	DROP TEMPORARY TABLE tmp.buyUltimate;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
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 vWithPackage 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;

	DROP TEMPORARY TABLE IF EXISTS  tmp.ticketClosure2;
	CREATE TEMPORARY TABLE tmp.ticketClosure2
			SELECT ticketFk FROM tmp.ticketClosure;
	INSERT INTO tmp.ticketClosure 
			SELECT id FROM stowaway s 
				JOIN tmp.ticketClosure2 tc ON s.shipFk = tc.ticketFk;
	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,
				w.isManaged
			INTO vClientFk,
				vIsTaxDataChecked,
				vCompanyFk, 
				vShipped,
				vIsUeeMember,
				vWithPackage
			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
				JOIN warehouse w ON w.id = t.warehouseFk
			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 packaging p ON p.itemFk = e.itemFk
				WHERE e.ticketFk = vTicketFk AND p.isPackageReturnable
					AND vWithPackage
				GROUP BY p.itemFk);

		-- No retornables o no catalogados
		INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed) 
			(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 packaging 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;

	DROP TEMPORARY TABLE IF EXISTS  tmp.ticketClosure2;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 `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`( vRouteFk INT)
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.routeFk = vRouteFk
			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 `ticketComponentCalculate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentCalculate`(IN `vAddressFk` INT, IN `vAgencyModeFk` INT)
proc: BEGIN
/**
 * Calcula los componentes de un ticket
 *
 * @param vAddressFk Id del consignatario
 * @param vAgencyModeFk Id del modo de agencia
 * @return tmp.ticketComponent, tmp.ticketComponentPrice
 */
 
	DECLARE vClientFk INT;
    DECLARE vGeneralInflationCoefficient INT DEFAULT 1;
    DECLARE vMinimumDensityWeight INT DEFAULT 167;
	DECLARE vBoxFreightItem INT DEFAULT 71;
    DECLARE vBoxVolume BIGINT; -- DEFAULT 138000;
	DECLARE vSpecialPriceComponent INT DEFAULT 10;
	DECLARE vExtraFreightComponent INT DEFAULT 14;
	DECLARE vDeliveryComponent INT DEFAULT 15;
	DECLARE vRecoveryComponent INT DEFAULT 17;
	DECLARE vSellByPacketComponent INT DEFAULT 22;
	DECLARE vBuyValueComponent INT DEFAULT 28;
	DECLARE vMarginComponent INT DEFAULT 29;
	DECLARE vDiscountLastItemComponent INT DEFAULT 32;
	DECLARE vExtraBaggedComponent INT DEFAULT 38;
	DECLARE vManaAutoComponent INT DEFAULT 39;
	DECLARE vFreightBonusComponent INT DEFAULT 41;
    
    
    SELECT volume INTO vBoxVolume
		FROM vn.packaging
        WHERE id = '94';
        
    SELECT clientFk INTO vClientFK 
		FROM address 
        WHERE id = vAddressFk;
    
    SET @rate2 := 0;
    SET @rate3 := 0;

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate;
	CREATE TEMPORARY TABLE tmp.ticketComponentCalculate
	(PRIMARY KEY (itemFk, warehouseFk))
	ENGINE = MEMORY
		SELECT 
			tl.itemFk, tl.warehouseFk, tl.available,
			IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2,
			IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3,
            IFNULL(pf.rate3, 0) AS minPrice,
			IFNULL(pf.packing, b.packing) packing,
			IFNULL(pf.`grouping`, b.`grouping`) `grouping`,
			ABS(IFNULL(pf.box, b.groupingMode)) groupingMode,
            tl.buyFk, i.typeFk
        FROM tmp.ticketLot tl
		JOIN buy b ON b.id = tl.buyFk
		JOIN item i ON i.id = tl.itemFk
        JOIN itemType it ON it.id = i.typeFk
        LEFT JOIN itemCategory ic ON ic.id = it.categoryFk
		LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk
		LEFT JOIN (
			SELECT * FROM (
				SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, aho.warehouseFk
					FROM priceFixed pf
					JOIN tmp.agencyHourGetShipped aho ON pf.warehouseFk = aho.warehouseFk OR pf.warehouseFk = 0 
						WHERE aho.shipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC
			) tpf
			GROUP BY tpf.itemFk, tpf.warehouseFk
		) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk
        WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.display <> 0;
        
    
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent;
    CREATE TEMPORARY TABLE tmp.ticketComponent (
		`warehouseFk` INT UNSIGNED NOT NULL,
		`itemFk` INT NOT NULL,
		`componentFk` INT UNSIGNED NOT NULL,
		`cost` DECIMAL(10,4) NOT NULL,
		INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC),
		UNIQUE INDEX `itemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC));


	
	INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost)
		SELECT 
				tcc.warehouseFk, 
				tcc.itemFk, 
				vBuyValueComponent, 
				b.buyingValue + b.freightValue + b.packageValue + b.comissionValue
			FROM tmp.ticketComponentCalculate tcc 
				JOIN buy b ON b.id = tcc.buyFk;
                
	INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost)
		SELECT 
				tcc.warehouseFk, 
				tcc.itemFk, 
				vMarginComponent, 
				tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue
			FROM tmp.ticketComponentCalculate tcc 
				JOIN buy b ON b.id = tcc.buyFk;

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase;
	CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY
		SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk
			FROM tmp.ticketComponent tc
			GROUP BY tc.itemFk, warehouseFk;

	INSERT INTO tmp.ticketComponent
		SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.recobro, 0.25), 3)
			FROM tmp.ticketComponentBase tcb
			JOIN bi.claims_ratio cr ON cr.Id_Cliente = vClientFk
				WHERE cr.recobro > 0.009;
            
    INSERT INTO tmp.ticketComponent
		SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + prices_modifier_rate), 3) as manaAuto
			FROM tmp.ticketComponentBase tcb
				JOIN `client` c on c.id = vClientFk
				JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador 
			WHERE ms.prices_modifier_activated
			HAVING manaAuto <> 0;
	
	INSERT INTO tmp.ticketComponent
		SELECT 
				tcb.warehouseFk, 
                tcb.itemFk, 
                cr.id, 
                GREATEST(IFNULL(ROUND(tcb.base * cr.tax, 4), 0), tcc.minPrice - tcc.rate3)
			FROM tmp.ticketComponentBase tcb
				JOIN componentRate cr
				JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk 
				LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk
			WHERE cr.id = vDiscountLastItemComponent AND cr.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL;
	
	INSERT INTO tmp.ticketComponent
		SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3 
			FROM tmp.ticketComponentCalculate tcc
				JOIN buy b ON b.id = tcc.buyFk
			LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk
		WHERE sp.value IS NULL;
 
	INSERT INTO tmp.ticketComponent
		SELECT 
				tcc.warehouseFK, 
				tcc.itemFk,
				vDeliveryComponent, 
				vGeneralInflationCoefficient
				* ROUND((
					i.compression
					* r.cm3 
					* IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1)
					* IFNULL(amz.price
					* amz.inflation, 50)) / vBoxVolume, 4
				) cost
		FROM tmp.ticketComponentCalculate tcc
			JOIN item i ON i.id = tcc.itemFk
			JOIN agencyMode am ON am.id = vAgencyModeFk
			JOIN `address` a ON a.id = vAddressFk
			JOIN agencyProvince ap ON ap.agencyFk = am.agencyFk 
				AND ap.warehouseFk = tcc.warehouseFk AND ap.provinceFk = a.provinceFk
			JOIN agencyModeZone amz ON amz.agencyModeFk = vAgencyModeFk 
				AND amz.zone = ap.zone AND amz.itemFk = 71 AND amz.warehouseFk = tcc.warehouseFk
			LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk 
				AND r.Id_Article = tcc.itemFk
			HAVING cost <> 0;

	INSERT INTO tmp.ticketComponent
		SELECT 
				tcc.warehouseFk, 
				tcc.itemFk, 
				vFreightBonusComponent,
				vGeneralInflationCoefficient
				* ROUND(
					r.cm3 
					* IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1)
					* awb.bonus 
					* amz.inflation / vBoxVolume, 4
				) cost
		FROM tmp.ticketComponentCalculate tcc
			JOIN item i ON i.id = tcc.itemFk
			JOIN agencyMode am ON am.id = vAgencyModeFk
			JOIN `address` a ON a.id = vAddressFk
			JOIN agencyProvince ap ON ap.agencyFk = a.id 
				AND ap.warehouseFk = tcc.warehouseFk AND ap.provinceFk = a.provinceFk
			JOIN agencyModeZone amz ON amz.agencyModeFk = vAgencyModeFk 
				AND amz.zone = ap.zone AND amz.itemFk = vBoxFreightItem AND amz.warehouseFk = tcc.warehouseFk
			JOIN agencyWeekDayBonus awb ON awb.warehouseFk = amz.warehouseFk AND awb.zone = amz.zone AND am.id = awb.agencyFk
			LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk 
				AND r.Id_Article = tcc.itemFk
			JOIN tmp.agencyHourGetShipped aho ON aho.warehouseFk = awb.warehouseFk 
				AND WEEKDAY(aho.landed) = awb.weekDay
		HAVING cost <> 0
		LIMIT 1;

    IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN
		INSERT INTO tmp.ticketComponent
			SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost
				FROM tmp.ticketComponentCalculate tcc
					JOIN vn.addressForPackaging ap
				WHERE ap.addressFk = vAddressFk;
    END IF;
    
	INSERT INTO tmp.ticketComponent
		SELECT tcb.warehouseFk, tcb.itemFk, vExtraFreightComponent, tcb.base * (IFNULL(pe.percentage,pp.percentage)/100)
			FROM tmp.ticketComponentBase tcb
				JOIN tmp.agencyHourGetShipped aho ON aho.warehouseFk = tcb.warehouseFk
				LEFT JOIN preparationPercentage pp ON pp.weekDay = WEEKDAY(aho.shipped) 
					AND tcb.warehouseFk = IFNULL(pp.warehouseFk, tcb.warehouseFk)
				LEFT JOIN preparationException pe ON pe.exceptionDay = aho.shipped 
					AND tcb.warehouseFk = IFNULL(pe.warehouseFk, tcb.warehouseFk)
			WHERE IFNULL(pe.percentage, pp.percentage);
	
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy;
    CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY
		SELECT * FROM tmp.ticketComponent;
        
	INSERT INTO tmp.ticketComponent
		SELECT 
				tcc.warehouseFk, 
				tcc.itemFk, 
				vSpecialPriceComponent, 
				sp.value - SUM(tcc.cost) sumCost
			FROM tmp.ticketComponentCopy tcc
				JOIN componentRate cr ON cr.id = tcc.componentFk
				JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk
			WHERE cr.classRate IS NULL
			GROUP BY tcc.itemFk, tcc.warehouseFk
			HAVING ABS(sumCost) > 0.001;
	
	DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum;
	CREATE TEMPORARY TABLE tmp.ticketComponentSum
		(INDEX (itemFk, warehouseFk))
		ENGINE = MEMORY
		SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, cr.classRate
			FROM tmp.ticketComponent tc
				JOIN componentRate cr ON cr.id = tc.componentFk
			GROUP BY tc.itemFk, tc.warehouseFk, cr.classRate;

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate;
	CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY
		SELECT 
				tcc.warehouseFk,  
				tcc.itemFk, 
				1 rate,
				IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, 
				SUM(tcs.sumCost) price
			FROM tmp.ticketComponentCalculate tcc
				JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk 
					AND tcs.warehouseFk = tcc.warehouseFk
			WHERE IFNULL(tcs.classRate, 1) = 1 
				AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0)
			GROUP BY tcs.warehouseFk, tcs.itemFk;

	INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price)
        SELECT 
				tcc.warehouseFk, 
				tcc.itemFk, 
				2 rate, 
				tcc.packing `grouping`, 
				SUM(tcs.sumCost) price
			FROM tmp.ticketComponentCalculate tcc
				JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk 
					AND tcs.warehouseFk = tcc.warehouseFk
			WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 
				AND tcc.packing > 0 AND tcc.available >= tcc.packing)
			GROUP BY tcs.warehouseFk, tcs.itemFk;

	INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price)
		 SELECT 				
		 		tcc.warehouseFk, 
				tcc.itemFk, 
				3 rate, 
				tcc.available `grouping`, 
				SUM(tcs.sumCost) price
			FROM tmp.ticketComponentCalculate tcc
				JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk 
					AND tcs.warehouseFk = tcc.warehouseFk
			WHERE IFNULL(tcs.classRate, 3) = 3 
			GROUP BY tcs.warehouseFk, tcs.itemFk;
        
	DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice;
	CREATE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY 
		SELECT * FROM (
			SELECT * FROM tmp.ticketComponentRate ORDER BY price
		) t
		GROUP BY itemFk, warehouseFk, `grouping`;

    DROP TEMPORARY TABLE 
		tmp.ticketComponentCalculate,
		tmp.ticketComponentSum,
		tmp.ticketComponentBase,
		tmp.ticketComponentRate,
    	tmp.ticketComponentCopy;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentCalculateKK` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentCalculateKK`(IN `vAddressFk` INT, IN `vAgencyModeFk` INT)
proc: BEGIN
/**
 * Calcula los componentes de un ticket
 *
 * @param vAddressFk Id del consignatario
 * @param vAgencyModeFk Id del modo de agencia
 * @return tmp.ticketComponent, tmp.ticketComponentPrice
 */
	DECLARE vClientFk INT;
    DECLARE vGeneralInflationCoefficient INT DEFAULT 1;
    DECLARE vMinimumDensityWeight INT DEFAULT 167;
	DECLARE vBoxFreightItem INT DEFAULT 71;
    DECLARE vBoxVolume BIGINT; -- DEFAULT 138000;
	DECLARE vSpecialPriceComponent INT DEFAULT 10;
	DECLARE vExtraFreightComponent INT DEFAULT 14;
	DECLARE vDeliveryComponent INT DEFAULT 15;
	DECLARE vRecoveryComponent INT DEFAULT 17;
	DECLARE vSellByPacketComponent INT DEFAULT 22;
	DECLARE vBuyValueComponent INT DEFAULT 28;
	DECLARE vMarginComponent INT DEFAULT 29;
	DECLARE vDiscountLastItemComponent INT DEFAULT 32;
	DECLARE vExtraBaggedComponent INT DEFAULT 38;
	DECLARE vManaAutoComponent INT DEFAULT 39;
	DECLARE vFreightBonusComponent INT DEFAULT 41;
    
    
    SELECT volume INTO vBoxVolume
		FROM vn.packaging
        WHERE id = '94';
        
    SELECT clientFk INTO vClientFK 
		FROM address 
        WHERE id = vAddressFk;
    
    SET @rate2 := 0;
    SET @rate3 := 0;

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate;
	CREATE TEMPORARY TABLE tmp.ticketComponentCalculate
	(PRIMARY KEY (itemFk, warehouseFk))
	ENGINE = MEMORY
		SELECT 
			tl.itemFk, tl.warehouseFk, tl.available,
			IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2,
			IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3,
            IFNULL(pf.rate3, 0) AS minPrice,
			IFNULL(pf.packing, b.packing) packing,
			IFNULL(pf.`grouping`, b.`grouping`) `grouping`,
			ABS(IFNULL(pf.box, b.groupingMode)) groupingMode,
            tl.buyFk, i.typeFk
        FROM tmp.ticketLot tl
		JOIN buy b ON b.id = tl.buyFk
		JOIN item i ON i.id = tl.itemFk
        JOIN itemType it ON it.id = i.typeFk
        LEFT JOIN itemCategory ic ON ic.id = it.categoryFk
		LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk
		LEFT JOIN (
			SELECT * FROM (
				SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, aho.warehouseFk
					FROM priceFixed pf
					JOIN tmp.agencyHourGetShipped aho ON pf.warehouseFk = aho.warehouseFk OR pf.warehouseFk = 0 
						WHERE aho.shipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC
			) tpf
			GROUP BY tpf.itemFk, tpf.warehouseFk
		) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk
        WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.display <> 0;
        
    
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent;
    CREATE TEMPORARY TABLE tmp.ticketComponent (
		`warehouseFk` INT UNSIGNED NOT NULL,
		`itemFk` INT NOT NULL,
		`componentFk` INT UNSIGNED NOT NULL,
		`cost` DECIMAL(10,4) NOT NULL,
		INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC),
		UNIQUE INDEX `itemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC));


	
	INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost)
		SELECT 
				tcc.warehouseFk, 
				tcc.itemFk, 
				vBuyValueComponent, 
				b.buyingValue + b.freightValue + b.packageValue + b.comissionValue
			FROM tmp.ticketComponentCalculate tcc 
				JOIN buy b ON b.id = tcc.buyFk;
                
	INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost)
		SELECT 
				tcc.warehouseFk, 
				tcc.itemFk, 
				vMarginComponent, 
				tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue
			FROM tmp.ticketComponentCalculate tcc 
				JOIN buy b ON b.id = tcc.buyFk;

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase;
	CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY
		SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk
			FROM tmp.ticketComponent tc
			GROUP BY tc.itemFk, warehouseFk;

	INSERT INTO tmp.ticketComponent
		SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.recobro, 0.25), 3)
			FROM tmp.ticketComponentBase tcb
			JOIN bi.claims_ratio cr ON cr.Id_Cliente = vClientFk
				WHERE cr.recobro > 0.009;
            
    INSERT INTO tmp.ticketComponent
		SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + prices_modifier_rate), 3) as manaAuto
			FROM tmp.ticketComponentBase tcb
				JOIN `client` c on c.id = vClientFk
				JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador 
			WHERE ms.prices_modifier_activated
			HAVING manaAuto <> 0;
	
	INSERT INTO tmp.ticketComponent
		SELECT 
				tcb.warehouseFk, 
                tcb.itemFk, 
                cr.id, 
                GREATEST(IFNULL(ROUND(tcb.base * cr.tax, 4), 0), tcc.minPrice - tcc.rate3)
			FROM tmp.ticketComponentBase tcb
				JOIN componentRate cr
				JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk 
				LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk
			WHERE cr.id = vDiscountLastItemComponent AND cr.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL;
	
	INSERT INTO tmp.ticketComponent
		SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3 
			FROM tmp.ticketComponentCalculate tcc
				JOIN buy b ON b.id = tcc.buyFk
			LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk
		WHERE sp.value IS NULL;
 
	INSERT INTO tmp.ticketComponent
		SELECT 
				tcc.warehouseFK, 
				tcc.itemFk,
				vDeliveryComponent, 
				vGeneralInflationCoefficient
				* ROUND((
					i.compression
					* r.cm3 
					* IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1)
					* IFNULL(amz.price
					* amz.inflation, 50)) / vBoxVolume, 4
				) cost
		FROM tmp.ticketComponentCalculate tcc
			JOIN item i ON i.id = tcc.itemFk
			JOIN agencyMode am ON am.id = vAgencyModeFk
			JOIN `address` a ON a.id = vAddressFk
			JOIN agencyProvince ap ON ap.agencyFk = am.agencyFk 
				AND ap.warehouseFk = tcc.warehouseFk AND ap.provinceFk = a.provinceFk
			JOIN agencyModeZone amz ON amz.agencyModeFk = vAgencyModeFk 
				AND amz.zone = ap.zone AND amz.itemFk = 71 AND amz.warehouseFk = tcc.warehouseFk
			LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk 
				AND r.Id_Article = tcc.itemFk
			HAVING cost <> 0;

	INSERT INTO tmp.ticketComponent
		SELECT 
				tcc.warehouseFk, 
				tcc.itemFk, 
				vFreightBonusComponent,
				vGeneralInflationCoefficient
				* ROUND(
					r.cm3 
					* IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1)
					* awb.bonus 
					* amz.inflation / vBoxVolume, 4
				) cost
		FROM tmp.ticketComponentCalculate tcc
			JOIN item i ON i.id = tcc.itemFk
			JOIN agencyMode am ON am.id = vAgencyModeFk
			JOIN `address` a ON a.id = vAddressFk
			JOIN agencyProvince ap ON ap.agencyFk = a.id 
				AND ap.warehouseFk = tcc.warehouseFk AND ap.provinceFk = a.provinceFk
			JOIN agencyModeZone amz ON amz.agencyModeFk = vAgencyModeFk 
				AND amz.zone = ap.zone AND amz.itemFk = vBoxFreightItem AND amz.warehouseFk = tcc.warehouseFk
			JOIN agencyWeekDayBonus awb ON awb.warehouseFk = amz.warehouseFk AND awb.zone = amz.zone AND am.id = awb.agencyFk
			LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk 
				AND r.Id_Article = tcc.itemFk
			JOIN tmp.agencyHourGetShipped aho ON aho.warehouseFk = awb.warehouseFk 
				AND WEEKDAY(aho.landed) = awb.weekDay
		HAVING cost <> 0
		LIMIT 1;

    IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN
		INSERT INTO tmp.ticketComponent
			SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost
				FROM tmp.ticketComponentCalculate tcc
					JOIN vn.addressForPackaging ap
				WHERE ap.addressFk = vAddressFk;
    END IF;
    
	INSERT INTO tmp.ticketComponent
		SELECT tcb.warehouseFk, tcb.itemFk, vExtraFreightComponent, tcb.base * (IFNULL(pe.percentage,pp.percentage)/100)
			FROM tmp.ticketComponentBase tcb
				JOIN tmp.agencyHourGetShipped aho ON aho.warehouseFk = tcb.warehouseFk
				LEFT JOIN preparationPercentage pp ON pp.weekDay = WEEKDAY(aho.shipped) 
					AND tcb.warehouseFk = IFNULL(pp.warehouseFk, tcb.warehouseFk)
				LEFT JOIN preparationException pe ON pe.exceptionDay = aho.shipped 
					AND tcb.warehouseFk = IFNULL(pe.warehouseFk, tcb.warehouseFk)
			WHERE IFNULL(pe.percentage, pp.percentage);
	
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy;
    CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY
		SELECT * FROM tmp.ticketComponent;
        
	INSERT INTO tmp.ticketComponent
		SELECT 
				tcc.warehouseFk, 
				tcc.itemFk, 
				vSpecialPriceComponent, 
				sp.value - SUM(tcc.cost) sumCost
			FROM tmp.ticketComponentCopy tcc
				JOIN componentRate cr ON cr.id = tcc.componentFk
				JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk
			WHERE cr.classRate IS NULL
			GROUP BY tcc.itemFk, tcc.warehouseFk
			HAVING ABS(sumCost) > 0.001;
	
	DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum;
	CREATE TEMPORARY TABLE tmp.ticketComponentSum
		(INDEX (itemFk, warehouseFk))
		ENGINE = MEMORY
		SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, cr.classRate
			FROM tmp.ticketComponent tc
				JOIN componentRate cr ON cr.id = tc.componentFk
			GROUP BY tc.itemFk, tc.warehouseFk, cr.classRate;

		select 1;
		
		
	DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate;
	CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY
		SELECT 
				tcc.warehouseFk,  
				tcc.itemFk, 
				1 rate,
				IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, 
				SUM(tcs.sumCost) price
			FROM tmp.ticketComponentCalculate tcc
				JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk 
					AND tcs.warehouseFk = tcc.warehouseFk
			WHERE IFNULL(tcs.classRate, 1) = 1 
				AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0)
			GROUP BY tcs.warehouseFk, tcs.itemFk;

	INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price)
        SELECT 
				tcc.warehouseFk, 
				tcc.itemFk, 
				2 rate, 
				tcc.packing `grouping`, 
				SUM(tcs.sumCost) price
			FROM tmp.ticketComponentCalculate tcc
				JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk 
					AND tcs.warehouseFk = tcc.warehouseFk
			WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 
				AND tcc.packing > 0 AND tcc.available >= tcc.packing)
			GROUP BY tcs.warehouseFk, tcs.itemFk;

	INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price)
		 SELECT 				
		 		tcc.warehouseFk, 
				tcc.itemFk, 
				3 rate, 
				tcc.available `grouping`, 
				SUM(tcs.sumCost) price
			FROM tmp.ticketComponentCalculate tcc
				JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk 
					AND tcs.warehouseFk = tcc.warehouseFk
			WHERE IFNULL(tcs.classRate, 3) = 3 
			GROUP BY tcs.warehouseFk, tcs.itemFk;
        
	DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice;

select 2;

	CREATE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY 
		SELECT * FROM (
			SELECT * FROM tmp.ticketComponentRate ORDER BY price
		) t
		GROUP BY itemFk, warehouseFk, `grouping`;

    DROP TEMPORARY TABLE 
		tmp.ticketComponentCalculate,
		tmp.ticketComponentSum,
		tmp.ticketComponentBase,
		tmp.ticketComponentRate,
    	tmp.ticketComponentCopy;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentMakeUpdate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentMakeUpdate`(	
	vTicketFk INT,
    vClientFk INT,
	vAgencyModeFk INT,
	vAddressFk INT,
	vWarehouseFk TINYINT,
    vCompanyFk SMALLINT,
	vShipped DATETIME,
	vLanded DATE,
    vIsDeleted BOOLEAN,
    vHasToBeUnrouted BOOLEAN,
	vOption INT)
BEGIN

 
	CALL vn.ticketComponentPreview (vTicketFk, vLanded, vAddressFk, vAgencyModeFk, vWarehouseFk);
    CALL vn.ticketComponentUpdate (
		vTicketFk, 
        vClientFk,
        vAgencyModeFk, 
        vAddressFk, 
		vWarehouseFk,
        vCompanyFk,
        vShipped, 
        vLanded, 
        vIsDeleted, 
        vHasToBeUnrouted,
        vOption
	);

    DROP TEMPORARY TABLE 
        tmp.ticketComponent,
		tmp.ticketComponentPrice;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentPreview` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentPreview`(
	vTicketFk INT,
    vLanded DATE, 
    vAddressFk INT,
    vAgencyModeFk INT,
    vWarehouseFk SMALLINT)
BEGIN

 
	DECLARE vAgencyFk INT;  
	DECLARE vShipped DATE;
	DECLARE vBuyOrderItem INT DEFAULT 100;

    DECLARE vHasDataChanged BOOL DEFAULT FALSE;    
    DECLARE vHasAddressChanged BOOL;
    DECLARE vHasAgencyModeChanged BOOL DEFAULT FALSE;
    DECLARE vHasWarehouseChanged BOOL DEFAULT FALSE;
    
	DECLARE vAddressTypeRateFk INT DEFAULT NULL;
	DECLARE vAgencyModeTypeRateFk INT DEFAULT NULL;
    
    DECLARE vHasChangeAll BOOL DEFAULT FALSE;
  
	SELECT DATE(landed) <> vLanded, 
			addressFk <> vAddressFk, 
			agencyModeFk <> vAgencyModeFk,
            warehouseFk <> vWarehouseFk
		INTO
			vHasDataChanged,
            vHasAddressChanged,
            vHasAgencyModeChanged,
            vHasWarehouseChanged
		FROM vn.ticket t
        WHERE t.id = vTicketFk;

    IF vHasDataChanged OR vHasWarehouseChanged THEN
		SET vHasChangeAll = TRUE;
	END IF;
    
	IF vHasAddressChanged THEN
		SET vAddressTypeRateFk = 5;
    END IF;
    
	IF vHasAgencyModeChanged THEN
		SET vAgencyModeTypeRateFk = 6;
    END IF;
        
	SELECT agencyFk INTO vAgencyFk 
		FROM agencyMode 
        WHERE id = vAgencyModeFk;

	CALL agencyHourGetShipped(vLanded, vAddressFk, vAgencyFk);

	SELECT shipped INTO vShipped 
		FROM tmp.agencyHourGetShipped 
		WHERE warehouseFk = vWarehouseFk;
        
	CALL buyUltimate(vWarehouseFk, vShipped);
        
	DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
    CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY ( 
	SELECT 
			vWarehouseFk AS warehouseFk,
			NULL AS available,
			s.itemFk,
			bu.buyFk
		FROM sale s
			LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
		WHERE s.ticketFk = vTicketFk
			AND s.itemFk != vBuyOrderItem
		GROUP BY bu.warehouseFk, bu.itemFk);

	CALL ticketComponentCalculate(vAddressFk, vAgencyModeFk);



	
	REPLACE INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost)
		SELECT t.warehouseFk, s.itemFk, sc.componentFk, sc.value
			FROM saleComponent sc
				JOIN sale s ON s.id = sc.saleFk
				JOIN ticket t ON t.id = s.ticketFk
				JOIN componentRate cr ON cr.id = sc.componentFk
			WHERE s.ticketFk = vTicketFk 
				AND (cr.isRenewable = FALSE 
					OR 
					(NOT vHasChangeAll
						AND (NOT (cr.componentTypeRate <=> vAddressTypeRateFk
                        OR cr.componentTypeRate <=> vAgencyModeTypeRateFk))));

    SET @shipped = vShipped;

	DROP TEMPORARY TABLE 
		tmp.agencyHourGetShipped,
        tmp.buyUltimate,
		tmp.ticketLot;

	IF IFNULL(vShipped, CURDATE() - 1) < CURDATE() THEN
		CALL util.throw('NO_AGENCY_AVAILABLE');
    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 `ticketComponentPreviewKk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentPreviewKk`(
	vTicketFk INT,
    vLanded DATE, 
    vAddressFk INT,
    vAgencyModeFk INT,
    vWarehouseFk SMALLINT)
BEGIN
/**
 * Devuelve un listado previo de 
 * componentes para un ticket
 *
 * @param vTicketFk Id del ticket
 * @param vLanded Fecha de recepcion
 * @param vAddressFk Id del consignatario
 * @param vAgencyModeFk Id del modo de agencia
 * @param vWarehouseFk Id del almacén
 */
 
	DECLARE vAgencyFk INT;  
	DECLARE vShipped DATE;
	DECLARE vBuyOrderItem INT DEFAULT 100;

    DECLARE vHasDataChanged BOOL DEFAULT FALSE;    
    DECLARE vHasAddressChanged BOOL;
    DECLARE vHasAgencyModeChanged BOOL DEFAULT FALSE;
    DECLARE vHasWarehouseChanged BOOL DEFAULT FALSE;
    
	DECLARE vAddressTypeRateFk INT DEFAULT NULL;
	DECLARE vAgencyModeTypeRateFk INT DEFAULT NULL;
    
    DECLARE vHasChangeAll BOOL DEFAULT FALSE;
  
	SELECT DATE(landed) <> vLanded, 
			addressFk <> vAddressFk, 
			agencyModeFk <> vAgencyModeFk,
            warehouseFk <> vWarehouseFk
		INTO
			vHasDataChanged,
            vHasAddressChanged,
            vHasAgencyModeChanged,
            vHasWarehouseChanged
		FROM vn.ticket t
        WHERE t.id = vTicketFk;
/*SELECT vHasDataChanged,
            vHasAddressChanged,
            vHasAgencyModeChanged,
            vHasWarehouseChanged;
            */
    IF vHasDataChanged OR vHasWarehouseChanged THEN
		SET vHasChangeAll = TRUE;
	END IF;
    
	IF vHasAddressChanged THEN
		SET vAddressTypeRateFk = 5;
    END IF;
    
	IF vHasAgencyModeChanged THEN
		SET vAgencyModeTypeRateFk = 6;
    END IF;
        
	SELECT agencyFk INTO vAgencyFk 
		FROM agencyMode 
        WHERE id = vAgencyModeFk;
     select 1; 
	CALL agencyHourGetShipped(vLanded, vAddressFk, vAgencyFk);

	SELECT shipped INTO vShipped 
		FROM tmp.agencyHourGetShipped 
		WHERE warehouseFk = vWarehouseFK;
      select 2;  
	CALL buyUltimate(vWarehouseFK, vShipped);
        
	DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
    CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY ( 
	SELECT 
			vWarehouseFK AS warehouseFk,
			NULL AS available,
			s.itemFk,
			bu.buyFk
		FROM sale s
			LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
		WHERE s.ticketFk = vTicketFk
			AND s.itemFk != vBuyOrderItem
		GROUP BY bu.warehouseFk, bu.itemFk);
     select 3; 
	CALL ticketComponentCalculateKK(vAddressFk, vAgencyModeFk);
     select 4; 
/*SELECT *,vHasChangeAll,cr.isRenewable = FALSE,vHasChangeAll,
				NOT (cr.componentTypeRate <=> vAddressTypeRateFk),NOT (cr.componentTypeRate <=> vAgencyModeTypeRateFk),
                NOT (cr.componentTypeRate <=> vAddressTypeRateFk) OR NOT (cr.componentTypeRate <=> vAgencyModeTypeRateFk)
			FROM saleComponent sc
				JOIN sale s ON s.id = sc.saleFk
				JOIN ticket t ON t.id = s.ticketFk
				JOIN componentRate cr ON cr.id = sc.componentFk
			WHERE s.ticketFk = vTicketFk 
				AND (cr.isRenewable = FALSE 
					OR 
					(NOT vHasChangeAll
						AND (NOT (cr.componentTypeRate <=> vAddressTypeRateFk
                        OR cr.componentTypeRate <=> vAgencyModeTypeRateFk))));*/
/*SELECT * FROM tmp.ticketComponent;*/
	-- Inserta los componentes que NO seran modificados
	REPLACE INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost)
		SELECT t.warehouseFk, s.itemFk, sc.componentFk, sc.value
			FROM saleComponent sc
				JOIN sale s ON s.id = sc.saleFk
				JOIN ticket t ON t.id = s.ticketFk
				JOIN componentRate cr ON cr.id = sc.componentFk
			WHERE s.ticketFk = vTicketFk 
				AND (cr.isRenewable = FALSE 
					OR 
					(NOT vHasChangeAll
						AND (NOT (cr.componentTypeRate <=> vAddressTypeRateFk
                        OR cr.componentTypeRate <=> vAgencyModeTypeRateFk))));
/*SELECT * FROM tmp.ticketComponent;*/
    SET @shipped = vShipped;

	DROP TEMPORARY TABLE 
		tmp.agencyHourGetShipped,
        tmp.buyUltimate,
		tmp.ticketLot;

	IF IFNULL(vShipped, CURDATE() - 1) < CURDATE() THEN
		CALL util.throw('NO_AGENCY_AVAILABLE');
    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 `ticketComponentPriceDifference` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentPriceDifference`(
	vTicketFk INT,
    vLanded DATE, 
    vAddressFk INT,
    vAgencyModeFk INT,
    vWarehouseFk INT)
BEGIN
/**
 * Devuelve las diferencias de precio 
 * de los movimientos de un ticket.
 * 
 * @param vTicketFk Id del ticket
 * @param vLanded Fecha de recepcion
 * @param vAddressFk Id del consignatario
 * @param vAgencyModeFk Id del modo de agencia
 * @param vWarehouseFk Id del almacén
 */
	CALL vn.ticketComponentPreview(vTicketFk, vLanded, vAddressFk, vAgencyModeFk, vWarehouseFk);

	SELECT 	s.itemFk, 
			i.name, 
			i.size, 
			i.category, 
			IFNULL(s.quantity, 0) AS quantity, 
			IFNULL(s.price, 0) AS price, 
			ROUND(SUM(tc.cost), 2) AS newPrice,
			s.quantity * (s.price - ROUND(SUM(tc.cost), 2)) difference,
			s.id AS saleFk
		FROM sale s
			JOIN item i ON i.id = s.itemFk 
			JOIN ticket t ON t.id = s.ticketFk 
			LEFT JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk 
				AND tc.warehouseFk = t.warehouseFk
			LEFT JOIN saleComponent sc ON sc.saleFk = s.id 
				AND sc.componentFk = tc.componentFk
			LEFT JOIN componentRate cr ON cr.id = tc.componentFk 
		WHERE 
			t.id = vTicketFk 
			AND IF(sc.componentFk IS NULL 
				AND cr.classRate IS NOT NULL, FALSE, TRUE) 
		GROUP BY s.id ORDER BY s.id;

	DROP TEMPORARY TABLE 
        tmp.ticketComponent,
		tmp.ticketComponentPrice;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentPriceDifferenceKk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentPriceDifferenceKk`(
	vTicketFk INT,
    vLanded DATE, 
    vAddressFk INT,
    vAgencyModeFk INT,
    vWarehouseFk INT)
BEGIN
/**
 * Devuelve las diferencias de precio 
 * de los movimientos de un ticket.
 * 
 * @param vTicketFk Id del ticket
 * @param vLanded Fecha de recepcion
 * @param vAddressFk Id del consignatario
 * @param vAgencyModeFk Id del modo de agencia
 * @param vWarehouseFk Id del almacén
 */
	CALL vn.ticketComponentPreviewKk(vTicketFk, vLanded, vAddressFk, vAgencyModeFk, vWarehouseFk);
select 1;
	SELECT 	s.itemFk, 
			i.name, 
			i.size, 
			i.category, 
			IFNULL(s.quantity, 0) AS quantity, 
			IFNULL(s.price, 0) AS price, 
			ROUND(SUM(tc.cost), 2) AS newPrice,
			s.quantity * (s.price - ROUND(SUM(tc.cost), 2)) difference,
			s.id AS saleFk
		FROM sale s
			JOIN item i ON i.id = s.itemFk 
			JOIN ticket t ON t.id = s.ticketFk 
			LEFT JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk 
				AND tc.warehouseFk = t.warehouseFk
			LEFT JOIN saleComponent sc ON sc.saleFk = s.id 
				AND sc.componentFk = tc.componentFk
			LEFT JOIN componentRate cr ON cr.id = tc.componentFk 
		WHERE 
			t.id = vTicketFk 
			AND IF(sc.componentFk IS NULL 
				AND cr.classRate IS NOT NULL, FALSE, TRUE) 
		GROUP BY s.id ORDER BY s.id;

	DROP TEMPORARY TABLE 
        tmp.ticketComponent,
		tmp.ticketComponentPrice;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentUpdate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentUpdate`(
	 vTicketFk INT,
     vClientFk INT,
     vAgencyModeFk INT,
     vAddressFk INT,
     vWarehouseFk TINYINT,
     vCompanyFk SMALLINT,
     vShipped DATETIME,
     vLanded DATE,
     vIsDeleted BOOLEAN,
     vHasToBeUnrouted BOOLEAN,
     vOption INT)
BEGIN

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

	START TRANSACTION;
    
	UPDATE ticket t 
		SET 
			t.clientFk = vClientFk,
			t.agencyModeFk = vAgencyModeFk,
			t.addressFk = vAddressFk,
			t.warehouseFk = vWarehouseFk,
            t.companyFk = vCompanyFk,
			t.landed = vLanded,
			t.shipped = vShipped,
            t.isDeleted = vIsDeleted
		WHERE
			t.id = vTicketFk;
            
	IF vHasToBeUnrouted THEN
		UPDATE ticket t SET t.routeFk = NULL
			WHERE t.id = vTicketFk;
    END IF;
            
	IF vOption <> 8 THEN
		DROP TEMPORARY TABLE IF EXISTS tmp.sale;
		CREATE TEMPORARY TABLE tmp.sale
			(PRIMARY KEY (saleFk))
            ENGINE = MEMORY
			SELECT id AS saleFk, vWarehouseFk warehouseFk
				FROM sale s WHERE s.ticketFk = vTicketFk;

		CALL ticketComponentUpdateSale (vOption);

        DROP TEMPORARY TABLE tmp.sale;
	END IF;
	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 `ticketComponentUpdateSale` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentUpdateSale`(vOption INT)
BEGIN
/**
 * A partir de la tabla tmp.sale, crea los Movimientos_componentes
 * y modifica el campo Preu de la tabla Movimientos
 *
 * @param i_option integer tipo de actualizacion
 * @param table tmp.sale  tabla memory con el campo saleFk, warehouseFk
 **/
	DECLARE vComponentFk INT;
    DECLARE vRenewComponents BOOLEAN;
    DECLARE vKeepPrices BOOLEAN;
    
    CASE vOption
		WHEN 1 THEN  
			SET vRenewComponents = TRUE;
            SET vKeepPrices = FALSE;
		WHEN 2 THEN
			SET vComponentFk = 17;  
			SET vRenewComponents = TRUE;
            SET vKeepPrices = TRUE;
		WHEN 3 THEN 
			SET vComponentFk = 37; 
			SET vRenewComponents = TRUE;
            SET vKeepPrices = TRUE;	
		WHEN 4 THEN 
			SET vComponentFk = 34; 
			SET vRenewComponents = TRUE;
            SET vKeepPrices = TRUE;
        WHEN 5 THEN 
			SET vComponentFk = 35;
			SET vRenewComponents = TRUE;
            SET vKeepPrices = TRUE;
		WHEN 6 THEN 
    		SET vComponentFk = 36;   
			SET vRenewComponents = TRUE;
            SET vKeepPrices = TRUE;
        WHEN 7 THEN
		    REPLACE INTO saleComponent(saleFk, componentFk, value)
				SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.8, 3) 
				    FROM sale s
                        JOIN tmp.sale tmps ON tmps.saleFk = s.id
				        LEFT JOIN saleComponent sc ON sc.saleFk = s.id 
                            AND sc.componentFk NOT IN (28, 29)
                    GROUP BY s.id;
			
			REPLACE INTO saleComponent(saleFk, componentFk, value)
				SELECT s.id, 29, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.2, 3) 
				    FROM sale s
                        JOIN tmp.sale tmps ON tmps.saleFk = s.id
				        LEFT JOIN saleComponent sc ON sc.saleFk = s.id 
                            AND sc.componentFk NOT IN (28, 29)
                GROUP BY s.id;
                
			SET vRenewComponents = FALSE;
            SET vKeepPrices = FALSE;
		WHEN 8 THEN
            DELETE sc.* 
				FROM tmp.sale tmps JOIN saleComponent sc ON sc.saleFk = tmps.saleFk;
			
			REPLACE INTO saleComponent(saleFk, componentFk, value)
				SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100)), 3) 
                    FROM sale s
                        JOIN tmp.sale tmps ON tmps.saleFk = s.id;
				
			SET vRenewComponents = FALSE;
            SET vKeepPrices = FALSE;
		WHEN 9 THEN  
			SET vRenewComponents = TRUE;
            SET vKeepPrices = TRUE;
    END CASE;

    IF vRenewComponents THEN
        DELETE sc.* 
            FROM tmp.sale tmps 
                JOIN saleComponent sc ON sc.saleFk = tmps.saleFk
                JOIN componentRate cr ON cr.id = sc.componentFk
        WHERE cr.isRenewable;
				
        REPLACE INTO saleComponent(saleFk, componentFk, value)
            SELECT s.id, tc.componentFk, tc.cost
                FROM sale s 
                    JOIN tmp.sale tmps ON tmps.saleFk = s.id
                    JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk
                    LEFT JOIN saleComponent sc ON sc.saleFk = s.id 
                        AND sc.componentFk = tc.componentFk 
                    LEFT JOIN componentRate cr ON cr.id = tc.componentFk 
                WHERE IF(sc.componentFk IS NULL AND NOT cr.isRenewable, FALSE, TRUE);
    END IF;

    IF vKeepPrices THEN
		REPLACE INTO saleComponent(saleFk, componentFk, value)
		    SELECT s.id, vComponentFk, ROUND((s.price * (100 - s.discount) / 100) - SUM(sc.value), 3) dif
		        FROM sale s
                    JOIN tmp.sale tmps ON tmps.saleFk = s.id
                    LEFT JOIN saleComponent sc ON sc.saleFk = s.id
		    WHERE  sc.saleFk <> vComponentFk
		    GROUP BY s.id
		    HAVING dif <> 0;
    ELSE
		UPDATE sale s
			JOIN item i on i.id = s.itemFk
			JOIN itemType it on it.id = i.typeFk
				JOIN (SELECT SUM(sc.value) sumValue, sc.saleFk 
						FROM saleComponent sc
							JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk
						GROUP BY sc.saleFk) sc ON sc.saleFk = s.id
				SET s.price = sumValue
			WHERE it.code != 'PRT';  
            
		REPLACE INTO saleComponent(saleFk, componentFk, value)
			SELECT s.id, 21, ROUND((s.price * (100 - s.discount) / 100) - SUM(value), 3) saleValue
				FROM sale s
					JOIN tmp.sale tmps ON tmps.saleFk = s.id
					LEFT JOIN saleComponent sc ON sc.saleFk = s.id
				WHERE sc.componentFk != 21
				GROUP BY s.id 
				HAVING ROUND(saleValue, 4) <> 0;
    END IF;
    
    UPDATE sale s
		JOIN (
			SELECT SUM(sc.value) sumValue, sc.saleFk 
				FROM saleComponent sc
					JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk
					JOIN componentRate cr ON cr.id = sc.componentFk
					JOIN componentTypeRate ctr on ctr.id = cr.componentTypeRate AND ctr.base
				GROUP BY sc.saleFk) sc ON sc.saleFk = s.id
		SET s.priceFixed = sumValue, s.isPriceFixed = 1;

    DELETE sc.*
		FROM saleComponent sc
			JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk
			JOIN sale s on s.id = sc.saleFk
			JOIN item i ON i.id = s.itemFk
			JOIN itemType it ON it.id = i.typeFk
		WHERE it.code = 'PRT'; 
		
	INSERT INTO saleComponent(saleFk, componentFk, value)
		SELECT s.id, 15, s.price   
			FROM sale s
				JOIN tmp.sale tmps ON tmps.saleFk = s.id
				JOIN item i ON i.id = s.itemFK
				JOIN itemType it ON it.id = i.typeFk
		WHERE it.code = 'PRT' AND s.price > 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 `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
	CALL `ticketCreateWithUser`(vClientId, vShipped, vWarehouseId, vCompanyFk, vAddressFk, vAgencyType, vRouteFk, vlanded, account.userGetId(), 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 `ticketCreateWithUser` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithUser`(
     vClientId INT
    ,vShipped DATE
    ,vWarehouseId INT
    ,vCompanyFk INT
    ,vAddressFk INT
    ,vAgencyType INT
    ,vRouteFk INT
    ,vlanded DATE
    ,vUserId INT
    ,OUT vNewTicket INT)
BEGIN

		IF vClientId IS NULL THEN  
			CALL util.throw ('CLIENT_NOT_ESPECIFIED'); 
		END IF;

    IF NOT vAddressFk OR vAddressFk IS NULL THEN
        SELECT id INTO vAddressFk 
            FROM address
            WHERE clientFk = vClientId AND isDefaultAddress;
    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.agencyModeFk),
					a.nickname,
					vWarehouseId,
					IF(vRouteFk,vRouteFk,NULL),
					vCompanyFk,
					vlanded
			FROM address a
				JOIN agencyMode am ON am.id = a.agencyModeFk
			WHERE a.id = vAddressFk;

	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.id = vAddressFk;

	-- CALL logAddWithUser(vNewTicket, vUserId, 'insert', 'ticket', CONCAT('Ha creado el ticket', ' ', vNewTicket));
    INSERT INTO vn.ticketLog
		SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket);

	IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.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 `ticketFilter` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketFilter`()
BEGIN
/**
 * Obtiene un listado de tickets 
 * junto con el precio total y los problemas
 * 
 * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
 * @return Listado de tickets
 */
	CALL ticketGetTotal();
    CALL ticketGetProblems();
    
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketFilter;
    CREATE TEMPORARY TABLE tmp.ticketFilter ENGINE = MEMORY
    SELECT t.*, tt.total, tp.problem
		FROM tmp.ticket t
        JOIN tmp.ticketTotal tt ON tt.ticketFk = t.ticketFk
        LEFT JOIN tmp.ticketProblems tp ON tp.ticketFk = t.ticketFk;

    DROP TEMPORARY TABLE 
        tmp.ticket, 
        tmp.ticketTotal, 
        tmp.ticketProblems;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketGetProblems` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetProblems`()
BEGIN

    DECLARE vWarehouse INT;
    DECLARE vDate DATE;
    DECLARE vAvailableCache INT;
    DECLARE vVisibleCache INT;
    DECLARE vDone INT DEFAULT 0;

    DECLARE vCursor CURSOR FOR
        SELECT DISTINCT tt.warehouseFk, date(tt.shipped)
            FROM tmp.ticketGetProblems tt
            WHERE DATE(tt.shipped) BETWEEN CURDATE()
                AND TIMESTAMPADD(DAY, 1.9, CURDATE());
  
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1;

    DROP TEMPORARY TABLE IF EXISTS tmp.ticketProblems;
        CREATE TEMPORARY TABLE tmp.ticketProblems (
            ticketFk INT(11) PRIMARY KEY,
            isFreezed INTEGER(1) DEFAULT 0,
            risk DECIMAL(10,2) DEFAULT 0,
            hasTicketRequest INTEGER(1) DEFAULT 0,
            isAvailable INTEGER(1) DEFAULT 1
        ) ENGINE = MEMORY;

     DROP TEMPORARY TABLE IF EXISTS tmp.ticketList;
        CREATE TEMPORARY TABLE tmp.ticketList
        (PRIMARY KEY (ticketFk))
         ENGINE = MEMORY
            SELECT tp.ticketFk, c.id clientFk
                FROM tmp.ticketGetProblems tp
        JOIN vn.client c ON c.id = tp.clientFk;
 
 
    INSERT INTO tmp.ticketProblems(ticketFk, isFreezed)
        SELECT DISTINCT tl.ticketFk, 1
            FROM tmp.ticketList tl
                JOIN vn.client c ON c.id = tl.clientFk
            WHERE c.isFreezed;

    DELETE tl FROM tmp.ticketList tl
        JOIN tmp.ticketProblems tp ON tl.ticketFk = tp.ticketFk;

     DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt;
     CREATE TEMPORARY TABLE tmp.clientGetDebt
        (PRIMARY KEY (clientFk))
        ENGINE = MEMORY
            SELECT DISTINCT clientFk
                FROM tmp.ticketList;

    CALL clientGetDebt(CURDATE());

 
    INSERT INTO tmp.ticketProblems(ticketFk, risk)
        SELECT DISTINCT tl.ticketFk, r.risk
            FROM tmp.ticketList tl
                JOIN vn.ticket t ON t.id = tl.ticketFk
                JOIN vn.agencyMode a ON t.agencyModeFk = a.id
                JOIN tmp.risk r ON r.clientFk = t.clientFk
                JOIN vn.client c ON c.id = t.clientFk
            WHERE r.risk > c.credit + 10
                AND a.deliveryMethodFk != 3
        ON DUPLICATE KEY UPDATE
            risk = r.risk;
   
    DELETE tl FROM tmp.ticketList tl
        JOIN tmp.ticketProblems tp ON tl.ticketFk = tp.ticketFk;
  
     
    INSERT INTO tmp.ticketProblems(ticketFk, hasTicketRequest)
        SELECT DISTINCT tl.ticketFk, 1
            FROM tmp.ticketList tl
                JOIN vn.ticketRequest tr ON tr.ticketFk = tl.ticketFk
            WHERE tr.isOK IS NULL
        ON DUPLICATE KEY UPDATE
            hasTicketRequest = 1;
      
    DELETE tl FROM tmp.ticketList tl
        JOIN tmp.ticketProblems tp ON tl.ticketFk = tp.ticketFk;

    OPEN vCursor;

    WHILE NOT vDone
    DO
        FETCH vCursor INTO vWarehouse, vDate;
   
        CALL cache.visible_refresh(vVisibleCache, FALSE, vWarehouse);
        CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouse, vDate);

 
        INSERT INTO tmp.ticketProblems(ticketFk, isAvailable)
            SELECT tl.ticketFk, 0
                FROM tmp.ticketList tl
                    JOIN vn.ticket t ON t.id = tl.ticketFk
                    LEFT JOIN vn.sale s ON s.ticketFk = t.id
                    JOIN vn.item i ON i.id = s.itemFk
                    JOIN vn.itemType it on it.id = i.typeFk
                    LEFT JOIN cache.visible v ON i.id = v.item_id
                    AND v.calc_id = vVisibleCache
                    LEFT JOIN cache.available av ON av.item_id = i.id
                    AND av.calc_id = vAvailableCache
                WHERE date(t.shipped) = vDate
                    AND categoryFk != 6
                    AND s.quantity > IFNULL(v.visible, 0)
                    AND IFNULL(av.available, 0) < 0
                    AND s.isPicked = FALSE
                    AND NOT i.generic
                    AND vWarehouse = t.warehouseFk
                GROUP BY tl.ticketFk
            ON DUPLICATE KEY UPDATE
                isAvailable = 0;

   
    DELETE tl FROM tmp.ticketList tl
        JOIN tmp.ticketProblems tp ON tl.ticketFk = tp.ticketFk; 

   
    INSERT INTO tmp.ticketProblems(ticketFk, isAvailable)
        SELECT tl.ticketFk, 0
            FROM tmp.ticketList tl
                JOIN vn.ticket t ON t.id = tl.ticketFk
                LEFT JOIN vn.sale s ON s.ticketFk = t.id
                JOIN vn.item i ON i.id = s.itemFk
                JOIN vn.itemType it on it.id = i.typeFk
                LEFT JOIN cache.visible v ON i.id = v.item_id AND v.calc_id = vVisibleCache
                LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache
            WHERE IFNULL(av.available, 0) >= 0
                AND s.quantity > IFNULL(v.visible, 0)
                AND s.isPicked = FALSE
                AND s.reserved = FALSE
                AND it.categoryFk != 6
                AND date(t.shipped) = vDate
                AND NOT i.generic
                AND CURDATE() = vDate
                AND t.warehouseFk = vWarehouse
            GROUP BY tl.ticketFk
        ON DUPLICATE KEY UPDATE
            isAvailable = 0;
 
    DELETE tl FROM tmp.ticketList tl
        JOIN tmp.ticketProblems tp ON tl.ticketFk = tp.ticketFk;

    END WHILE;

    CLOSE vCursor;

    SELECT * FROM tmp.ticketProblems;
   
    DROP TEMPORARY TABLE
        tmp.clientGetDebt,
        tmp.ticketList; 
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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              = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetTax`()
    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
 * @return tmp.ticketAmount
 * @return tmp.ticketTax Impuesto desglosado para cada ticket.

 */
    DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany;
    CREATE TEMPORARY TABLE tmp.addressCompany
        (INDEX (addressFk, companyFk))
        ENGINE = MEMORY
        SELECT DISTINCT t.addressFk, t.companyFk
            FROM tmp.ticket tmpTicket
                JOIN ticket t ON t.id = tmpTicket.ticketFk;

    CALL addressTaxArea ();
    

 /** Solo se calcula la base imponible (taxableBase) y el impuesto se calculará posteriormente
  *   No se debería cambiar el sistema por problemas con los decimales
  */
    
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax;
    CREATE TEMPORARY TABLE tmp.ticketTax
        (INDEX (ticketFk))
        ENGINE = MEMORY
    SELECT tmpTicket.ticketFk,
                bp.pgcFk,
                SUM(s.quantity * s.price * (100 - s.discount)/100 ) AS taxableBase,
                pgc.rate,
                tc.code
            FROM tmp.ticket tmpTicket
                JOIN sale s ON s.ticketFk = tmpTicket.ticketFk
                JOIN item i ON i.id = s.itemFk
                JOIN ticket t ON t.id = tmpTicket.ticketFk
                JOIN supplier su ON su.id = t.companyFk
                JOIN tmp.addressTaxArea ata
                    ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk
                JOIN itemTaxCountry itc
                    ON itc.itemFk = i.id AND itc.countryFk = su.countryFk
                JOIN bookingPlanner bp
                    ON bp.countryFk = su.countryFk
                        AND bp.taxAreaFk = ata.areaFk
                        AND bp.taxClassFk = itc.taxClassFk
                JOIN pgc ON pgc.code = bp.pgcFk
                JOIN taxClass tc ON tc.id = bp.taxClassFk
            GROUP BY tmpTicket.ticketFk, pgc.code,pgc.rate
            HAVING taxableBase != 0;

   DROP TEMPORARY TABLE IF EXISTS tmp.ticketServiceTax;
    CREATE TEMPORARY TABLE tmp.ticketServiceTax
        (INDEX (ticketFk))
        ENGINE = MEMORY
     SELECT tt.ticketFk,
                      SUM(ts.quantity * ts.price) AS taxableBase,
                    pgc.rate,
                    tc.code
                FROM tmp.ticketTax tt
                    JOIN ticketService ts ON ts.ticketFk = tt.ticketFk
                    JOIN ticket t ON t.id = tt.ticketFk
                    JOIN supplier su ON su.id = t.companyFk
                    JOIN tmp.addressTaxArea ata
                        ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk          
                    JOIN bookingPlanner bp
                        ON bp.countryFk = su.countryFk
                            AND bp.taxAreaFk = ata.areaFk
                            AND bp.taxClassFk = ts.taxClassFk
                    JOIN pgc ON pgc.code = bp.pgcFk AND pgc.rate = tt.rate
                    JOIN taxClass tc ON tc.id = bp.taxClassFk
                    GROUP BY tt.ticketFk, tt.code,tt.rate
                    HAVING taxableBase != 0;

        UPDATE tmp.ticketTax tt
            JOIN tmp.ticketServiceTax ts ON tt.ticketFk = ts.ticketFk AND tt.code = ts.code AND tt.rate = ts.rate
        SET tt.taxableBase = tt.taxableBase + ts.taxableBase;

    DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount;
    CREATE TEMPORARY TABLE tmp.ticketAmount
        (INDEX (ticketFk))
        ENGINE = MEMORY
        SELECT ticketFk, taxableBase, SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax,code
            FROM tmp.ticketTax
            GROUP BY ticketFk, code;

    DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany;
    DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketGetTaxAdd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetTaxAdd`(vTicketFk INT)
BEGIN
/**
 * Añade un ticket a la tabla tmp.ticket para calcular
 * el IVA y el recargo de equivalencia y devuelve el resultado.
 */
	DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
	CREATE TEMPORARY TABLE tmp.ticket
		ENGINE = MEMORY
		SELECT vTicketFk ticketFk;
        
	CALL vn.ticketGetTax();

    SELECT 
			tt.ticketFk,
            CAST(tt.taxableBase AS DECIMAL(10, 2)) AS taxableBase,
			CAST(tt.rate * tt.taxableBase / 100  AS DECIMAL(10, 2)) AS tax,
            pgc.*, 
            CAST(IF(pe.equFk IS NULL, taxableBase, 0) AS DECIMAL(10, 2)) AS Base,
            pgc.rate / 100 as vatPercent
		FROM tmp.ticketTax tt
			JOIN vn.pgc ON pgc.code = tt.pgcFk
			LEFT JOIN vn.pgcEqu pe ON pe.equFk = pgc.code;
    
	DROP TEMPORARY TABLE tmp.ticket;
    DROP TEMPORARY TABLE tmp.ticketTax;
	DROP TEMPORARY TABLE tmp.ticketAmount;
  
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_new` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetTax_new`()
    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
 * @return tmp.ticketTax Impuesto desglosado para cada ticket
 * @return tmp.ticketAmount
 */

	DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany;
	CREATE TEMPORARY TABLE tmp.addressCompany
		(INDEX (addressFk, companyFk))
		ENGINE = MEMORY
			SELECT DISTINCT t.addressFk, t.companyFk
				FROM tmp.ticket tmpTicket
					JOIN ticket t ON t.id = tmpTicket.ticketFk;

    CALL addressTaxArea ();
     
	DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax;
	CREATE TEMPORARY TABLE tmp.ticketTax
		(INDEX (ticketFk))
		ENGINE = MEMORY
			SELECT tmpTicket.ticketFk,
					bp.pgcFk,
					SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) 
						) AS taxableBase,
					SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)
						) * pgc.rate / 100 AS tax,
					tc.code
                        
				FROM tmp.ticket tmpTicket
					JOIN sale s ON s.ticketFk = tmpTicket.ticketFk
					JOIN item i ON i.id = s.itemFk
                    JOIN ticket t ON t.id = tmpTicket.ticketFk
                    JOIN supplier su ON su.id = t.companyFk
                    JOIN tmp.addressTaxArea ata 
						ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk
					JOIN itemTaxCountry itc 
						ON itc.itemFk = i.id AND itc.countryFk = su.countryFk
					JOIN bookingPlanner bp 
						ON bp.countryFk = su.countryFk
							AND bp.taxAreaFk = ata.areaFk
							AND bp.taxClassFk = itc.taxClassFk
					JOIN pgc ON pgc.code = bp.pgcFk
                    JOIN taxClass tc ON tc.id = bp.taxClassFk
				GROUP BY tmpTicket.ticketFk, pgc.code
				HAVING taxableBase != 0;
                              
	DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount;
	CREATE TEMPORARY TABLE tmp.ticketAmount
		(INDEX (ticketFk))
		ENGINE = MEMORY
			SELECT ticketFk, taxableBase, SUM(tax) tax
				FROM tmp.ticketTax
				GROUP BY ticketFk, code;

    DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany;
    DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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
 * @return tmp.ticketTotal Total para cada ticket
 */
	CALL ticketGetTax;
	 
	DROP TEMPORARY TABLE IF EXISTS tmp.ticketTotal;
	CREATE TEMPORARY TABLE tmp.ticketTotal
		(INDEX (ticketFk))
		ENGINE = MEMORY
		SELECT t.ticketFk, IFNULL(SUM(ta.taxableBase + ta.tax), 0.0) AS total
			FROM tmp.ticket t
				LEFT JOIN tmp.ticketAmount ta ON t.ticketFk = ta.ticketFk
			GROUP BY ticketFk;
			
	DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount;
	DROP TEMPORARY TABLE IF EXISTS 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 `ticketGetVisibleAvailable` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetVisibleAvailable`(
    vTicket INT)
BEGIN
    DECLARE vVisibleCalc INT;
    DECLARE vAvailableCalc INT;
    DECLARE vShipped DATE;
    DECLARE vWarehouse TINYINT;
    DECLARE vAlertLevel INT;

    SELECT t.warehouseFk, t.shipped, ts.alertLevel INTO vWarehouse, vShipped, vAlertLevel
        FROM ticket t
            LEFT JOIN ticketState ts ON ts.ticketFk = vTicket
       WHERE t.id = vTicket;

    IF vAlertLevel IS NULL OR vAlertLevel = 0 THEN
        IF vShipped >= CURDATE() THEN
            CALL cache.available_refresh(vAvailableCalc, FALSE, vWarehouse, vShipped);
        END IF;
        IF vShipped = CURDATE() THEN
            CALL cache.visible_refresh(vVisibleCalc, FALSE, vWarehouse);
        END IF;
    END IF;

    SELECT s.id, s.itemFk, s.quantity, s.concept, s.price, s.reserved, s.discount, v.visible, av.available, it.image, it.subName
        FROM sale s
            LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCalc
            LEFT JOIN cache.available av ON av.item_id = s.itemFk AND av.calc_id = vAvailableCalc
            LEFT JOIN item it ON it.id = s.itemFk
        WHERE s.ticketFk = vTicket
		ORDER BY s.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 `ticketListCreate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketListCreate`(
     vClientId INT
    ,vShipped DATE
    ,vWarehouseId INT
    ,vCompanyFk INT
    ,vAddressFk INT
    ,vAgencyType INT
    ,vRouteFk INT
    ,vlanded DATE)
BEGIN

    DECLARE vNewTicket INT;
    CALL vn.ticketCreate(vClientId, vShipped, vWarehouseId, vCompanyFk, vAddressFk, vAgencyType, vRouteFk, vlanded,vNewTicket);
    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 `ticketListVolume` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketListVolume`(IN vTicketId INT)
BEGIN

	DECLARE vWarehouseId INTEGER;
    DECLARE vShippedDate DATE;

    SELECT warehouseFk, shipped INTO vWarehouseId,vShippedDate FROM vn.ticket WHERE id = vTicketId;

	SELECT s.quantity, 
			round(r.cm3 * i.compression * s.quantity / 1000000,3) as m3,
			s.itemFk, 
            s.id AS saleFk, 
            s.concept, 
            t.agencyModeFk
                FROM sale s
					JOIN vn.item i ON i.id = s.itemFk
                    JOIN vn.ticket t on t.id = s.ticketFk
                    JOIN bi.rotacion r ON r.Id_Article = s.itemFk AND r.warehouse_id = t.warehouseFk
                WHERE s.ticketFk = vTicketId;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketNotInvoicedByClient` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketNotInvoicedByClient`(vClientFk INT)
BEGIN

	DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
    
	CREATE TEMPORARY TABLE tmp.ticket
		SELECT id ticketFk
			FROM ticket
		WHERE refFk IS NULL
			AND clientFk = vClientFk
			AND shipped > '2001-01-01';

	CALL vn.ticketGetTotal;

	SELECT 	c.id, 
			c.name as Cliente,
            t.shipped as Fecha,
            t.id as Id_Ticket,
            CAST(tt.total AS DECIMAL(10,2)) as Importe
		FROM tmp.ticketTotal tt
			JOIN ticket t ON t.id = tt.ticketFk
			JOIN client c ON c.id = t.ClientFk;

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

/* Recupera los embalajes que han caido en el cliente 31 */

DECLARE done BOOL DEFAULT FALSE;
DECLARE vClientFk INT;
DECLARE vTicketFk INT;
DECLARE vTicketNewFk INT;
DECLARE vWarehouseFk INT;
DECLARE vShipped DATE;
DECLARE vAddressFk INT;
DECLARE vCompanyFk INT;
DECLARE vAgenciaEmbalajesFk INT DEFAULT 628;

DECLARE rs CURSOR FOR
		SELECT DISTINCT tp.ticketFk, a.clientFk, t.warehouseFk, t.shipped, t.addressFk, t.companyFk
        FROM ticket t 
        JOIN ticketPackaging tp ON t.id = tp.ticketFk
        JOIN address a ON a.id = t.addressFk
		WHERE t.clientFk = 31 
        AND a.clientFk != 31
        AND t.shipped > '2001-01-01';

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN rs;

FETCH rs INTO vTicketFk, vClientFk, vWarehouseFk, vShipped, vAddressFk,vCompanyFk;

WHILE NOT done DO

    CALL vn.ticketCreate(vClientFk,vShipped,vWarehouseFk,vCompanyFk,vAddressFk,vAgenciaEmbalajesFk,NULL,vShipped,vTicketNewFk);

    UPDATE vn.ticketPackaging set ticketFk = vTicketNewFk WHERE ticketFk = vTicketFk;

    CALL vn.ticketStateUpdate(vTicketNewFk, 'DELIVERED');

    INSERT INTO vn.sale(ticketFk, itemFk, concept) VALUES(vTicketNewFk,90,CONCAT('Embalajes ',vTicketFk));
    
	FETCH rs INTO vTicketFk, vClientFk, vWarehouseFk, vShipped, vAddressFk,vCompanyFk;

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 `ticketShippingFillLabel` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketShippingFillLabel`(vTicketFk INT)
BEGIN
	/* Prepara el origen de datos para la etiqueta amarilla de preparacion previa
     * 
    */
	DECLARE vCalcFk INT;
    DECLARE vWarehouseFk INT;
    
    SELECT warehouseFk INTO vWarehouseFk
		FROM vn.ticket
        WHERE id = vTicketFk;
        
    CALL cache.ticketShippingRefresh(vCalcFk,FALSE,vWarehouseFk);

	SELECT  
			ts.ticketFk ,
            ts.shippingHour, 
            ts.shippingMinute 
		FROM cache.ticketShipping ts
		WHERE ts.calc_id = vCalcFk AND ts.ticketFk = vTicketFk;

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

SELECT CONCAT(OK,'/',Total, IF(OK = Total ,' LS',''))
	FROM
	(
		SELECT sum(if(l.Id_Movimiento != 0,1,0)) as OK, COUNT(*) as Total
			FROM vn.sale s
				LEFT JOIN movement_label l ON l.Id_Movimiento = s.id
			WHERE ticketFk = vTicketFk
	) sub;

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

	DECLARE vControlFk INT;
    DECLARE vLastWorkerFk INT;
    DECLARE vStateId INT;
    
    SELECT MAX(inter_id) INTO vControlFk
		FROM vncontrol.inter
        WHERE Id_Ticket = vTicketFk;
        
	IF (SELECT s.code
			FROM vn.state s 
				JOIN vncontrol.inter i ON i.state_id = s.id 
			WHERE i.inter_id = vControlFk) 
		= 'PREVIOUS_PREPARATION' THEN
        
        SELECT inter_id, Id_Trabajador
				INTO vControlFk,vLastWorkerFk
			FROM vncontrol.inter i  
				JOIN vn.state s ON i.state_id = s.id
			WHERE Id_Ticket = vTicketFk
				AND inter_id < vControlFk
                AND s.code != 'PREVIOUS_PREPARATION'
			ORDER BY inter_id DESC
            LIMIT 1;
                
		INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador, Id_Supervisor)
			SELECT state_id, Id_Ticket, vLastWorkerFk, vn.getWorker()
				FROM vncontrol.inter
                WHERE inter_id = vControlFk;
                
		SELECT state_id INTO vStateId
				FROM vncontrol.inter
                WHERE inter_id = vControlFk;
                      
    END IF;
    
    /*DELETE FROM vn2008.Movimientos_mark 
    WHERE Id_Movimiento IN (SELECT Id_Movimiento FROM vn2008.Movimientos WHERE Id_Ticket = vTicketFk)
    AND valor  <> 1
    AND stateFk = 26;  */
    
    SELECT TRUE AS IsUpdated;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketStateUpdate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketStateUpdate`(vTicketFk	INT, vStateCode VARCHAR(45))
BEGIN

	INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador)
		SELECT id, vTicketFk, getWorker()
			FROM vn.state 
            WHERE `code` = vStateCode collate utf8_unicode_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 `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 `ticketToPrePrepare` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketToPrePrepare`(IN vIdTicket INT, IN viewAll BOOL)
BEGIN

/* Tickets con estado 26 para preaprar en altillo 
*/
IF viewAll IS true THEN
	SELECT   *
		FROM vn.ticketeToPreparePrepared ttp
        WHERE ttp.Id_Ticket =  vIdTicket;
ELSE
	SELECT   *
			FROM vn.ticketToPrepare ttp
			WHERE ttp.Id_Ticket =  vIdTicket;

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

	DECLARE vDateStart DATETIME DEFAULT DATE(vDate);
    DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate);

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketVolumeByDate;
    
    CREATE TEMPORARY TABLE tmp.ticketVolumeByDate
	ENGINE = MEMORY
	SELECT s.ticketFk,
			CAST(SUM(r.cm3 * s.quantity) / 1000000 AS DECIMAL(10,2)) as m3
                FROM sale s
					JOIN vn.item i ON i.id = s.itemFk
                    JOIN vn.itemType it ON it.id = i.typeFk
                    JOIN vn.itemCategory ic ON ic.id = it.categoryFk
                    JOIN vn.ticket t on t.id = s.ticketFk
                    JOIN bi.rotacion r ON r.Id_Article = s.itemFk AND r.warehouse_id = t.warehouseFk
                WHERE ic.merchandise 
					AND ic.id < 6
                    AND t.shipped BETWEEN vDateStart AND vDateEnd
                GROUP BY s.ticketFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travel_checkDates` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `travel_checkDates`(vShipped DATE, vLanded DATE)
BEGIN
/**
 * Checks the landing/shipment dates of travel, throws an error
 * ir they are not correct.
 *
 * @param vShipped The shipment date
 * @param vLanded The landing date
 */
	IF vLanded < vShipped THEN
		SIGNAL SQLSTATE '45000'
			SET MESSAGE_TEXT = 'Landing cannot be lesser than shipment';
	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 `travel_doRecalc` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `travel_doRecalc`()
BEGIN
/**
 * Recounts the number of entries of changed travels.
 */
	DECLARE vDone BOOL;
	DECLARE vTravelFk INT;
    DECLARE vTotalEntries INT;

	DECLARE cCur CURSOR FOR
		SELECT travelFk FROM travelRecalc;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	OPEN cCur;

	myLoop: LOOP
		SET vDone = FALSE;
		FETCH cCur INTO vTravelFk;

		IF vDone THEN
			LEAVE myLoop;
		END IF;

		SELECT COUNT(*) INTO vTotalEntries
			FROM entry
			WHERE travelFk = vTravelFk;
            
		UPDATE travel
			SET totalEntries = vTotalEntries
			WHERE id = vTravelFk;
            
		DELETE FROM travelRecalc WHERE travelFk = vTravelFk;
	END LOOP;

	CLOSE cCur;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travel_requestRecalc` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `travel_requestRecalc`(vSelf INT)
proc: BEGIN
/**
 * Adds a request to recount the number of entries for the travel.
 *
 * @param vSelf The travel reference
 */
	IF vSelf IS NULL THEN
		LEAVE proc;
	END IF;
    
    INSERT IGNORE INTO travelRecalc SET travelFk = vSelf;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `typeTagMake` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `typeTagMake`(vTypeFk INT)
BEGIN

	DELETE it.* 
		FROM itemTag it 
			JOIN item i ON i.id = it.itemFk
		WHERE i.typeFk = vTypeFk;

	INSERT INTO itemTag(itemFk, tagFk, value, priority)
		SELECT  i.id, t.id, CONCAT(i.size,' cm'), 1
			FROM item i
				JOIN tag t ON t.name = 'Longitud' COLLATE utf8_general_ci
			WHERE i.typeFk  =  vTypeFk;
            
	INSERT INTO itemTag(itemFk, tagFk, value, priority)
		SELECT  i.id, t.id, i.category, 5
			FROM item i
				JOIN tag t ON t.name = 'Categoria' COLLATE utf8_general_ci
			WHERE i.typeFk  =  vTypeFk;
    	
	INSERT INTO itemTag(itemFk, tagFk, value, priority)
		SELECT  i.id, t.id, ink.name, 2
			FROM item i
				JOIN tag t ON t.name = 'Color' COLLATE utf8_general_ci
                JOIN ink ON ink.id = i.inkFk
			WHERE i.typeFk  =  vTypeFk;
            
    INSERT INTO itemTag(itemFk, tagFk, value, priority)
		SELECT  i.id, t.id, p.name, 3
			FROM item i
				JOIN tag t ON t.name = 'Productor' COLLATE utf8_general_ci
                JOIN producer p ON p.id = i.producerFk
			WHERE i.typeFk  =  vTypeFk;    
            
	INSERT INTO itemTag(itemFk, tagFk, value, priority)
		SELECT  i.id, t.id, o.name, 4
			FROM item i
				JOIN tag t ON t.name = 'Origen' COLLATE utf8_general_ci
                JOIN origin o ON o.id = i.originFk
			WHERE i.typeFk  =  vTypeFk;
     /*      
	INSERT INTO itemTag(itemFk, tagFk, value, priority)
		SELECT  i.id, t.id, i.stems, 6
			FROM item i
				JOIN tag t ON t.name = 'Tallos' COLLATE utf8_general_ci
			WHERE i.typeFk  =  vTypeFk;  
     */   
-- CALL itemTagArrangedUpdate(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 `updatePedidosInternos` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `updatePedidosInternos`(vItemFk INT)
BEGIN

	UPDATE vn.item SET upToDown = 0 WHERE item.id = vItemFk;
    

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `warehouseFitting` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `warehouseFitting`(IN vWhOrigin INT , IN vWhDestiny INT)
BEGIN
	DECLARE vCacheVisibleOriginFk INT;
    DECLARE vCacheVisibleDestinyFk INT;
    
	CALL cache.visible_refresh(vCacheVisibleOriginFk, TRUE, vWhOrigin);
    CALL cache.visible_refresh(vCacheVisibleDestinyFk, TRUE, vWhDestiny);
    
    SELECT i.id itemFk,
		   i.longName,
           i.size,
           i.subName,
           vOrigin.visible AS Origen,
           vDestiny.visible Destino
           
		FROM vn.item i
			JOIN vn.itemType it ON it.id = i.typeFk
			LEFT JOIN cache.visible vOrigin ON vOrigin.calc_id = vCacheVisibleOriginFk AND vOrigin.item_id = i.id
            LEFT JOIN cache.visible vDestiny ON vDestiny.calc_id = vCacheVisibleDestinyFk AND vDestiny.item_id = i.id
            WHERE (vOrigin.visible OR vDestiny.visible)
				AND it.categoryFk < 6
			ORDER BY IF(vOrigin.visible,0,1), longName, size, subName;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `warehouseFitting_byTravel` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `warehouseFitting_byTravel`(IN vTravelFk INT)
BEGIN

	DECLARE vWhOrigin INT;
    DECLARE vWhDestiny INT;
    
    SELECT warehouseInFk, warehouseOutFk INTO vWhDestiny, vWhOrigin
		FROM vn.travel
        WHERE id = vTravelFk;
        
	CALL vn.warehouseFitting(vWhOrigin, vWhDestiny);
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerCalculateBoss` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `workerCalculateBoss`(vWorker INT)
BEGIN
/**
* Actualiza la tabla workerBosses
* vWorker: id del trabajador
*
*/
	DECLARE vBoss INT;
	DECLARE vWorkerCompare INT DEFAULT vWorker;

	l: LOOP
		SELECT bossFk INTO vBoss
			FROM vn.worker
			WHERE id=vWorkerCompare;

		IF vBoss=0 OR vWorkerCompare=vBoss THEN
			LEAVE l;
		END IF;

		REPLACE INTO vn.workerBosses(workerFk,bossFk)
			VALUES(vWorker,vBoss);

		SET vWorkerCompare = vBoss;

	END LOOP;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerCreate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `workerCreate`(
	vFirstname VARCHAR(50),
    vSurnames VARCHAR(50), 
    vFi VARCHAR(9),
    vWorkerCode CHAR(3),
    vBossFk INT,
    vUserFk INT
)
BEGIN
/**
 * Create new worker
 *
 */

	INSERT INTO vn2008.Trabajadores(CodigoTrabajador, Nombre, Apellidos, dni, user_id, boss) 
		VALUES (vWorkerCode, vFirstname, vSurnames, vFi, vUserFk, vBossFk);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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,lastName,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 `workerDepartmentByDate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `workerDepartmentByDate`(vDate DATE)
BEGIN

	DROP TEMPORARY TABLE IF EXISTS tmp.workerDepartmentByDate;
    CREATE TEMPORARY TABLE tmp.workerDepartmentByDate
		ENGINE = MEMORY
		SELECT 
			w.userFk, 
            p.name, 
            p.firstname, 
            d.name AS department, 
            b.date_start, 
            d.production, 
            CAST(12 * blp.importepactado / clt.hours_week / 52 AS DECIMAL(10,2)) as costeHora 
            
		FROM postgresql.person p
			JOIN postgresql.profile pr ON p.person_id = pr.person_id
			JOIN postgresql.business b ON b.client_id = pr.profile_id
			JOIN postgresql.business_labour bl ON bl.business_id = b.business_id
            JOIN postgresql.calendar_labour_type clt ON clt.calendar_labour_type_id = bl.calendar_labour_type_id
            JOIN postgresql.business_labour_payroll blp ON blp.business_id = b.business_id
			JOIN vn2008.department d ON d.department_id = bl.department_id
			JOIN vn.worker w ON w.id = p.id_trabajador
		WHERE b.date_start <= vDate AND IFNULL(b.date_end,'3000-01-01') > vDate
			;

	-- SELECT * FROM tmp.workerDepartmentByDate;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `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` c
		JOIN payMethod p ON p.name = 'CONTADO'
		SET c.credit = 0, c.payMethodFk = p.id, hasCoreVnl = FALSE
		WHERE c.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 `workerDisableAll` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `workerDisableAll`()
BEGIN
	DECLARE done BOOL DEFAULT FALSE;
	DECLARE vUserFk INT;

	DECLARE rs CURSOR FOR
		SELECT a.id
			FROM ((SELECT * FROM (select date_end,date_start,business_id, client_id
						FROM postgresql.business
						ORDER BY client_id, date_end IS NULL DESC , date_end DESC) 
					c GROUP BY client_id) c 
				INNER JOIN postgresql.business b ON c.client_id = b.client_id AND c.business_id = b.business_id
				INNER JOIN postgresql.profile pr ON b.client_id = pr.profile_id
				INNER JOIN postgresql.person p ON pr.person_id = p.person_id 
					
				INNER JOIN vn.worker w ON p.id_trabajador = w.id)
				INNER JOIN account.account a ON w.userFk = a.id
			WHERE ((b.date_end) IS NOT NULL
				AND (b.date_end) < CURDATE()
				AND (b.date_end) > TIMESTAMPADD(DAY, -70,CURDATE()) );
                
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	OPEN rs;

	FETCH rs INTO vUserFk;

	WHILE NOT done DO
		CALL workerDisable(vUserFk);
		FETCH rs INTO vUserFk;

	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 `workerForAllCalculateBoss` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `workerForAllCalculateBoss`()
BEGIN
/**
* Actualiza la tabla workerBosses utilizando el procedimiento
* vn.workerCalculateBoss(), actualiza todos los trabajadores en esa tabla
*
*/
	DECLARE vWorker INT;
	DECLARE vDone BOOL;

	DECLARE cur CURSOR FOR
	SELECT id FROM worker;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

	OPEN cur;

	l: LOOP
		SET vDone = FALSE;
		FETCH cur INTO vWorker;

		IF vDone THEN
			LEAVE l;
		END IF;

		CALL workerCalculateBoss(vWorker);
	END LOOP;

	CLOSE cur;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerJourneyReplace` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `workerJourneyReplace`(vFromDate DATE, vToDate DATE, vUserFk INT)
BEGIN

	/*  Actualiza la tabla workerJourney para que actue como caché permanente revisable de las jornadas laborales.
    *   vUserFk es opcional. El valor 0 indica que se tenga en cuenta a todos los usuarios.
    *
    *   PAK Julio '18
    */
	
	DELETE
    FROM workerJourney
		WHERE dated BETWEEN vFromDate AND vToDate 
			AND isPaid = FALSE
            AND isUpdated = FALSE
            AND vUserFk IN (0,userFk);
        
	
    -- Se inicia la tabla con todas las fechas posibles para cada uno de los trabajadores que han fichado en el rango de fechas.
	INSERT IGNORE INTO workerJourney(userFk, dated, businessFk)
    SELECT w.userFk, tm.dated, b.business_id
					FROM vn.worker w
						JOIN postgresql.person pe ON pe.id_trabajador = w.id
						JOIN postgresql.profile p ON p.person_id = pe.person_id
						JOIN postgresql.business b ON b.client_id = p.profile_id
						JOIN postgresql.business_labour bl ON bl.business_id = b.business_id
                        JOIN vn.time tm ON tm.dated BETWEEN   b.date_start AND IFNULL(b.date_end,CURDATE())
					WHERE b.date_start <= vToDate
						AND IFNULL(b.date_end, CURDATE()) >= vFromDate
						AND bl.porhoras
                        AND vUserFk IN (0,w.userFk);
  
	-- Se actualiza la cantidad total de horas prácticas, así como el tiempo de almuerzo remunerado, si corresponde
	UPDATE workerJourney wj
		JOIN workerTimeControl_Journey j ON wj.dated = j.dated AND wj.userFk = j.userFk
        SET wj.total = j.Journey,
			wj.lunch = IF(j.Journey < 5,0,0.33)
		WHERE wj.dated BETWEEN vFromDate AND vToDate
			AND wj.isPaid = FALSE
            AND wj.isUpdated = FALSE
            AND vUserFk IN (0,wj.userFk);    
        
	/********** NOCTURNIDAD ************/
    DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControl;
    
	CREATE TEMPORARY TABLE tmp.workerTimeControl
		SELECT w.*, 0 as Non 
			FROM vn.workerTimeControl w
			WHERE timed BETWEEN vFromDate AND vToDate
            AND vUserFk IN (0,userFk)
            ORDER BY userFk, timed;
	
    -- Regalamos un segundo para evitar que hayan fichadas en las horas claves de inicio y fin de la nocturnidad.
    UPDATE tmp.workerTimeControl 
		SET timed = TIMESTAMPADD(SECOND,-1,timed) 
        WHERE TIME(timed) IN ('06:00:00','22:00:00');

    -- Fichada virtual a las 6:00 h, hora en que empieza la jornada diurna
	INSERT INTO tmp.workerTimeControl(userFk, timed)
		SELECT userFk, TIMESTAMPADD(HOUR, 6, DATE(timed))
			FROM vn.workerTimeControl 
            WHERE vUserFk IN (0,userFk)
			GROUP BY userFk, DATE(timed);  
    
    -- Fichada virtual a las 22:00 h, momento en que empieza la jornada nocturna.
	INSERT INTO tmp.workerTimeControl(userFk, timed)
		SELECT userFk, TIMESTAMPADD(HOUR, 22, DATE(timed))
			FROM vn.workerTimeControl 
            WHERE vUserFk IN (0,userFk)
			GROUP BY userFk, DATE(timed);     
	
	-- Establece el orden en que se han de leer las fichadas
	CALL vn.workerTimeControlSetOrder;

	-- Marca los impares para facilitar la consulta siguiente
	UPDATE tmp.workerTimeControl 
		SET Non = 1 
		WHERE `order` mod 2;

	-- Actualizamos la nocturnidad
	UPDATE workerJourney wj
		JOIN
			(	SELECT userFk, Dia, sum(Nocturnidad) as Nocturnidad FROM
					(
					SELECT 	userFk, 
							date(timed) as Dia,										
							((
								IF( TIME(timed) < '06:00:00' OR (TIME(timed) = '06:00:00' AND Non = FALSE ) , IF(Non,-1,1),0)
								+
								IF(TIME(timed) > '22:00:00' OR (TIME(timed) = '22:00:00' AND Non = TRUE), If(Non,-1,1),0)
								)
								* (HOUR(`timed`) + MINUTE(`timed`) / 60)
							) as Nocturnidad
						FROM tmp.workerTimeControl
					) sub
					GROUP BY Dia, userFk
					HAVING Nocturnidad
			) night ON night.userFk = wj.userFk AND night.Dia = wj.dated
		SET wj.nocturn = night.Nocturnidad
        WHERE wj.isPaid = FALSE  AND isUpdated = FALSE;

	-- Horas téoricas y precio de la hora ordinaria
	UPDATE vn.workerJourney wj
        JOIN postgresql.business_labour_payroll blp ON blp.business_id = wj.businessFk
        JOIN postgresql.business_labour bl ON bl.business_id = wj.businessFk
        JOIN postgresql.calendar_labour_type pclt ON pclt.calendar_labour_type_id = bl.calendar_labour_type_id
        SET wj.priceOrdinaryHour = (12 * blp.importepactado) / (52 * pclt.hours_week),
			wj.contractJourney = pclt.hours_week/5
		WHERE wj.dated BETWEEN vFromDate AND vToDate
			AND vUserFk IN (0,wj.userFk)
            AND wj.isPaid = FALSE  
            AND isUpdated = FALSE;
            
	-- Precio Extras, Vacaciones y Nocturnas 
    UPDATE vn.workerJourney wj
		JOIN 
			(    
			SELECT dated, hollidayInc, nightInc, extraInc
				FROM (
						SELECT tm.dated , hollidayInc, nightInc, extraInc
							FROM vn.time tm
								JOIN vn.workerHourPrice whp ON tm.dated >= whp.dated
							ORDER BY tm.dated, whp.dated DESC
					  ) sub
				GROUP BY dated
			) conv ON conv.dated = wj.dated
		SET wj.priceHollydayHour = wj.priceOrdinaryHour * conv.hollidayInc,
			wj.priceNocturnHour = wj.priceOrdinaryHour * conv.nightInc,
            wj.priceExtraHour = wj.priceOrdinaryHour * conv.extraInc
		WHERE wj.dated BETWEEN vFromDate AND vToDate
			AND vUserFk IN (0,wj.userFk)
            AND wj.isPaid = FALSE  
            AND wj.isUpdated = FALSE;
        
	-- Bajas, vacaciones y festivos personales
    UPDATE vn.workerJourney wj
		JOIN postgresql.calendar_employee pce ON pce.date = wj.dated AND pce.business_id = wj.businessFk
		JOIN postgresql.business_labour bl ON bl.business_id = wj.businessFk
        SET wj.permission = IF(pce.calendar_state_id = 6, 0.5, 1) * wj.contractJourney, 
			wj.contractJourney = IF(pce.calendar_state_id = 6, 0.5, 0) * wj.contractJourney,-- Vacaciones medio dia
			wj.hollyday = wj.total - IF(pce.calendar_state_id = 6, 0.5, 0) * wj.contractJourney
		WHERE wj.dated BETWEEN vFromDate AND vToDate
			AND vUserFk IN (0,wj.userFk)
            AND wj.isPaid = FALSE  
            AND wj.isUpdated = FALSE;
            
	-- Festivos por centro de trabajo
      UPDATE vn.workerJourney wj
		JOIN postgresql.calendar_labour pcl ON pcl.day = wj.dated
        JOIN postgresql.business_labour pbl ON wj.businessFk = pbl.business_id AND pbl.workcenter_id = pcl.workcenter_id 
		SET wj.hollyday = wj.total,
			wj.permission = wj.contractJourney,
			wj.contractJourney = 0
		WHERE wj.dated BETWEEN vFromDate AND vToDate
			AND vUserFk IN (0,wj.userFk)
            AND wj.isPaid = FALSE  
            AND wj.isUpdated = FALSE;
        
	-- Domingos
	 UPDATE vn.workerJourney 
		SET hollyday = total,
			contractJourney = 0
		WHERE weekday(dated) = 6
        AND dated BETWEEN vFromDate AND vToDate
			AND vUserFk IN (0,userFk)
            AND isPaid = FALSE  
            AND isUpdated = FALSE;
	
    -- Sábados
	 UPDATE vn.workerJourney 
		SET contractJourney = 0
		WHERE weekday(dated) = 5
        AND dated BETWEEN vFromDate AND vToDate
			AND vUserFk IN (0,userFk)
            AND isPaid = FALSE  
            AND isUpdated = FALSE;
            
            
	-- Horas extras
    UPDATE workerJourney 
		SET extra =  lunch + total - contractJourney  
        WHERE dated BETWEEN vFromDate AND vToDate
			AND vUserFk IN (0,userFk)
            AND isPaid = FALSE  
            AND isUpdated = FALSE;
            
	-- Contratos NO por horas
    INSERT IGNORE INTO workerJourney(	userFk, 
										dated, 
                                        businessFk, 
                                        priceOrdinaryHour, 
                                        contractJourney, 
                                        total)
		SELECT 	w.userFk, 
				tm.dated, 
                b.business_id, 
                (12 * blp.importepactado) / (52 * pclt.hours_week) as priceOrdinaryHour,
                IF(weekday(tm.dated) IN (5,6),0, pclt.hours_week/5) as contractJourney,
                IF(weekday(tm.dated) IN (5,6),0, pclt.hours_week/5) as total
			FROM vn.worker w
				JOIN postgresql.person pe ON pe.id_trabajador = w.id
				JOIN postgresql.profile p ON p.person_id = pe.person_id
				JOIN postgresql.business b ON b.client_id = p.profile_id
				JOIN postgresql.business_labour bl ON bl.business_id = b.business_id
                JOIN postgresql.calendar_labour_type pclt ON pclt.calendar_labour_type_id = bl.calendar_labour_type_id
                JOIN postgresql.business_labour_payroll blp ON blp.business_id = b.business_id
				JOIN vn.time tm ON tm.dated BETWEEN   b.date_start AND IFNULL(b.date_end,CURDATE())
			WHERE b.date_start <= vToDate
				AND IFNULL(b.date_end, CURDATE()) >= vFromDate
				AND bl.porhoras = FALSE
				AND vUserFk IN (0,w.userFk);
                
		-- Elimina dias sin fichadas ni contrato
   /* DELETE FROM workerJourney 
		WHERE contractJourney = 0 
			AND total = 0
            AND permission = 0
            AND dated BETWEEN vFromDate AND vToDate
			AND vUserFk IN (0,userFk)
            AND isPaid = FALSE  
            AND isUpdated = 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 `workerJourneyReplaceLauncher` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `workerJourneyReplaceLauncher`()
BEGIN

	DECLARE vDateStart DATE;
    DECLARE vDateEnd DATE;
    
    SET vDateStart = TIMESTAMPADD(MONTH,-1,CURDATE());
    SET vDateEnd = util.yesterday();

	CALL vn.workerJourneyReplace(vDateStart,vDateEnd,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 `workerTimeControlAdd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControlAdd`(IN vUserFk INT, IN vWarehouseFk INT, IN vDated DATETIME)
BEGIN

	INSERT INTO workerTimeControl(userFk, timed, manual, warehouseFk)
		VALUES(vUserFk, vDated, TRUE, vWarehouseFk);
        
	CALL vn.workerTimeControlSOWP(vUserFk , vDated);
 

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

    SELECT wtc.userFk, date(wtc.timed) as Fecha , COUNT(wtc.`order`) as maxOrder, c.name as worker, wb.code as Boss, CONCAT (au.name, "@verdnatura.es") AS bossMail
        FROM workerTimeControl wtc
            JOIN worker w ON w.userFk = wtc.userFk
            LEFT JOIN worker wb ON wb.id = w.bossFk 
            JOIN client c ON c.id = wtc.userFk
            LEFT JOIN account.user au ON au.id = wb.userFK
       WHERE timed BETWEEN TIMESTAMPADD(YEAR,-5,CURDATE()) AND  CURDATE()
        GROUP BY userFk, date(timed)
       HAVING maxOrder mod 2 = 1
		ORDER BY Boss;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControlSetOrder` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControlSetOrder`()
BEGIN

	SET @order := 1;
	SET @userFk := 0;
	SET @day := 0;

	UPDATE tmp.workerTimeControl
		SET `order` = IF(userFk = @userFk AND day(timed) = @day, @order := @order + 1, @order := 1),
			userFk = @userFk := userFk,
			manual = manual + (0 * @day := day(timed))
		ORDER BY userFk, timed;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControlSOWP` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControlSOWP`(IN vUserFk INT, IN vDated DATE)
BEGIN
		SET @order := 0;
	
		UPDATE workerTimeControl 
			SET `order` =  @order := @order + 1 
			WHERE vUserFk =userFk  
            AND vDated = DATE(timed)
			ORDER BY timed;
            
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `worker_getHierarch` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `worker_getHierarch`(vBoss INT)
BEGIN
    DECLARE EXIT HANDLER FOR 1062 BEGIN
		CALL util.throw('INFINITE_LOOP');
    END;

	DROP TEMPORARY TABLE IF EXISTS workerHierarch;
	CREATE TEMPORARY TABLE workerHierarch
		(PRIMARY KEY (workerFk))
		ENGINE = MEMORY
		SELECT vBoss AS workerFk;
            
	DROP TEMPORARY TABLE IF EXISTS tmp.workerHierarchList;
	CREATE TEMPORARY TABLE tmp.workerHierarchList
		(PRIMARY KEY (workerFk))
		ENGINE = MEMORY
		SELECT vBoss AS workerFk, 0 AS isChecked;


    WHILE (SELECT COUNT(*) FROM tmp.workerHierarchList WHERE NOT isChecked) > 0 DO

	INSERT INTO tmp.workerHierarchList
		SELECT w.id, 0 
			FROM worker w
				JOIN workerHierarch wh ON wh.workerFk = w.bossFk;

	UPDATE tmp.workerHierarchList whl
			JOIN workerHierarch wh ON  wh.workerFk = whl.workerFk
		SET whl.isChecked = 1;

	TRUNCATE workerHierarch;

	INSERT INTO workerHierarch
		SELECT workerFk 
			FROM tmp.workerHierarchList
			WHERE NOT isChecked;

    END WHILE;
    
    DROP TEMPORARY TABLE IF EXISTS workerHierarch;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 `wrongEqualizatedClient` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `wrongEqualizatedClient`()
BEGIN
	SELECT clientFk, c.name, c.isActive, c.isTaxDataChecked, count(ie) as num
	FROM vn.client c
		JOIN 
		(
		SELECT DISTINCT 
				`a`.`clientFk` ,
				 a.isEqualizated = 0 as ie
				
			FROM
				`vn`.`address` `a`
		) sub ON sub.clientFk = c.id
		WHERE c.hasToInvoiceByAddress = FALSE
        
		GROUP BY clientFk
		HAVING num > 1
	UNION ALL
    SELECT DISTINCT c.id, c.name, c.isActive, c.isTaxDataChecked,1
			FROM
				`vn`.`address` `a`
				JOIN `vn`.`client` `c` ON `c`.`id` = `a`.`clientFk`
			WHERE ABS(a.isEqualizated) <> ABS(c.isEqualizated)
            AND c.hasToInvoiceByAddress = 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 `xdiarioNextId` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `xdiarioNextId`()
BEGIN
 DECLARE vNewAsien INT;
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
        ROLLBACK;
        RESIGNAL;
    END;

 START TRANSACTION;
    
    SELECT nasiento + 1 INTO vNewAsien FROM vn2008.tblContadores FOR UPDATE;
    UPDATE vn2008.tblContadores SET nasiento = vNewAsien;
    COMMIT;

    SELECT vNewAsien;
	
	DROP TEMPORARY TABLE IF EXISTS tmp.xdiarioNextId;
	CREATE TEMPORARY TABLE tmp.xdiarioNextId AS
		SELECT vNewAsien ;
	
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zoneGetAgency` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetAgency`(vAddress INT, vLanded DATE)
BEGIN
/**
 * Devuelve el listado de agencias disponibles para la fecha 
 * y dirección pasadas.
 *
 * @param vAddress Id de dirección de envío, %NULL si es recogida
 * @param vDate Fecha de recogida
 * @select Listado de agencias disponibles
 */
 
 	DECLARE vPostalCode varchar(10);

	SELECT postalCode INTO vPostalCode 
		FROM address WHERE id = vAddress;

	/*DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetAgency;
	CREATE TEMPORARY TABLE tmp.zoneGetAgency
			(INDEX (agencyModeFk)) ENGINE = MEMORY*/
		SELECT * FROM (
			SELECT am.id agencyModeFk, 
					am.name agencyMode, 
					am.description, 
					am.deliveryMethodFk,
					TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped,
                    zi.isIncluded,
                    z.warehouseFk
				FROM zoneGeo zgSon
					JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt
					JOIN zoneIncluded zi ON zi.geoFk = zgFather.id
					JOIN zone z ON z.id = zi.zoneFk
					JOIN zoneCalendar zc ON zc.zoneFk = z.id
					JOIN agencyMode am ON am.id = z.agencyModeFk
				WHERE zgSon.`name` LIKE vPostalCode
					AND zc.delivered = vLanded
					AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE)
				ORDER BY zgFather.depth DESC) t 
			GROUP BY agencyModeFk 
			HAVING isIncluded > 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 `zoneGetFirstShipped` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetFirstShipped`(vAgencyModeFk INT, vAddress INT, vWarehouseFk INT)
BEGIN
/**
* Devuelve la primera fecha de envio disponible para una agencia en una direccion y un warehouse
*
* @param vAgencyMode id de la agencia en  vn.agencyMode
* @param vAddress id de la direccion
* @param vWarehouse id del warehouse
* @return vShipped la primera fecha disponible y vLanded la fecha de llegada/recojida
*/    

	DECLARE vPostalCode varchar(10);

	SELECT postalCode INTO vPostalCode 
		FROM address WHERE id = vAddress;

	SELECT * FROM (
		SELECT TIMESTAMPADD(DAY,-z.travelingDays, zc.delivered) shipped, 
				zc.delivered landed
			FROM zoneGeo zgSon
				JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt
				JOIN zoneIncluded zi ON zi.geoFk = zgFather.id
				JOIN zone z ON z.id = zi.zoneFk
				JOIN zoneCalendar zc ON zc.zoneFk = z.id
			WHERE zgSon.`name` LIKE vPostalCode
                AND z.agencyModeFk = vAgencyModeFk
                AND  z.warehouseFk = vWarehouseFk
				AND IF(TIMESTAMPADD(DAY,-z.travelingDays, zc.delivered) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE)
			ORDER BY landed ASC, zgFather.depth DESC) t 
		HAVING isIncluded > 0 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 `zoneGetLanded` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetLanded`(vShipped DATE, vAddress INT, vAgencyMode INT, vWarehouse INT)
BEGIN
/**
* Devuelve una tabla temporal con el dia de recepcion para vShipped.
*
* @param vShipped Fecha de preparacion de mercancia
* @param vAddress Id de consignatario, %NULL para recogida
* @param vAgencyMode Id agencia
* @table tmp.zoneGetLanded Datos de recepción
*/
	DECLARE vPostalCode varchar(10);

	SELECT postalCode INTO vPostalCode 
		FROM address WHERE id = vAddress;
        
	DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded;
	CREATE TEMPORARY TABLE tmp.zoneGetLanded
			ENGINE = MEMORY
		SELECT vWarehouse warehouseFk,delivered landed, isIncluded, id zoneFk FROM (
			SELECT zi.isIncluded, zc.delivered, z.id
				FROM vn.zoneGeo zgSon
					JOIN vn.zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt
					JOIN zoneIncluded zi ON zi.geoFk = zgFather.id
					JOIN zone z ON z.id = zi.zoneFk
					JOIN zoneCalendar zc ON zc.zoneFk = z.id
				WHERE zgSon.`name` LIKE vPostalCode
					AND zc.delivered = TIMESTAMPADD(DAY,z.travelingDays, vShipped)
					AND IF(vShipped = CURDATE(), hour(now()) < hour(z.`hour`),TRUE)
					AND z.agencyModeFk = vAgencyMode
                    AND z.warehouseFk = vWarehouse
				ORDER BY zgFather.depth DESC) t 
			GROUP BY zoneFk
			HAVING isIncluded > 0 
			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 `zoneGetShipped` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShipped`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT)
BEGIN
/**
 * Devuelve la mínima fecha de envía para cada warehouse
 * 
 * @param vLanded La fecha de recepcion
 * @param vAddressFk Id del consignatario
 * @param vAgencyModeFk Id de la agencia
 * @return tmp.zoneGetShipped
 */

	DECLARE vPostalCode varchar(10);

	SELECT postalCode INTO vPostalCode 
		FROM address WHERE id = vAddressFk;

	SELECT * FROM (
		SELECT z.id,
				TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, 
				vLanded landed,
                zi.isIncluded
			FROM zoneGeo zgSon
				JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt
				JOIN zoneIncluded zi ON zi.geoFk = zgFather.id
				JOIN zone z ON z.id = zi.zoneFk
				JOIN zoneCalendar zc ON zc.zoneFk = z.id
			WHERE zgSon.`name` LIKE vPostalCode
				AND zc.delivered = vLanded
                AND z.agencyModeFk = vAgencyModeFk
                AND z.warehouseFk = vWarehouseFk
				AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE)
			ORDER BY z.id, landed ASC, zgFather.depth DESC) t 
		GROUP BY id
		HAVING isIncluded > 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 `zoneGetWarehouse` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetWarehouse`(vAddress INT, vLanded DATE, vWarehouse INT)
BEGIN
/**
* Devuelve el listado de agencias disponibles para la fecha,
 * dirección y warehouse pasadas
 * 
 * @param vAddress
 * @param vWarehouse warehouse
 * @param vLanded Fecha de recogida
 * @select Listado de agencias disponibles
 */
 
 	DECLARE vPostalCode varchar(10);

	SELECT postalCode INTO vPostalCode 
		FROM address WHERE id = vAddress;

	SELECT * FROM (
		SELECT am.id, 
				am.name agencyMode, 
				am.description, 
				am.deliveryMethodFk,
				TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, 
				z.warehouseFk,
                zi.isIncluded
			FROM zoneGeo zgSon
				JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt
				JOIN zoneIncluded zi ON zi.geoFk = zgFather.id
				JOIN zone z ON z.id = zi.zoneFk
				JOIN zoneCalendar zc ON zc.zoneFk = z.id
				JOIN agencyMode am ON am.id = z.agencyModeFk
			WHERE zgSon.`name` LIKE vPostalCode
				AND delivered = vLanded
                AND z.warehouseFk = vWarehouse
				AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE)
			ORDER BY zgFather.depth DESC) t 
		GROUP BY id 
		HAVING isIncluded > 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 `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              = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zoneNest`()
BEGIN  
	DROP TEMPORARY TABLE IF EXISTS tmp.zoneGeo;
	CREATE TEMPORARY TABLE tmp.zoneGeo 
		(id INT AUTO_INCREMENT PRIMARY KEY)
		ENGINE = MEMORY
		SELECT * FROM vn.zoneGeo;
	
	DROP TEMPORARY TABLE IF EXISTS tmp.country;
	CREATE TEMPORARY TABLE tmp.country 
		SELECT id FROM country 
	 		WHERE country IN('España', 'Francia', 'Holanda', 'Portugal');

	CALL vn.zoneNestCountry();
	CALL vn.zoneNestProvince();
	CALL vn.zoneNestTown();
	CALL vn.zoneNestPostcode();
	
    CALL vn.nestTree('tmp', 'zoneGeo', 'vn', 'zoneGeo');
		
	DROP TEMPORARY TABLE tmp.zoneGeo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zoneNestCountry` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zoneNestCountry`()
BEGIN

	DECLARE vDone BOOL;
    DECLARE vParent INT DEFAULT 1;
    DECLARE vGeoFk INT;
    DECLARE vChildFk INT;
    DECLARE vChildName VARCHAR(100);
			
	DECLARE countryCur CURSOR FOR
		SELECT 1, c.id, c.`country`
	        FROM vn.country c 
	        	JOIN tmp.country tc ON tc.id = c.id
			ORDER BY c.`country`;
			
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

	-- > Country cursor start
	OPEN countryCur;
	
	countryLoop: LOOP
		SET vDone = FALSE;
        
		FETCH countryCur INTO vParent, vChildFk, vChildName;
		
		IF vDone THEN
			LEAVE countryLoop;
		END IF;
		
		CALL nestAdd('tmp', 'zoneGeo', vParent, vChildName);
		
		-- Update country geoFk
        -- SET vGeoFk = LAST_INSERT_ID();
        -- UPDATE country SET geoFk = vGeoFk WHERE id = vChildFk;
	END LOOP;
	CLOSE countryCur;
	-- < Country cursor end
	
	UPDATE country c
		JOIN tmp.zoneGeo z ON z.name = c.country
			SET c.geoFk = z.id
		WHERE c.geoFk 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 `zoneNestPostcode` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zoneNestPostcode`()
BEGIN

	DECLARE vDone BOOL;
    DECLARE vParent INT DEFAULT 1;
    DECLARE vGeoFk INT;
    DECLARE vChildFk INT;
    DECLARE vChildName VARCHAR(100);
			
	DECLARE postcodeCur CURSOR FOR
		SELECT t.geoFk, pc.`code`, pc.`code`
			FROM vn.postCode pc 
				JOIN vn.town t ON t.id = pc.townFk
				JOIN vn.province p ON p.id = t.provinceFk
				JOIN tmp.country tc ON tc.id = p.countryFk
			ORDER BY pc.`code`;
			
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

	-- > Postcode cursor start
	OPEN postcodeCur;
	
	postcodeLoop: LOOP
		SET vDone = FALSE;
        
		FETCH postcodeCur INTO vParent, vChildFk, vChildName;
		
		IF vDone THEN
			LEAVE postcodeLoop;
		END IF;
		
		CALL nestAdd('tmp', 'zoneGeo', vParent, vChildName);
		
		-- Update postcode geoFk
        -- SET vGeoFk = LAST_INSERT_ID();
        -- UPDATE vn.postCode SET geoFk = vGeoFk WHERE `code` = vChildFk;
	END LOOP;
	CLOSE postcodeCur;
	-- < Postcode cursor end
	
	UPDATE postCode p
		JOIN tmp.zoneGeo z ON z.name = p.code
			SET p.geoFk = z.id
		WHERE p.geoFk 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 `zoneNestProvince` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zoneNestProvince`()
BEGIN

	DECLARE vDone BOOL;
    DECLARE vParent INT DEFAULT 1;
    DECLARE vGeoFk INT;
    DECLARE vChildFk INT;
    DECLARE vChildName VARCHAR(100);
			
	DECLARE provinceCur CURSOR FOR
		SELECT c.geoFk, p.id, p.`name`
			FROM province p 
				JOIN tmp.country tc ON tc.id = p.countryFk
				JOIN vn.country c ON c.id = tc.id
			ORDER BY p.`name`;
			
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
	
	-- > Province cursor start
	OPEN provinceCur;
	
	provinceLoop: LOOP
		SET vDone = FALSE;
        
		FETCH provinceCur INTO vParent, vChildFk, vChildName;
		
		IF vDone THEN
			LEAVE provinceLoop;
		END IF;
		
		CALL nestAdd('tmp', 'zoneGeo', vParent, vChildName);
		
		-- Update province geoFk
        -- SET vGeoFk = LAST_INSERT_ID();
        -- UPDATE province SET geoFk = vGeoFk WHERE id = vChildFk;
	END LOOP;
	CLOSE provinceCur;
	-- < Province cursor end
	
	UPDATE province p
		JOIN tmp.zoneGeo z ON z.name = p.name
			SET p.geoFk = z.id
		WHERE p.geoFk 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 `zoneNestTown` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zoneNestTown`()
BEGIN

	DECLARE vDone BOOL;
    DECLARE vParent INT DEFAULT 1;
    DECLARE vGeoFk INT;
    DECLARE vChildFk INT;
    DECLARE vChildName VARCHAR(100);
			
	DECLARE townCur CURSOR FOR
		SELECT p.geoFk, t.id, t.`name`
			FROM vn.town t 
				JOIN vn.province p ON p.id = t.provinceFk
				JOIN tmp.country tc ON tc.id = p.countryFk
			ORDER BY t.`name`;
			
	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('tmp', 'zoneGeo', 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
	
	UPDATE town t
		JOIN tmp.zoneGeo z ON z.name = t.name
		LEFT JOIN province p ON p.geoFk = z.id
			SET t.geoFk = z.id
		WHERE p.geoFk 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 */ ;

--
-- Current Database: `vn2008`
--

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

USE `vn2008`;

--
-- Table structure for table `Agencias`
--

DROP TABLE IF EXISTS `Agencias`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Agencias` (
  `Id_Agencia` int(11) NOT NULL AUTO_INCREMENT,
  `Agencia` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `description` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Vista` int(11) DEFAULT '0',
  `m3` double DEFAULT '0',
  `cod71` tinyint(3) unsigned DEFAULT '0',
  `web` smallint(1) unsigned zerofill NOT NULL DEFAULT '0',
  `agency_id` smallint(6) NOT NULL,
  `agency_service_id` tinyint(4) NOT NULL DEFAULT '1',
  `inflacion` decimal(5,2) NOT NULL DEFAULT '0.00' COMMENT 'Este valor se utiliza para aumentar el valor del componente porte.',
  `is_volumetric` tinyint(1) NOT NULL DEFAULT '0',
  `send_mail` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `show_AgencyName` tinyint(1) DEFAULT '1',
  `tpv` tinyint(1) NOT NULL DEFAULT '1',
  `externalAgency` tinyint(1) NOT NULL DEFAULT '0',
  `flag` blob,
  `code` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`Id_Agencia`),
  KEY `Agencias` (`Agencia`),
  KEY `Vista` (`Vista`)
) ENGINE=InnoDB AUTO_INCREMENT=1226 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Agencias_dits`
--

DROP TABLE IF EXISTS `Agencias_dits`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Agencias_dits` (
  `idAgencia_dits` int(11) NOT NULL AUTO_INCREMENT,
  `idaccion_dits` int(11) NOT NULL,
  `ODBC_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `Id_Ticket` int(11) NOT NULL,
  `Id_Trabajador` int(11) NOT NULL,
  `value_old` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value_new` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`idAgencia_dits`)
) ENGINE=InnoDB AUTO_INCREMENT=39926 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Agencias_province`
--

DROP TABLE IF EXISTS `Agencias_province`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Agencias_province` (
  `province_id` smallint(6) unsigned NOT NULL,
  `agency_id` smallint(5) unsigned NOT NULL,
  `zona` tinyint(4) NOT NULL,
  `warehouse_id` smallint(6) unsigned NOT NULL,
  `route` tinyint(4) NOT NULL COMMENT 'Etiqueta zeleris',
  `isVolumetric` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`province_id`,`agency_id`,`warehouse_id`),
  KEY `warehouse_id` (`warehouse_id`),
  KEY `agency_id` (`agency_id`),
  CONSTRAINT `Agencias_province_ibfk_1` FOREIGN KEY (`province_id`) REFERENCES `province` (`province_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `Agencias_province_ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `Agencias_province_ibfk_3` FOREIGN KEY (`agency_id`) REFERENCES `agency` (`agency_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 `Agencias_zonas`
--

DROP TABLE IF EXISTS `Agencias_zonas`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Agencias_zonas` (
  `Id_Agencia` int(11) NOT NULL,
  `zona` tinyint(4) NOT NULL,
  `price` double NOT NULL,
  `Id_Article` int(10) NOT NULL DEFAULT '71',
  `warehouse_id` smallint(6) NOT NULL DEFAULT '1',
  `porte_minimo` tinyint(1) NOT NULL DEFAULT '0',
  `inflacion` decimal(5,2) NOT NULL DEFAULT '1.00',
  PRIMARY KEY (`Id_Agencia`,`zona`,`Id_Article`,`warehouse_id`),
  KEY `Id_Article` (`Id_Article`),
  CONSTRAINT `Agencias_zonas_ibfk_1` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `Agencias_zonas_ibfk_2` FOREIGN KEY (`Id_Agencia`) REFERENCES `Agencias` (`Id_Agencia`) 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 `Articles`
--

DROP TABLE IF EXISTS `Articles`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Articles` (
  `Id_Article` int(11) NOT NULL AUTO_INCREMENT,
  `Equivalente` int(11) unsigned DEFAULT NULL,
  `Article` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Medida` int(10) unsigned DEFAULT NULL,
  `Tallos` int(11) DEFAULT '1',
  `PVP` double DEFAULT '0',
  `Imprimir` tinyint(1) NOT NULL DEFAULT '0',
  `Albaranero` tinyint(1) NOT NULL DEFAULT '0',
  `iva_group_id` tinyint(4) unsigned NOT NULL DEFAULT '1',
  `Familia` varchar(3) COLLATE utf8_unicode_ci DEFAULT 'VT',
  `caja` tinyint(1) NOT NULL DEFAULT '0',
  `Categoria` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `id_origen` tinyint(2) unsigned NOT NULL,
  `do_photo` tinyint(4) NOT NULL DEFAULT '0',
  `Foto` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Color` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Nicho` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Codintrastat` int(8) unsigned zerofill DEFAULT NULL,
  `Min` tinyint(1) NOT NULL DEFAULT '0',
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `offer` tinyint(4) NOT NULL DEFAULT '0',
  `bargain` tinyint(4) NOT NULL DEFAULT '0',
  `comments` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'renombrar: reference',
  `tipo_id` smallint(5) unsigned NOT NULL,
  `generic` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0',
  `producer_id` mediumint(3) unsigned DEFAULT NULL,
  `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `density` double NOT NULL DEFAULT '167' COMMENT 'Almacena la densidad en kg/m3 para el calculo de los portes, si no se especifica se pone por defecto la del tipo en un trigger',
  `relevancy` tinyint(1) NOT NULL DEFAULT '0',
  `expenceFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT '7001000000',
  `isActive` tinyint(1) NOT NULL DEFAULT '1',
  `longName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `subName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `tag5` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value5` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `tag6` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value6` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `tag7` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value7` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `tag8` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value8` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `tag9` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value9` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `tag10` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value10` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `compression` decimal(5,2) NOT NULL DEFAULT '1.00' COMMENT 'Relacion de compresividad entre el volumen de las entradas en Silla y el empaquetado en los envios a clientes.\n\nMenor que 1 significa que se puede comprimir más que el volumen original.',
  `minimum` decimal(10,0) unsigned NOT NULL DEFAULT '3',
  `upToDown` decimal(10,0) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`Id_Article`),
  KEY `Article` (`Article`),
  KEY `Color` (`Color`),
  KEY `id_origen` (`id_origen`),
  KEY `Codintrastat` (`Codintrastat`),
  KEY `iva_group_id` (`iva_group_id`),
  KEY `tipo_id` (`tipo_id`),
  KEY `producer_id` (`producer_id`),
  KEY `expenceFk_idx` (`expenceFk`),
  KEY `ArticlesIsActive_idx` (`isActive`),
  CONSTRAINT `Articles_ibfk_1` FOREIGN KEY (`id_origen`) REFERENCES `Origen` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `Articles_ibfk_2` FOREIGN KEY (`Codintrastat`) REFERENCES `Intrastat` (`Codintrastat`) ON UPDATE CASCADE,
  CONSTRAINT `Articles_ibfk_4` FOREIGN KEY (`iva_group_id`) REFERENCES `iva_group` (`iva_group_id`) ON UPDATE CASCADE,
  CONSTRAINT `Articles_ibfk_5` FOREIGN KEY (`tipo_id`) REFERENCES `Tipos` (`tipo_id`) ON UPDATE CASCADE,
  CONSTRAINT `expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `Gastos` (`Id_Gasto`) ON UPDATE CASCADE,
  CONSTRAINT `producer_id` FOREIGN KEY (`producer_id`) REFERENCES `producer` (`producer_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=350407 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 `vn2008`.`ArticlesBeforeInsert`
	BEFORE INSERT ON `Articles` FOR EACH ROW
BEGIN

	DECLARE vDensity DOUBLE;
	DECLARE vInsertId INT;
	DECLARE vProducerFk VARCHAR(50);
    DECLARE vInkName VARCHAR(50);

	IF NEW.density IS NULL
	THEN
		SELECT density INTO vDensity
			FROM Tipos WHERE tipo_id = NEW.tipo_id;

		SET NEW.density = vDensity;
	END IF;

	IF NEW.Foto IS NULL
	THEN
		SELECT `auto_increment` INTO vInsertId
			FROM `information_schema`.TABLES    
			WHERE `table_name` = 'Articles'
				AND `table_schema` = DATABASE();

		SET NEW.Foto = vInsertId;
	END IF;
    
	-- SET NEW.longName = NEW.Article;
    
	-- MIGRACION
  /*  IF NEW.producer_id is not null THEN
		SELECT name INTO vProducerFk FROM producer WHERE producer_id = NEW.producer_id;
        SET NEW.subname = vProducerFk;
    END IF;
    
    IF NEW.Medida IS NOT NULL AND NEW.value5 IS NULL THEN
		SET NEW.tag5 ='Medida'; 
        SET NEW.value5 = NEW.medida;
	END IF;
    
    IF NEW.Color IS NOT NULL AND NEW.value6 IS NULL THEN
		SET NEW.tag6 ='Color'; 
        SELECT name INTO vInkName FROM vn.ink i where i.id = NEW.Color;
        SET NEW.value6 = vInkName;
	END IF;

	IF NEW.Categoria IS NOT NULL AND NEW.value7 IS NULL THEN
		SET NEW.tag7 ='Categoria'; 
        SET NEW.value7 = NEW.Categoria;
	END IF;

	IF NEW.Tallos IS NOT NULL AND NEW.value8 IS NULL THEN
		SET NEW.tag8 ='Tallos'; 
        SET NEW.value8 = NEW.Tallos;
	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 `vn2008`.`Articles_AFTER_INSERT` AFTER INSERT ON `Articles` FOR EACH ROW
BEGIN

    INSERT INTO vn.itemTaxCountry(itemFk, countryFk, taxClassFk)
        SELECT NEW.Id_Article, 1, NEW.iva_group_id;
        
    INSERT INTO vn.itemTaxCountry(itemFk, countryFk, taxClassFk)
        SELECT NEW.Id_Article, 5, NEW.iva_group_id;
    
    INSERT INTO vn.itemTaxCountry(itemFk, countryFk, taxClassFk)
        SELECT NEW.Id_Article, 30, NEW.iva_group_id;
  /*      
    IF NEW.tipo_id IS NOT NULL THEN
        INSERT INTO vn.itemTag (itemFk, tagFk, priority)
            SELECT NEW.Id_Article, tagFk, priority FROM vn.itemTypeTag 
                WHERE itemTypeFk = NEW.tipo_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 */ ;

--
-- Table structure for table `Articles_botanical`
--

DROP TABLE IF EXISTS `Articles_botanical`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Articles_botanical` (
  `Id_Article` int(11) NOT NULL,
  `botanical` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `genus_id` mediumint(8) unsigned DEFAULT NULL,
  `specie_id` mediumint(8) unsigned DEFAULT NULL,
  PRIMARY KEY (`Id_Article`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Sustituye a antiguo NomBotanic de Articles';
/*!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 `Articles_botanical_bi` BEFORE INSERT ON `Articles_botanical` FOR EACH ROW
BEGIN
	IF NEW.botanical = '' THEN
		SET NEW.botanical = 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 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `Articles_botanical_bu` BEFORE UPDATE ON `Articles_botanical` FOR EACH ROW
BEGIN
	IF NEW.botanical = '' THEN
		SET NEW.botanical = 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 `Articles_dits`
--

DROP TABLE IF EXISTS `Articles_dits`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Articles_dits` (
  `idArticles_dits` int(11) NOT NULL AUTO_INCREMENT,
  `idaccion_dits` int(11) NOT NULL,
  `ODBC_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `Id_Ticket` int(11) NOT NULL,
  `Id_Trabajador` int(11) NOT NULL,
  `value_old` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value_new` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`idArticles_dits`),
  KEY `fgkey1_idx` (`idaccion_dits`),
  KEY `fgkey2_idx` (`Id_Ticket`),
  KEY `fgkey3_idx` (`Id_Trabajador`)
) ENGINE=InnoDB AUTO_INCREMENT=21430 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Articles_nicho`
--

DROP TABLE IF EXISTS `Articles_nicho`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Articles_nicho` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Article` int(11) NOT NULL,
  `warehouse_id` smallint(6) unsigned NOT NULL DEFAULT '1',
  `nicho` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `modificationDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `reserve` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `pickable` int(11) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `Id_Article_UNIQUE` (`Id_Article`,`warehouse_id`),
  KEY `Articles_nicho_wh_fk` (`warehouse_id`),
  CONSTRAINT `Articles_nicho_wh_fk` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `Articles_nichos_fk` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=777965 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Baldas`
--

DROP TABLE IF EXISTS `Baldas`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Baldas` (
  `Id_Estanterias` int(11) NOT NULL,
  `Id_Baldas` int(11) NOT NULL,
  `h` int(11) NOT NULL,
  PRIMARY KEY (`Id_Estanterias`,`Id_Baldas`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Bancos`
--

DROP TABLE IF EXISTS `Bancos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Bancos` (
  `Id_Banco` int(11) NOT NULL DEFAULT '0',
  `Banco` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Cuenta` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `cash` smallint(6) NOT NULL DEFAULT '0',
  `warehouse_id` smallint(5) unsigned NOT NULL DEFAULT '1',
  `entity_id` int(10) unsigned NOT NULL,
  `activo` tinyint(4) NOT NULL DEFAULT '1',
  `currencyFk` tinyint(3) unsigned DEFAULT '1',
  PRIMARY KEY (`Id_Banco`),
  KEY `BancosBanco` (`Banco`),
  KEY `fk_Bancos_entity1_idx` (`entity_id`),
  KEY `foreignkey1_idx` (`cash`),
  KEY `Bancoscurrency_idx` (`currencyFk`),
  CONSTRAINT `Bancoscurrency` FOREIGN KEY (`currencyFk`) REFERENCES `Monedas` (`Id_Moneda`) ON UPDATE CASCADE,
  CONSTRAINT `foreignkey1` FOREIGN KEY (`cash`) REFERENCES `vn`.`accountingType` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Apunta a la vista vn.Accounting\nLa columna cash es la FK de vn.AccountingType';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Bancos_poliza`
--

DROP TABLE IF EXISTS `Bancos_poliza`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Bancos_poliza` (
  `poliza_id` int(11) NOT NULL AUTO_INCREMENT,
  `referencia` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `importe` double NOT NULL,
  `com_dispuesto` double DEFAULT NULL,
  `com_no_dispuesto` double DEFAULT NULL,
  `com_anual` double DEFAULT NULL,
  `apertura` date NOT NULL,
  `cierre` date DEFAULT NULL,
  `Id_Banco` int(11) NOT NULL,
  `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442',
  PRIMARY KEY (`poliza_id`),
  KEY `Id_Banco_Poliza_idx` (`Id_Banco`),
  KEY `Id_Poliza_Empresa_idx` (`empresa_id`),
  CONSTRAINT `Id_Banco_Poliza` FOREIGN KEY (`Id_Banco`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE,
  CONSTRAINT `Id_Poliza_Empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=35 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Lineas de credito asociadas a cuentas corrientes';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Brasa`
--

DROP TABLE IF EXISTS `Brasa`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Brasa` (
  `Id_Cliente` int(10) unsigned NOT NULL DEFAULT '0',
  `Cliente` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `Vista` int(10) unsigned NOT NULL DEFAULT '0',
  `Reg` bigint(21) unsigned NOT NULL DEFAULT '0',
  `Consumo` double NOT NULL,
  `Grupo` int(10) unsigned NOT NULL,
  PRIMARY KEY (`Id_Cliente`),
  KEY `Index_1` (`Id_Cliente`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Cajas`
--

DROP TABLE IF EXISTS `Cajas`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Cajas` (
  `Id_Caja` int(11) NOT NULL AUTO_INCREMENT,
  `Cajafecha` date NOT NULL,
  `Partida` tinyint(1) NOT NULL DEFAULT '0',
  `Serie` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Numero` int(11) DEFAULT NULL,
  `Concepto` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `Entrada` decimal(10,2) DEFAULT NULL,
  `Salida` decimal(10,2) DEFAULT NULL,
  `Id_Banco` int(11) DEFAULT '1',
  `Id_Trabajador` int(11) DEFAULT NULL,
  `empresa_id` smallint(5) unsigned DEFAULT '442' COMMENT 'kakear',
  `linked` tinyint(4) DEFAULT '0',
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `ok` tinyint(4) NOT NULL DEFAULT '0',
  `warehouse_id` smallint(5) unsigned NOT NULL DEFAULT '1' COMMENT 'to kak\n',
  `conciliado` tinyint(4) NOT NULL DEFAULT '0',
  `Proveedores_account_Id` mediumint(8) unsigned NOT NULL,
  `id_calculated` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `InForeignValue` decimal(10,2) DEFAULT NULL,
  `OutForeignValue` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`Id_Caja`),
  UNIQUE KEY `id_calculated_UNIQUE` (`id_calculated`),
  KEY `CajasCajafecha` (`Cajafecha`),
  KEY `Id_Banco` (`Id_Banco`),
  KEY `Id_Trabajador` (`Id_Trabajador`),
  KEY `empresa_id` (`empresa_id`),
  KEY `warehouse_id` (`warehouse_id`),
  KEY `fk_Cajas_Proveedores_account1_idx` (`Proveedores_account_Id`),
  CONSTRAINT `Cajas_ibfk_2` FOREIGN KEY (`Id_Banco`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=688389 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 `vn2008`.`CajasBeforeInsert` BEFORE INSERT ON `Cajas` FOR EACH ROW
BEGIN
	IF IFNULL(NEW.Concepto,"") = "" THEN
		CALL util.throw ('Error. El concepto esta vacío');
    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 `Clases`
--

DROP TABLE IF EXISTS `Clases`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Clases` (
  `Id_Clase` int(11) NOT NULL DEFAULT '0',
  `Clase` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`Id_Clase`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Clientes`
--

DROP TABLE IF EXISTS `Clientes`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Clientes` (
  `id_cliente` int(11) NOT NULL AUTO_INCREMENT,
  `cliente` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `descuento` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `default_address` int(11) DEFAULT NULL,
  `domicilio` longtext COLLATE utf8_unicode_ci,
  `if` varchar(14) COLLATE utf8_unicode_ci DEFAULT NULL,
  `telefono` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `fax` varchar(11) COLLATE utf8_unicode_ci DEFAULT NULL,
  `e-mail` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `cc` varchar(23) COLLATE utf8_unicode_ci DEFAULT NULL,
  `vencimiento` smallint(6) NOT NULL DEFAULT '5',
  `recibo` int(11) DEFAULT '1' COMMENT 'Deprecated',
  `oficial` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'Deprecated',
  `contabilizado` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Deprecated',
  `movil` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Cuenta` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `RE` tinyint(1) NOT NULL DEFAULT '0',
  `poblacion` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
  `province_id` smallint(5) unsigned DEFAULT NULL,
  `codPostal` varchar(8) COLLATE utf8_unicode_ci DEFAULT NULL,
  `razonSocial` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
  `contacto` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `mayorista` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Deprecated',
  `reexpedicion` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Deprecated',
  `invoice` tinyint(1) NOT NULL DEFAULT '1',
  `notas` text COLLATE utf8_unicode_ci COMMENT 'Deprecated',
  `notas_administracion` text COLLATE utf8_unicode_ci NOT NULL COMMENT 'Deprecated',
  `copiaFactura` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Deprecated',
  `retener` tinyint(1) NOT NULL DEFAULT '0',
  `congelado` tinyint(1) NOT NULL DEFAULT '0',
  `Id_Trabajador` int(11) DEFAULT NULL,
  `credito` decimal(10,2) NOT NULL DEFAULT '0.00',
  `cyc` double DEFAULT NULL,
  `Id_Pais` mediumint(8) unsigned NOT NULL DEFAULT '1',
  `activo` tinyint(1) NOT NULL DEFAULT '1',
  `gestdoc_id` int(11) DEFAULT NULL,
  `calidad` int(2) DEFAULT '11',
  `pay_met_id` tinyint(3) unsigned NOT NULL DEFAULT '5',
  `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `mail` tinyint(1) NOT NULL DEFAULT '1',
  `chanel_id` smallint(6) DEFAULT NULL,
  `vies` tinyint(4) NOT NULL DEFAULT '0',
  `split_holland` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'eliminar',
  `sepaFth` tinyint(1) DEFAULT '0' COMMENT 'campo para recibir los escritos de los clientes para el sepa',
  `sepaVnl` tinyint(1) DEFAULT '0',
  `coreFth` tinyint(1) DEFAULT '0',
  `coreVnl` tinyint(1) DEFAULT '0',
  `risk_calculated` date NOT NULL,
  `coreVnh` tinyint(1) DEFAULT '0',
  `real` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'Define los clientes cuyas ventas hay que tener en cuenta en los calculos estadisticos.',
  `clientes_tipo_id` int(11) NOT NULL DEFAULT '1',
  `postcode_id` int(11) unsigned DEFAULT NULL,
  `mail_address` int(11) DEFAULT NULL,
  `codpos` char(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `creditInsurance` int(11) DEFAULT NULL,
  `EYPBC` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Email\nYesterday\nPurchases\nBy\nConsigna',
  `invoiceByAddress` tinyint(1) DEFAULT '0',
  `cplusTerIdNifFk` int(11) NOT NULL DEFAULT '1' COMMENT 'OBSOLETO',
  `isCreatedAsServed` tinyint(1) DEFAULT '0',
  `hasInvoiceSimplified` tinyint(1) NOT NULL DEFAULT '0',
  `iban` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `hasLcr` tinyint(1) NOT NULL DEFAULT '0',
  `bankEntityFk` int(10) DEFAULT NULL,
  `typeFk` varchar(20) CHARACTER SET utf8 NOT NULL DEFAULT 'normal',
  PRIMARY KEY (`id_cliente`),
  UNIQUE KEY `IF` (`if`),
  KEY `Id_Trabajador` (`Id_Trabajador`),
  KEY `Id_Pais` (`Id_Pais`),
  KEY `pay_met_id` (`pay_met_id`),
  KEY `canal_nuevo_cliente` (`chanel_id`),
  KEY `Cuenta` (`Cuenta`),
  KEY `province_id` (`province_id`),
  KEY `default_address` (`default_address`),
  KEY `Telefono` (`telefono`),
  KEY `movil` (`movil`),
  KEY `tipos_de_cliente_idx` (`clientes_tipo_id`),
  KEY `codpos` (`codpos`,`codPostal`),
  KEY `fk_Clientes_entity_idx` (`bankEntityFk`),
  KEY `typeFk` (`typeFk`),
  CONSTRAINT `Clientes_ibfk_1` FOREIGN KEY (`Id_Pais`) REFERENCES `Paises` (`Id`) ON UPDATE CASCADE,
  CONSTRAINT `Clientes_ibfk_2` FOREIGN KEY (`pay_met_id`) REFERENCES `pay_met` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `Clientes_ibfk_3` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `Clientes_ibfk_4` FOREIGN KEY (`default_address`) REFERENCES `Consignatarios` (`id_consigna`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `Clientes_ibfk_5` FOREIGN KEY (`province_id`) REFERENCES `province` (`province_id`) ON UPDATE CASCADE,
  CONSTRAINT `canal_nuevo_cliente` FOREIGN KEY (`chanel_id`) REFERENCES `chanel` (`chanel_id`) ON UPDATE CASCADE,
  CONSTRAINT `tipos_de_cliente` FOREIGN KEY (`clientes_tipo_id`) REFERENCES `clientes_tipo` (`clientes_tipo_id`) ON UPDATE CASCADE,
  CONSTRAINT `typeFk` FOREIGN KEY (`typeFk`) REFERENCES `clientes_tipo` (`code`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=15790 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 `ClientesBeforeInsert`
	BEFORE INSERT ON `Clientes`
	FOR EACH ROW
BEGIN
    DECLARE isAlreadyUsedIf BOOL;

    SELECT COUNT(*) INTO isAlreadyUsedIf
		FROM Clientes
		WHERE `IF` = TRIM(NEW.`IF`);

    IF isAlreadyUsedIf THEN
    	CALL util.throw ('Error. El NIF/CIF está repetido');
    END IF;

	CALL pbx.phoneIsValid (NEW.telefono);
	CALL pbx.phoneIsValid (NEW.movil);
	CALL pbx.phoneIsValid (NEW.fax);

	SET NEW.cuenta = 4300000000 + NEW.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 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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 `ClientesBeforeUpdate`
	BEFORE UPDATE ON `Clientes`
    FOR EACH ROW
BEGIN
	DECLARE vText VARCHAR(255) DEFAULT NULL;
    DECLARE isAlreadyUsedIf BOOLEAN;

    SELECT (COUNT(*) > 1) INTO isAlreadyUsedIf
		FROM Clientes
		WHERE `IF` = TRIM(NEW.`IF`);

    IF isAlreadyUsedIf THEN
    	CALL util.throw ('Error. El NIF/CIF está repetido');
    END IF;

	-- Comprueba que el formato de los teléfonos es válido

	IF !(NEW.telefono <=> OLD.telefono) THEN
		CALL pbx.phoneIsValid (NEW.telefono);
	END IF;
    
    IF !(NEW.movil <=> OLD.movil) THEN
		CALL pbx.phoneIsValid (NEW.movil);
	END IF;
    
    IF !(NEW.fax <=> OLD.fax) THEN
		CALL pbx.phoneIsValid (NEW.fax);
	END IF;

	IF NEW.pay_met_id = 4 AND NEW.Vencimiento = 0 THEN
		SET NEW.Vencimiento = 5;
    END IF;
    
	-- Avisar al comercial si ha llegado la documentación sepa/core

	IF NEW.sepavnl AND !OLD.sepavnl THEN
		SET vText = 'Sepa de VNL';
	END IF;

	IF NEW.corevnl AND !OLD.corevnl THEN
		SET vText = 'Core de VNL';
	END IF;

	IF vText IS NOT NULL
    THEN
		INSERT INTO mail(`to`, reply_to, subject, text) 
			SELECT
					CONCAT(IF(ac.id,name, 'jgallego'), '@verdnatura.es'),
                    'administracion@verdnatura.es',
                    CONCAT('Cliente ', NEW.Id_Cliente),
					CONCAT('Recibida la documentación: ', vText)
				FROM Trabajadores t
					LEFT JOIN account.user u ON t.user_id = u.id AND active
					LEFT JOIN account.account ac ON ac.id = u.id
				WHERE t.Id_Trabajador = NEW.Id_Trabajador;
	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 `vn2008`.`ClientesAfterUpdate`
AFTER UPDATE ON `Clientes` 
FOR EACH ROW
BEGIN
    IF !(NEW.default_address <=> OLD.default_address) THEN
        UPDATE Consignatarios SET predeterminada = 0
            WHERE Id_cliente = NEW.Id_cliente;
            
		UPDATE Consignatarios SET predeterminada = 1
            WHERE Id_consigna = NEW.default_address;      
    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 `Clientes_cedidos`
--

DROP TABLE IF EXISTS `Clientes_cedidos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Clientes_cedidos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Cliente` int(11) NOT NULL,
  `Id_Trabajador_old` int(11) NOT NULL,
  `Id_Trabajador_new` int(11) NOT NULL,
  `datSTART` date NOT NULL,
  `datEND` date NOT NULL,
  `comision_old` double NOT NULL DEFAULT '0.5',
  `comision_new` double NOT NULL DEFAULT '0.5',
  PRIMARY KEY (`id`),
  KEY `trabajador_fk_idx` (`Id_Trabajador_old`),
  KEY `new_trabajador_fk_idx` (`Id_Trabajador_new`),
  KEY `cliente_cedido_fk_idx` (`Id_Cliente`),
  CONSTRAINT `cliente_cedido_fk` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `new_trabajador_fk` FOREIGN KEY (`Id_Trabajador_new`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `trabajador_fk` FOREIGN KEY (`Id_Trabajador_old`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Clientes que se han cambiado de comercial, pero durante un tiempo comisionan a los dos, al anterior y al actual';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Clientes_dits`
--

DROP TABLE IF EXISTS `Clientes_dits`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Clientes_dits` (
  `idClientes_dits` int(11) NOT NULL AUTO_INCREMENT,
  `idaccion_dits` int(11) NOT NULL,
  `ODBC_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `Id_Ticket` int(11) NOT NULL,
  `Id_Trabajador` int(11) NOT NULL,
  `value_old` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value_new` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`idClientes_dits`),
  KEY `idaccion_dits` (`idaccion_dits`),
  CONSTRAINT `Clientes_dits_ibfk_1` FOREIGN KEY (`idaccion_dits`) REFERENCES `accion_dits` (`idaccion_dits`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=71674 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Clientes_empresa`
--

DROP TABLE IF EXISTS `Clientes_empresa`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Clientes_empresa` (
  `Id_Clientes_empresa` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Cliente` int(11) NOT NULL,
  `empresa_id` smallint(5) unsigned NOT NULL,
  `fecha_ini` date NOT NULL,
  `fecha_fin` date NOT NULL,
  PRIMARY KEY (`Id_Clientes_empresa`),
  KEY `empresa_id_idx` (`empresa_id`),
  CONSTRAINT `empresa_id` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON DELETE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=470507 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Empresa por defecto para crear los tickets';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Clientes_event`
--

DROP TABLE IF EXISTS `Clientes_event`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Clientes_event` (
  `Id_Cliente` int(11) NOT NULL,
  `quantity` tinyint(3) unsigned NOT NULL,
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`Id_Cliente`),
  CONSTRAINT `Clientes_event_ibfk_1` FOREIGN KEY (`Id_Cliente`) REFERENCES `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 `Clientes_potenciales`
--

DROP TABLE IF EXISTS `Clientes_potenciales`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Clientes_potenciales` (
  `id` int(11) NOT NULL,
  `PAIS` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ACTIVIDAD` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `NOMBRE` varchar(45) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `PROVINCIA` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
  `POBLACION` varchar(45) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `CP` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `DIR_POSTAL` varchar(45) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `TELEFONO` varchar(12) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `TELEFONO2` varchar(12) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `FAX` varchar(12) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `E-MAIL` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `pagweb` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `SERVICIOS` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `state_id` smallint(6) DEFAULT '0' COMMENT '0 no se ha hecho nada\n1 ya existe el cliente\n2 cliente conseguido\n3 desestimado',
  `Id_Trabajador` smallint(6) DEFAULT NULL,
  `Notas` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`NOMBRE`,`POBLACION`,`DIR_POSTAL`,`TELEFONO`,`TELEFONO2`,`FAX`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Colas`
--

DROP TABLE IF EXISTS `Colas`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Colas` (
  `Id_Cola` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Impresora` tinyint(3) unsigned DEFAULT NULL,
  `Id_Prioridad` tinyint(3) unsigned DEFAULT NULL,
  `Id_Informe` tinyint(3) unsigned DEFAULT '0',
  `Id_Estado` tinyint(3) unsigned DEFAULT '1',
  `Hora_Inicio` datetime DEFAULT NULL,
  `Hora_Fin` datetime DEFAULT NULL,
  `Cola` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Id_Trabajador` int(11) DEFAULT '20',
  `Cola2` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Cola3` text COLLATE utf8_unicode_ci,
  `error` text COLLATE utf8_unicode_ci,
  PRIMARY KEY (`Id_Cola`),
  UNIQUE KEY `Id_Impresora_2` (`Id_Impresora`,`Id_Prioridad`,`Id_Informe`,`Id_Estado`,`Cola`,`Id_Trabajador`,`Cola2`),
  KEY `Id_estado` (`Id_Estado`),
  KEY `Id_Impresora` (`Id_Impresora`),
  KEY `Id_Informe` (`Id_Informe`),
  KEY `Id_Prioridad` (`Id_Prioridad`),
  KEY `Id_Trabajador` (`Id_Trabajador`),
  CONSTRAINT `Colas_ibfk_3` FOREIGN KEY (`Id_Prioridad`) REFERENCES `Prioridades` (`Id_Prioridad`) ON UPDATE CASCADE,
  CONSTRAINT `Colas_ibfk_4` FOREIGN KEY (`Id_Impresora`) REFERENCES `Impresoras` (`Id_Impresora`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=40628 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Colores`
--

DROP TABLE IF EXISTS `Colores`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Colores` (
  `Id_Color` int(11) NOT NULL DEFAULT '0',
  `Color` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`Id_Color`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Comparativa`
--

DROP TABLE IF EXISTS `Comparativa`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Comparativa` (
  `Periodo` int(11) NOT NULL,
  `Id_Article` bigint(20) NOT NULL,
  `warehouse_id` int(11) NOT NULL,
  `Cantidad` mediumint(9) NOT NULL DEFAULT '0',
  `price` mediumint(8) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`Periodo`,`Id_Article`,`warehouse_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Compres`
--

DROP TABLE IF EXISTS `Compres`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Compres` (
  `Id_Compra` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Entrada` int(11) NOT NULL DEFAULT '0',
  `Id_Article` int(11) NOT NULL DEFAULT '90',
  `Cantidad` int(11) DEFAULT '0',
  `dispatched` int(11) NOT NULL DEFAULT '0',
  `Costefijo` decimal(10,3) DEFAULT '0.000',
  `Portefijo` decimal(10,3) DEFAULT '0.000',
  `Novincular` tinyint(1) NOT NULL DEFAULT '0',
  `Etiquetas` int(11) DEFAULT '0',
  `Packing` int(11) DEFAULT '0',
  `grouping` smallint(5) unsigned NOT NULL DEFAULT '1',
  `caja` tinyint(4) NOT NULL DEFAULT '0' COMMENT '0=sin obligar 1=groping 2=packing',
  `container_id` smallint(5) unsigned NOT NULL DEFAULT '36',
  `Comisionfija` decimal(10,3) DEFAULT '0.000',
  `Embalajefijo` decimal(10,3) DEFAULT '0.000',
  `Nicho` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Id_Cubo` varchar(10) COLLATE utf8_unicode_ci DEFAULT '--',
  `Tarifa1` decimal(10,2) DEFAULT '0.00',
  `Tarifa2` decimal(10,2) DEFAULT '0.00',
  `Tarifa3` decimal(10,2) DEFAULT '0.00',
  `PVP` decimal(10,2) DEFAULT '0.00',
  `Productor` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Vida` int(11) DEFAULT '0',
  `Id_Trabajador` int(11) DEFAULT '0',
  `punteo` tinyint(1) NOT NULL DEFAULT '0',
  `isPickedOff` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Esta mercancia no va a la zona de picking.',
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `cm2kk` int(10) unsigned NOT NULL DEFAULT '0',
  `buy_edi_id` int(11) DEFAULT NULL,
  `weight` int(11) unsigned DEFAULT NULL,
  PRIMARY KEY (`Id_Compra`),
  KEY `CompresId_Trabajador` (`Id_Trabajador`),
  KEY `Id_Cubo` (`Id_Cubo`),
  KEY `Id_Entrada` (`Id_Entrada`),
  KEY `container_id` (`container_id`),
  KEY `buy_edi_id` (`buy_edi_id`),
  KEY `itemFk_entryFk` (`Id_Article`,`Id_Entrada`),
  CONSTRAINT `Compres_ibfk_1` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON UPDATE CASCADE,
  CONSTRAINT `Compres_ibfk_2` FOREIGN KEY (`Id_Cubo`) REFERENCES `Cubos` (`Id_Cubo`) ON UPDATE CASCADE,
  CONSTRAINT `Compres_ibfk_3` FOREIGN KEY (`container_id`) REFERENCES `container` (`container_id`) ON UPDATE CASCADE,
  CONSTRAINT `buy_id` FOREIGN KEY (`Id_Entrada`) REFERENCES `Entradas` (`Id_Entrada`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=309537117 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `buy_beforeInsert`
	BEFORE INSERT ON `Compres`
    FOR EACH ROW
trig: BEGIN
	DECLARE vWarehouse INT;
	DECLARE vLanding DATE;
	DECLARE vGrouping INT;
	DECLARE vGroupingMode TINYINT;
    
    IF @isModeInventory THEN
		LEAVE trig;
	END IF;
    
    CALL vn.buy_checkGrouping(NEW.`grouping`);

	SELECT t.warehouseInFk, t.landed INTO vWarehouse, vLanding
		FROM vn.entry e 
			JOIN vn.travel t ON t.id = e.travelFk
		WHERE e.id = NEW.Id_Entrada;

	SELECT b.`grouping`, b.groupingMode INTO vGrouping, vGroupingMode
		FROM vn.buy b
			JOIN vn.entry e ON e.id = b.entryFk
			JOIN vn.travel t ON t.id = e.travelFk
		WHERE t.landed <= vLanding
			AND b.itemFk = NEW.Id_Article
			AND !b.isIgnored
		ORDER BY t.warehouseInFk = vWarehouse DESC, t.landed DESC, b.id DESC
		LIMIT 1;
	
	IF NEW.`grouping` IS NULL THEN
		SET NEW.`grouping` = vGrouping;
	END IF;
	
	IF NEW.caja IS NULL THEN
		SET NEW.caja = vGroupingMode;
	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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `buy_afterInsert`
	AFTER INSERT ON `Compres`
    FOR EACH ROW
trig: BEGIN
	CALL stock.log_add('buy', NULL, NEW.Id_Compra);

	IF @isModeInventory THEN
		LEAVE trig;
	END IF;
    
    CALL vn.buy_afterUpsert(NEW.Id_Compra);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `buy_beforeUpdate`
	BEFORE UPDATE ON `Compres`
    FOR EACH ROW
BEGIN
    IF !(NEW.`grouping` <=> OLD.`grouping`) THEN
		CALL vn.buy_checkGrouping(NEW.`grouping`);
	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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `buy_afterUpdate`
	AFTER UPDATE ON `Compres`
    FOR EACH ROW
trig: BEGIN
    IF !(NEW.Id_Compra <=> OLD.Id_Compra)
    OR !(NEW.Id_Entrada <=> OLD.Id_Entrada)
    OR !(NEW.Id_Article <=> OLD.Id_Article)
    OR !(NEW.Cantidad <=> OLD.Cantidad)
    OR !(NEW.odbc_date <=> OLD.odbc_date) THEN
		CALL stock.log_add('buy', OLD.Id_Compra, NEW.Id_Compra);
	END IF;

	IF @isModeInventory THEN
		LEAVE trig;
	END IF;

    CALL vn.buy_afterUpsert(NEW.Id_Compra);

	IF !(NEW.weight <=> OLD.weight) THEN
		UPDATE vn.item
			SET density = (NEW.weight * NEW.packing) / (cm3_2(NEW.Id_Cubo, NEW.Id_Article) / 1000)
			WHERE id = NEW.Id_Article;
	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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `buy_beforeDelete`
	BEFORE DELETE ON `Compres`
    FOR EACH ROW
BEGIN
	IF OLD.Vida > 0 THEN
		SIGNAL SQLSTATE '45000'
			SET MESSAGE_TEXT = 'A buy from which labels have been printed cannot be deleted';
	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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `buy_afterDelete`
	AFTER DELETE ON `Compres`
    FOR EACH ROW
BEGIN
	CALL stock.log_add('buy', OLD.Id_Compra, 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 */ ;

--
-- Table structure for table `Compres_mark`
--

DROP TABLE IF EXISTS `Compres_mark`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Compres_mark` (
  `Id_Compra` int(11) NOT NULL,
  `comment` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `mark` tinyint(1) DEFAULT NULL,
  `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`Id_Compra`),
  CONSTRAINT `Compres_mark_ibfk_1` FOREIGN KEY (`Id_Compra`) REFERENCES `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 `Compres_ok`
--

DROP TABLE IF EXISTS `Compres_ok`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Compres_ok` (
  `Id_Compra` int(11) NOT NULL,
  `valor` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `original_quantity` double DEFAULT NULL,
  `Id_Trabajador` int(11) NOT NULL,
  `Id_Accion` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `Id_Compra_ok` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`Id_Compra_ok`),
  KEY `Id_Movimiento` (`Id_Compra`),
  KEY `Id_Accion` (`Id_Accion`),
  CONSTRAINT `Compres_ok_ibfk_1` FOREIGN KEY (`Id_Compra`) REFERENCES `Compres` (`Id_Compra`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=27969 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Consignatarios`
--

DROP TABLE IF EXISTS `Consignatarios`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Consignatarios` (
  `id_consigna` int(11) NOT NULL AUTO_INCREMENT,
  `Id_cliente` int(11) NOT NULL DEFAULT '0',
  `warehouse_id` smallint(6) unsigned DEFAULT '1',
  `domicilio` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `poblacion` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
  `province_id` smallint(5) unsigned DEFAULT NULL,
  `codPostal` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `telefono` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `movil` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `consignatario` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
  `predeterminada` tinyint(1) NOT NULL DEFAULT '0',
  `Id_Agencia` int(11) NOT NULL DEFAULT '2',
  `especificaciones` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `seguro` tinyint(1) NOT NULL DEFAULT '0',
  `porte` double DEFAULT NULL,
  `active` tinyint(4) NOT NULL DEFAULT '1',
  `postcode_id` int(11) unsigned DEFAULT NULL,
  `longitude` decimal(11,7) DEFAULT NULL,
  `latitude` decimal(11,7) DEFAULT NULL,
  `codPos` char(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `isEqualizated` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`id_consigna`),
  KEY `Id_Agencia` (`Id_Agencia`),
  KEY `Id_cliente` (`Id_cliente`),
  KEY `warehouse_id` (`warehouse_id`),
  KEY `province_id` (`province_id`),
  KEY `telefono` (`telefono`),
  KEY `movil` (`movil`),
  KEY `CODPOSTAL` (`codPostal`),
  CONSTRAINT `Consignatarios_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `Consignatarios_ibfk_3` FOREIGN KEY (`province_id`) REFERENCES `province` (`province_id`) ON UPDATE CASCADE,
  CONSTRAINT `Consignatarios_ibfk_4` FOREIGN KEY (`Id_Agencia`) REFERENCES `Agencias` (`Id_Agencia`) ON UPDATE CASCADE,
  CONSTRAINT `address_customer_id` FOREIGN KEY (`Id_cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=27726 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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`Consignatarios_beforeInsert`
	BEFORE INSERT ON `vn2008`.`Consignatarios`
	FOR EACH ROW
BEGIN
	DECLARE vIsEqualizated BOOLEAN;

	CALL pbx.phoneIsValid (NEW.telefono);
	CALL pbx.phoneIsValid (NEW.movil);

	IF NEW.isEqualizated IS NULL THEN
		SELECT RE 
				INTO vIsEqualizated
			FROM Clientes
			WHERE Id_Cliente = NEW.Id_Cliente;
		
		SET NEW.isEqualizated = vIsEqualizated;
	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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`Consignatarios_beforeUpdate`
	BEFORE UPDATE ON `vn2008`.`Consignatarios`
	FOR EACH ROW
BEGIN
	CALL pbx.phoneIsValid (NEW.telefono);
	CALL pbx.phoneIsValid (NEW.movil);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`Consignatarios_afterUpdate`
	AFTER UPDATE ON `Consignatarios`
	FOR EACH ROW
BEGIN
	-- Recargos de equivalencia distintos implican facturacion por consignatario
	IF NEW.isEqualizated != OLD.isEqualizated THEN
		IF 
			(SELECT COUNT(*) FROM
				(
					SELECT DISTINCT (isEqualizated = FALSE) as Equ
						FROM Consignatarios 
						WHERE Id_Cliente = NEW.Id_Cliente
				) t1
			) > 1
		THEN 
			UPDATE Clientes 
				SET invoiceByAddress = TRUE
				WHERE Id_Cliente = NEW.Id_Cliente;
		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 `Consignatarios_devices`
--

DROP TABLE IF EXISTS `Consignatarios_devices`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Consignatarios_devices` (
  `Id_Consigna` int(11) NOT NULL,
  `serialNumber` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `notas` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`Id_Consigna`,`serialNumber`),
  CONSTRAINT `Condigna_devices` FOREIGN KEY (`Id_Consigna`) REFERENCES `Consignatarios` (`id_consigna`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Contactos`
--

DROP TABLE IF EXISTS `Contactos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Contactos` (
  `Id_Contacto` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Nombre` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `Apellidos` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Empresa` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Cargo` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Telefono` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Movil` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `email` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Fax` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Notas` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`Id_Contacto`),
  KEY `Telefono` (`Telefono`),
  KEY `Movil` (`Movil`)
) ENGINE=InnoDB AUTO_INCREMENT=2705 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 `vn2008`.`ContactosBeforeInsert`
BEFORE INSERT ON `Contactos` FOR EACH ROW
BEGIN
	CALL pbx.phoneIsValid (NEW.telefono);
	CALL pbx.phoneIsValid (NEW.movil);
	CALL pbx.phoneIsValid (NEW.fax);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `vn2008`.`ContactosBeforeUpdate`
BEFORE UPDATE ON `Contactos` FOR EACH ROW
BEGIN
	CALL pbx.phoneIsValid (NEW.telefono);
	CALL pbx.phoneIsValid (NEW.movil);
	CALL pbx.phoneIsValid (NEW.fax);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `Conteo`
--

DROP TABLE IF EXISTS `Conteo`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Conteo` (
  `Id_Conteo` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Article` int(11) NOT NULL,
  `Fecha` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `dispositivo` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `warehouse_id` int(10) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`Id_Conteo`)
) 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              = '' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `Conteo_ai` AFTER INSERT ON `Conteo` FOR EACH ROW
BEGIN
	DECLARE intTravel INTEGER;
	SELECT t.id INTO intTravel FROM Compres c JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada 
			JOIN travel t ON t.id = e.travel_id 
				WHERE landing = CURDATE() AND c.Id_Article = NEW.Id_Article AND warehouse_id = NEW.warehouse_id AND received <> TRUE LIMIT 1;
	IF (intTravel) then
		UPDATE travel SET received = TRUE WHERE id = intTravel;
	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 `Cubos`
--

DROP TABLE IF EXISTS `Cubos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Cubos` (
  `Id_Cubo` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `Volumen` decimal(10,2) DEFAULT '0.00',
  `X` decimal(10,2) DEFAULT '0.00',
  `Y` decimal(10,2) DEFAULT '0.00',
  `Z` decimal(10,2) DEFAULT '0.00',
  `Valor` decimal(10,2) DEFAULT '0.00',
  `Retornable` tinyint(1) NOT NULL DEFAULT '0',
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `idCubos_Retorno` int(11) DEFAULT NULL,
  `Bajan` int(11) DEFAULT NULL,
  `Suben` int(11) DEFAULT NULL,
  `Base` decimal(10,2) DEFAULT NULL,
  `item_id` int(11) DEFAULT NULL,
  `pvp` decimal(10,2) NOT NULL,
  `box` tinyint(1) NOT NULL DEFAULT '0',
  `bultoCubico` decimal(10,2) DEFAULT NULL,
  `costeRetorno` decimal(10,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`Id_Cubo`),
  KEY `Article` (`item_id`),
  CONSTRAINT `Article` FOREIGN KEY (`item_id`) REFERENCES `Articles` (`Id_Article`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Cubos_Retorno`
--

DROP TABLE IF EXISTS `Cubos_Retorno`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Cubos_Retorno` (
  `idCubos_Retorno` int(11) NOT NULL AUTO_INCREMENT,
  `Soporte` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `Vacio` double NOT NULL DEFAULT '0',
  `Lleno` double NOT NULL DEFAULT '0',
  PRIMARY KEY (`idCubos_Retorno`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Enlaces Facturas`
--

DROP TABLE IF EXISTS `Enlaces Facturas`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Enlaces Facturas` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Asiento` int(11) DEFAULT '0',
  `Apunte` int(11) DEFAULT '0',
  `Data` datetime DEFAULT NULL,
  `Concepto` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Cuenta` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Debe` double DEFAULT NULL,
  `Haber` double DEFAULT NULL,
  `Contrapartida` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Contabilizado` tinyint(1) NOT NULL DEFAULT '0',
  `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442',
  PRIMARY KEY (`id`),
  KEY `empresa_id` (`empresa_id`),
  CONSTRAINT `Enlaces@0020Facturas_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=23889 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Entradas`
--

DROP TABLE IF EXISTS `Entradas`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Entradas` (
  `Id_Entrada` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Proveedor` int(11) NOT NULL DEFAULT '644',
  `Fecha` datetime NOT NULL,
  `Referencia` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Anotadoencaja` tinyint(1) NOT NULL DEFAULT '0',
  `Inventario` tinyint(1) NOT NULL DEFAULT '0',
  `Notas` longtext COLLATE utf8_unicode_ci,
  `Confirmada` tinyint(1) NOT NULL DEFAULT '0',
  `Pedida` tinyint(1) NOT NULL DEFAULT '0',
  `Redada` tinyint(1) NOT NULL DEFAULT '0',
  `comision` float DEFAULT '0',
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `Notas_Eva` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `travel_id` int(11) unsigned DEFAULT NULL,
  `Id_Moneda` tinyint(3) unsigned DEFAULT '1',
  `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442',
  `gestdoc_id` int(11) DEFAULT NULL,
  `recibida_id` mediumint(8) unsigned DEFAULT NULL,
  `blocked` tinyint(4) NOT NULL DEFAULT '0',
  `loadPriority` int(11) DEFAULT NULL,
  PRIMARY KEY (`Id_Entrada`),
  KEY `Id_Proveedor` (`Id_Proveedor`),
  KEY `Fecha` (`Fecha`),
  KEY `travel_id` (`travel_id`),
  KEY `empresa_id` (`empresa_id`),
  KEY `gestdoc_id` (`gestdoc_id`),
  KEY `recibida_id` (`recibida_id`),
  CONSTRAINT `Entradas_fk8` FOREIGN KEY (`recibida_id`) REFERENCES `recibida` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `Entradas_ibfk_1` FOREIGN KEY (`Id_Proveedor`) REFERENCES `Proveedores` (`Id_Proveedor`) ON UPDATE CASCADE,
  CONSTRAINT `Entradas_ibfk_6` FOREIGN KEY (`travel_id`) REFERENCES `travel` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `Entradas_ibfk_7` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=168096 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='InnoDB free: 88064 kB; (`Id_Proveedor`) REFER `vn2008/Provee';
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `entry_beforeInsert`
	BEFORE INSERT ON `Entradas`
    FOR EACH ROW
BEGIN 
    SET NEW.Id_Moneda = vn.entry_getCurrency(NEW.Id_Moneda, NEW.Id_Proveedor);
	SET NEW.comision = vn.entry_calcCommission(NEW.comision, NEW.travel_id, NEW.Id_Moneda);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`entry_afterInsert`
	AFTER INSERT ON `Entradas`
    FOR EACH ROW
BEGIN
	CALL vn.travel_requestRecalc(NEW.travel_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `entry_beforeUpdate`
	BEFORE UPDATE ON `Entradas`
    FOR EACH ROW
BEGIN 
    DECLARE vIsClone BOOL;
    DECLARE vHasDistinctWarehouses BOOL;

	IF !(NEW.travel_id <=> OLD.travel_id) THEN
		SELECT COUNT(*) > 0 INTO vIsClone
			FROM vn2008.Entradas_Auto WHERE Id_Entrada = NEW.Id_Entrada;

		SELECT !(o.warehouseInFk <=> n.warehouseInFk)
			OR !(o.warehouseOutFk <=> n.warehouseOutFk)
			INTO vHasDistinctWarehouses
			FROM vn.travel o, vn.travel n
			WHERE o.id = OLD.travel_id
				AND n.id = NEW.travel_id;

		IF vIsClone AND vHasDistinctWarehouses THEN
			SIGNAL SQLSTATE '45000'
				SET MESSAGE_TEXT = 'A cloned entry cannot be moved to travel with different warehouses';
		END IF;
	END IF;

	IF !(NEW.Id_Proveedor <=> OLD.Id_Proveedor) THEN
		SET NEW.Id_Moneda = vn.entry_getCurrency(NEW.Id_Moneda, NEW.Id_Proveedor);
	END IF;

    IF !(NEW.travel_id <=> OLD.travel_id)
	OR !(NEW.Id_Moneda <=> OLD.Id_Moneda) THEN 
		SET NEW.comision = vn.entry_calcCommission(NEW.comision, NEW.travel_id, NEW.Id_Moneda);
	END IF;

	IF !(ABS(NEW.anotadoencaja) <=> ABS(OLD.anotadoencaja)) THEN
		INSERT INTO vn2008.Entradas_dits SET
			idaccion_dits = 105,
            Id_Trabajador = vn.getWorker(),
            Id_Ticket = NEW.Id_Entrada,
            value_old = OLD.anotadoencaja,
            value_new = NEW.anotadoencaja;
	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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `entry_afterUpdate`
	AFTER UPDATE ON `Entradas`
    FOR EACH ROW
BEGIN
	IF !(NEW.Id_Entrada <=> OLD.Id_Entrada)
    OR !(NEW.travel_id <=> OLD.travel_id)
    OR !(NEW.Redada <=> OLD.Redada) THEN
		CALL stock.log_add('entry', OLD.Id_Entrada, NEW.Id_Entrada);
	END IF;

	IF !(NEW.travel_id <=> OLD.travel_id) THEN
		CALL vn.travel_requestRecalc(OLD.travel_id);
		CALL vn.travel_requestRecalc(NEW.travel_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 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`entry_beforeDelete`
	BEFORE DELETE ON `Entradas`
    FOR EACH ROW
BEGIN 
	DELETE FROM vn.buy WHERE entryFk = OLD.Id_Entrada;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`entry_afterDelete`
	AFTER DELETE ON `Entradas`
    FOR EACH ROW
BEGIN
	CALL vn.travel_requestRecalc(OLD.travel_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 */ ;

--
-- Table structure for table `Entradas_Auto`
--

DROP TABLE IF EXISTS `Entradas_Auto`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Entradas_Auto` (
  `Id_Entrada` int(11) NOT NULL,
  PRIMARY KEY (`Id_Entrada`),
  CONSTRAINT `Entradas_Auto_ibfk_1` FOREIGN KEY (`Id_Entrada`) REFERENCES `Entradas` (`Id_Entrada`) 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 `Entradas_dits`
--

DROP TABLE IF EXISTS `Entradas_dits`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Entradas_dits` (
  `idEntrada_dits` int(11) NOT NULL AUTO_INCREMENT,
  `idaccion_dits` int(11) NOT NULL,
  `ODBC_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `Id_Ticket` int(11) NOT NULL,
  `Id_Trabajador` int(11) DEFAULT NULL,
  `value_old` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value_new` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`idEntrada_dits`),
  KEY `fgkey_entradas_1_idx` (`idaccion_dits`),
  KEY `fgkey_entradas_2_idx` (`Id_Ticket`),
  KEY `fgkey_entradas_3_idx` (`Id_Trabajador`),
  CONSTRAINT `Entradas_dits_ibfk_1` FOREIGN KEY (`Id_Ticket`) REFERENCES `Entradas` (`Id_Entrada`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fgkey_entradas_1` FOREIGN KEY (`idaccion_dits`) REFERENCES `accion_dits` (`idaccion_dits`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `fgkey_entradas_3` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3571464 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Entradas_kop`
--

DROP TABLE IF EXISTS `Entradas_kop`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Entradas_kop` (
  `Id_Entradas_kop` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Entrada` int(11) NOT NULL,
  `kop` int(11) DEFAULT NULL,
  `sub` mediumint(8) unsigned DEFAULT NULL,
  PRIMARY KEY (`Id_Entradas_kop`),
  KEY `entradas_entradas_kop_idx` (`Id_Entrada`),
  CONSTRAINT `entradas_entradas_kop` FOREIGN KEY (`Id_Entrada`) REFERENCES `Entradas` (`Id_Entrada`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=489 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Relaciona las entradas con los origenes de compra';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Entradas_orden`
--

DROP TABLE IF EXISTS `Entradas_orden`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Entradas_orden` (
  `Id_Entrada` int(11) NOT NULL,
  `orden` int(11) NOT NULL DEFAULT '1' COMMENT '1.- Ordenar por articulo\n2.- Ordenar por compra\n',
  PRIMARY KEY (`Id_Entrada`),
  CONSTRAINT `entradas_entradas_orden` FOREIGN KEY (`Id_Entrada`) REFERENCES `Entradas` (`Id_Entrada`) 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 `Entradas_stack`
--

DROP TABLE IF EXISTS `Entradas_stack`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Entradas_stack` (
  `Id_Entrada` int(11) NOT NULL,
  `label_number` smallint(6) DEFAULT '0',
  PRIMARY KEY (`Id_Entrada`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Entradas_turno`
--

DROP TABLE IF EXISTS `Entradas_turno`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Entradas_turno` (
  `Id_Entrada` int(11) NOT NULL,
  `weekDay` tinyint(2) NOT NULL DEFAULT '0',
  PRIMARY KEY (`Id_Entrada`),
  CONSTRAINT `entrada_entrada_turno` FOREIGN KEY (`Id_Entrada`) REFERENCES `Entradas` (`Id_Entrada`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Estas entradas se clonan al mismo tiempo que los turnos';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `EnvioMasivo`
--

DROP TABLE IF EXISTS `EnvioMasivo`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `EnvioMasivo` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Cliente` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
  `Direccion` varchar(80) COLLATE utf8_unicode_ci NOT NULL,
  `CP` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
  `Poblacion` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
  `Telefono` varchar(9) COLLATE utf8_unicode_ci NOT NULL,
  `Bultos` int(11) NOT NULL,
  `Observaciones` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
  `IdTicket` int(11) NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=3373 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Generación de etiquetas a través de Zeleris con los clientes de esta tabla';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Equipos`
--

DROP TABLE IF EXISTS `Equipos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Equipos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `alias` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `trabajador_id` int(11) DEFAULT NULL,
  `descripcion` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `predet` int(1) unsigned zerofill DEFAULT '0',
  `Left` int(5) DEFAULT '3000',
  `Top` int(5) DEFAULT '3000',
  `Width` int(5) DEFAULT '6360',
  `Height` int(5) DEFAULT '5595',
  PRIMARY KEY (`id`),
  KEY `trabajador_id` (`trabajador_id`),
  CONSTRAINT `Equipos_ibfk_1` FOREIGN KEY (`trabajador_id`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=210 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Espionajes`
--

DROP TABLE IF EXISTS `Espionajes`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Espionajes` (
  `idEspionaje` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Trabajador` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Fecha` date DEFAULT NULL,
  `HoraEntrada` time DEFAULT NULL,
  `HoraSalida` time DEFAULT NULL,
  `Id_Equipo` int(11) DEFAULT NULL,
  PRIMARY KEY (`idEspionaje`),
  KEY `index` (`Id_Trabajador`,`Fecha`)
) ENGINE=InnoDB AUTO_INCREMENT=75648 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Estados`
--

DROP TABLE IF EXISTS `Estados`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Estados` (
  `Id_Estado` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `Estado` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`Id_Estado`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Estanterias`
--

DROP TABLE IF EXISTS `Estanterias`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Estanterias` (
  `Id_Estanterias` int(11) NOT NULL AUTO_INCREMENT,
  `w` int(11) DEFAULT NULL,
  `d` int(11) DEFAULT NULL,
  `modelo` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`Id_Estanterias`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Estanterias_distri`
--

DROP TABLE IF EXISTS `Estanterias_distri`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Estanterias_distri` (
  `idEstanterias_distri` int(11) NOT NULL,
  `posinicial` int(11) NOT NULL,
  `posfinal` int(11) NOT NULL,
  `Id_Estanterias` int(11) NOT NULL,
  PRIMARY KEY (`Id_Estanterias`,`idEstanterias_distri`),
  KEY `Estanterias_fgkey1_idx` (`Id_Estanterias`),
  KEY `est_distrib_fgkey1_idx` (`idEstanterias_distri`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Estanterias_distri_name`
--

DROP TABLE IF EXISTS `Estanterias_distri_name`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Estanterias_distri_name` (
  `idEstanterias_distri` int(11) NOT NULL AUTO_INCREMENT,
  `Descripcion` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`idEstanterias_distri`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Extractos`
--

DROP TABLE IF EXISTS `Extractos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Extractos` (
  `Id_Extracto` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Fecha` datetime NOT NULL,
  `Concepto` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `Debe` double unsigned zerofill NOT NULL DEFAULT '0000000000000000000000',
  `Haber` double unsigned zerofill NOT NULL DEFAULT '0000000000000000000000',
  `Concepto2` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `Concepto3` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`Id_Extracto`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Facturas`
--

DROP TABLE IF EXISTS `Facturas`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Facturas` (
  `factura_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Factura` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `Serie` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Fecha` date DEFAULT NULL,
  `Importe` decimal(12,2) DEFAULT '0.00',
  `Vencimiento` datetime DEFAULT NULL,
  `Id_Banco` int(11) DEFAULT NULL,
  `Id_Cliente` int(11) DEFAULT '0',
  `Id_Remesa` int(11) DEFAULT NULL,
  `Remesar` tinyint(1) NOT NULL DEFAULT '0',
  `BI7` decimal(12,2) DEFAULT '0.00',
  `BI16` decimal(12,2) DEFAULT '0.00',
  `RE1` decimal(12,2) DEFAULT '0.00',
  `RE4` decimal(12,2) DEFAULT '0.00',
  `IVA7` decimal(12,2) DEFAULT '0.00',
  `IVA16` decimal(12,2) DEFAULT '0.00',
  `Id_Trabajador` int(11) DEFAULT '0',
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442',
  `liquidacion` smallint(6) DEFAULT '0',
  `pdf` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `booked` date DEFAULT NULL,
  `cplusInvoiceType477Fk` int(10) unsigned NOT NULL DEFAULT '1',
  `cplusTaxBreakFk` int(10) unsigned NOT NULL DEFAULT '1',
  `cplusSubjectOpFk` int(10) unsigned NOT NULL DEFAULT '1',
  `cplusTrascendency477Fk` int(10) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`factura_id`,`Id_Factura`),
  UNIQUE KEY `Id_Factura` (`Id_Factura`),
  KEY `Id_Banco` (`Id_Banco`),
  KEY `Id_Cliente` (`Id_Cliente`),
  KEY `Id_Remesa` (`Id_Remesa`),
  KEY `Id_Trabajador` (`Id_Trabajador`),
  KEY `empresa_id` (`empresa_id`),
  KEY `Fecha` (`Fecha`),
  KEY `Facturas_ibfk_2_idx` (`cplusInvoiceType477Fk`),
  KEY `Facturas_ibfk_3_idx` (`cplusSubjectOpFk`),
  KEY `Facturas_ibfk_4_idx` (`cplusTaxBreakFk`),
  KEY `Facturas_ibfk_5_idx` (`cplusTrascendency477Fk`),
  KEY `Facturas_idx_Vencimiento` (`Vencimiento`),
  CONSTRAINT `Facturas_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `Facturas_ibfk_2` FOREIGN KEY (`cplusInvoiceType477Fk`) REFERENCES `vn`.`cplusInvoiceType477` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `Facturas_ibfk_3` FOREIGN KEY (`cplusSubjectOpFk`) REFERENCES `vn`.`cplusSubjectOp` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `Facturas_ibfk_4` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `vn`.`cplusTaxBreak` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `invoice_bank_id` FOREIGN KEY (`Id_Banco`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE,
  CONSTRAINT `invoice_customer_id` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=498319 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 `FacturasBeforeInsert`
BEFORE INSERT ON `Facturas` FOR EACH ROW
-- Edit trigger body code below this line. Do not edit lines above this one
BEGIN

	DECLARE v_Id_Factura_serie CHAR(9) DEFAULT '0000001';
    DECLARE v_Id_Factura INT;  
    DECLARE max_id, intLast, intProv INT;

    SELECT IFNULL(MAX(factura_id),0) into max_id 
    from Facturas 
    WHERE Serie LIKE NEW.Serie
    AND ((Year(NEW.Fecha) = Year(Fecha)
    AND empresa_id = NEW.empresa_id));
    
    IF max_id THEN
        
        SELECT right(max(Id_Factura), LENGTH(Id_Factura)-1) + 1 
            into v_Id_Factura_serie
        from Facturas
        WHERE Serie LIKE NEW.Serie
            AND ((Year(NEW.Fecha) = Year(Fecha)
            AND length(Id_Factura) > 6
            AND empresa_id = NEW.empresa_id) /*OR (NEW.Serie LIKE 'B' AND length(Id_Factura) > 7)*/ );
    ELSE
			SELECT CONCAT(digito_factura,RIGHT(YEAR(CURDATE()),1),'00001') INTO v_Id_Factura_serie
            FROM empresa WHERE id = NEW.empresa_id;

/*Primer digito la empresa, segundo el aÃ±o, despues la numeracion correlativa con 5 digitos*/

    END IF;

SELECT CONCAT(NEW.serie, lpad(v_Id_Factura_serie,7,'0')) into v_Id_Factura_serie;
SET NEW.Id_Factura = v_Id_Factura_serie;

	END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `vn2008`.`FacturasAfterInsert`
AFTER INSERT ON `Facturas`
FOR EACH ROW
	CALL bi.customer_risk_update (NEW.Id_Cliente, NEW.empresa_id, NEW.Importe) */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `vn2008`.`FacturasBeforeUpdate`
BEFORE UPDATE ON `Facturas`
FOR EACH ROW
BEGIN
	CALL bi.customer_risk_update (OLD.Id_Cliente, OLD.empresa_id, -OLD.Importe);
	CALL bi.customer_risk_update (NEW.Id_Cliente, NEW.empresa_id, NEW.Importe);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `vn2008`.`FacturasBeforeDelete`
BEFORE DELETE ON `Facturas`
FOR EACH ROW
	CALL bi.customer_risk_update (OLD.Id_Cliente, OLD.empresa_id, -OLD.Importe) */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `Familias`
--

DROP TABLE IF EXISTS `Familias`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Familias` (
  `Familia` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `Subcuenta` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Descripcion` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`Familia`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Forms`
--

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

DROP TABLE IF EXISTS `Gastos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Gastos` (
  `Id_Gasto` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `iva_tipo_id` tinyint(4) NOT NULL,
  `Gasto` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `conbase` tinyint(4) NOT NULL DEFAULT '1',
  `isWithheld` tinyint(4) NOT NULL DEFAULT '0',
  `isForSale` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`Id_Gasto`,`iva_tipo_id`),
  KEY `iva_tipo_id` (`iva_tipo_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Greuges`
--

DROP TABLE IF EXISTS `Greuges`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Greuges` (
  `Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Cliente` int(10) unsigned NOT NULL,
  `Comentario` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `Importe` decimal(10,2) NOT NULL,
  `Fecha` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `Greuges_type_id` int(11) DEFAULT NULL,
  `Id_Ticket` int(11) DEFAULT NULL,
  PRIMARY KEY (`Id`),
  KEY `greuges_type_fk_idx` (`Greuges_type_id`),
  KEY `Id_Ticket_Greuge_Ticket_idx` (`Id_Ticket`),
  CONSTRAINT `Id_Ticket_Greuge_Ticket` FOREIGN KEY (`Id_Ticket`) REFERENCES `Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `greuges_type_fk` FOREIGN KEY (`Greuges_type_id`) REFERENCES `Greuges_type` (`Greuges_type_id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3353601 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=COMPACT;
/*!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 `vn2008`.`Greuges_BEFORE_UPDATE` BEFORE UPDATE ON `Greuges` FOR EACH ROW
BEGIN

	DECLARE vMaxDate DATETIME DEFAULT TIMESTAMPADD(YEAR,1,CURDATE());
    
    IF NEW.Fecha > vMaxDate THEN
    
		SET NEW.Fecha = vMaxDate;
        
	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 `Greuges_type`
--

DROP TABLE IF EXISTS `Greuges_type`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Greuges_type` (
  `Greuges_type_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`Greuges_type_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 `Grupos`
--

DROP TABLE IF EXISTS `Grupos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Grupos` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `Grupo` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `observation_type_id` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Impresoras`
--

DROP TABLE IF EXISTS `Impresoras`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Impresoras` (
  `Id_Impresora` tinyint(3) unsigned NOT NULL,
  `Ruta` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Impresora` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `referencia` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `2C` tinyint(4) DEFAULT '0',
  `isLabeler` tinyint(3) NOT NULL DEFAULT '0',
  `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`Id_Impresora`),
  UNIQUE KEY `referencia` (`referencia`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Informes`
--

DROP TABLE IF EXISTS `Informes`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Informes` (
  `Id_Informe` tinyint(3) unsigned NOT NULL,
  `Informe` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`Id_Informe`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Intrastat`
--

DROP TABLE IF EXISTS `Intrastat`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Intrastat` (
  `Codintrastat` int(8) unsigned zerofill NOT NULL,
  `Definicion` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `import` tinyint(4) NOT NULL DEFAULT '0',
  `iva_group_id` tinyint(3) unsigned NOT NULL DEFAULT '2',
  `iva_codigo_id` tinyint(2) unsigned NOT NULL DEFAULT '64',
  PRIMARY KEY (`Codintrastat`),
  KEY `iva_group_id` (`iva_group_id`),
  CONSTRAINT `Intrastat_ibfk_1` FOREIGN KEY (`iva_group_id`) REFERENCES `iva_group` (`iva_group_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 `Jefes`
--

DROP TABLE IF EXISTS `Jefes`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Jefes` (
  `Id_Trabajador` int(11) NOT NULL,
  `Id_Jefe` int(11) NOT NULL,
  `Departamento` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`Id_Trabajador`,`Id_Jefe`),
  KEY `trabajador_jefe_idx` (`Id_Jefe`),
  CONSTRAINT `trabajador_jefe` FOREIGN KEY (`Id_Jefe`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `trabajador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Es una tabla que se rellena desde la comparativa, tomando los datos de postgress.';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Monedas`
--

DROP TABLE IF EXISTS `Monedas`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Monedas` (
  `Id_Moneda` tinyint(3) unsigned NOT NULL,
  `Moneda` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `Descripcion` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Cambio` double NOT NULL DEFAULT '1',
  PRIMARY KEY (`Id_Moneda`),
  UNIQUE KEY `Moneda_UNIQUE` (`Moneda`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Monitoring`
--

DROP TABLE IF EXISTS `Monitoring`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Monitoring` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `equipo_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `form_id` int(11) NOT NULL,
  `cliente_id` int(11) NOT NULL,
  `ticket_id` int(11) NOT NULL,
  `ODBC_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `equipo_id` (`equipo_id`,`user_id`,`form_id`,`cliente_id`,`ticket_id`),
  KEY `user_id` (`user_id`),
  KEY `form_id` (`form_id`),
  KEY `cliente_id` (`cliente_id`),
  KEY `ticket_id` (`ticket_id`),
  CONSTRAINT `Monitoring_ibfk_1` FOREIGN KEY (`equipo_id`) REFERENCES `Equipos` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `Monitoring_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE,
  CONSTRAINT `Monitoring_ibfk_3` FOREIGN KEY (`form_id`) REFERENCES `Forms` (`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 `Movimientos`
--

DROP TABLE IF EXISTS `Movimientos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Movimientos` (
  `Id_Movimiento` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Article` int(11) NOT NULL,
  `Id_Ticket` int(11) NOT NULL,
  `Concepte` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Cantidad` decimal(10,2) NOT NULL DEFAULT '0.00',
  `quantity` double(9,1) DEFAULT NULL,
  `Preu` decimal(10,2) DEFAULT '0.00',
  `Descuento` tinyint(2) unsigned NOT NULL DEFAULT '0',
  `CostFixat` decimal(10,2) NOT NULL DEFAULT '0.00',
  `Reservado` tinyint(1) NOT NULL DEFAULT '0',
  `OK` tinyint(1) NOT NULL DEFAULT '0',
  `PrecioFijado` tinyint(1) NOT NULL DEFAULT '0',
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`Id_Movimiento`),
  KEY `Id_Ticket` (`Id_Ticket`),
  KEY `itemFk_ticketFk` (`Id_Article`,`Id_Ticket`),
  CONSTRAINT `Movimientos_ibfk_1` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON UPDATE CASCADE,
  CONSTRAINT `movement_ticket_id` FOREIGN KEY (`Id_Ticket`) REFERENCES `Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=24546128 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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `sale_afterInsert`
	AFTER INSERT ON `Movimientos`
    FOR EACH ROW
BEGIN
	CALL stock.log_add('sale', NULL, NEW.Id_Movimiento);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `sale_beforeUpdate`
	BEFORE UPDATE ON `Movimientos`
    FOR EACH ROW
BEGIN
	IF NEW.Descuento > 100 THEN
		SET NEW.Descuento = 0;
	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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `sale_afterUpdate`
	AFTER UPDATE ON `Movimientos`
    FOR EACH ROW
BEGIN
    IF !(NEW.Id_Movimiento <=> OLD.Id_Movimiento)
    OR !(NEW.Id_Ticket <=> OLD.Id_Movimiento)
    OR !(NEW.Id_Article <=> OLD.Id_Article)
    OR !(NEW.Cantidad <=> OLD.Cantidad)
    OR !(NEW.odbc_date <=> OLD.odbc_date)
    OR !(NEW.OK <=> OLD.OK) THEN
		CALL stock.log_add('sale', OLD.Id_Movimiento, NEW.Id_Movimiento);
	END IF;

	IF !(OLD.Id_Ticket <=> NEW.Id_Ticket) THEN
		UPDATE Ordenes SET ticketFk = NEW.Id_Ticket
			WHERE Id_Movimiento = NEW.Id_Movimiento;
	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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `sale_afterDelete`
	AFTER DELETE ON `Movimientos`
    FOR EACH ROW
BEGIN
    CALL stock.log_add('sale', OLD.Id_Movimiento, 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 */ ;

--
-- Table structure for table `Movimientos_avisar`
--

DROP TABLE IF EXISTS `Movimientos_avisar`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Movimientos_avisar` (
  `Id_Movimiento` int(11) NOT NULL,
  `Id_Remitente` int(11) DEFAULT NULL,
  PRIMARY KEY (`Id_Movimiento`),
  KEY `Movimiento` (`Id_Movimiento`),
  KEY `Remitente` (`Id_Remitente`),
  CONSTRAINT `Id_Movimientos_avisar_fk` FOREIGN KEY (`Id_Movimiento`) REFERENCES `Movimientos` (`Id_Movimiento`) 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_checked`
--

DROP TABLE IF EXISTS `Movimientos_checked`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Movimientos_checked` (
  `Id_Movimiento` int(11) NOT NULL,
  `checked` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`Id_Movimiento`),
  CONSTRAINT `fk_Movimientos_checked_1` FOREIGN KEY (`Id_Movimiento`) REFERENCES `Movimientos` (`Id_Movimiento`) 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_componentes`
--

DROP TABLE IF EXISTS `Movimientos_componentes`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Movimientos_componentes` (
  `Id_Movimiento` int(11) NOT NULL,
  `Id_Componente` int(11) NOT NULL,
  `Valor` double NOT NULL,
  `greuge` tinyint(4) NOT NULL DEFAULT '0',
  `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`Id_Movimiento`,`Id_Componente`),
  KEY `fk_mov_comp_idx` (`Id_Componente`),
  CONSTRAINT `mc_fk1` FOREIGN KEY (`Id_Movimiento`) REFERENCES `Movimientos` (`Id_Movimiento`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `mc_fk2` FOREIGN KEY (`Id_Componente`) REFERENCES `bi`.`tarifa_componentes` (`Id_Componente`) 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_mark`
--

DROP TABLE IF EXISTS `Movimientos_mark`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Movimientos_mark` (
  `Id_Movimiento` int(11) NOT NULL,
  `valor` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `original_quantity` double DEFAULT NULL,
  `Id_Trabajador` int(11) NOT NULL,
  `Id_Accion` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `Id_Movimiento_mark` int(11) NOT NULL AUTO_INCREMENT,
  `stateFk` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`Id_Movimiento_mark`),
  UNIQUE KEY `stateFk_UNIQUE` (`stateFk`,`Id_Movimiento`),
  KEY `Id_Movimiento` (`Id_Movimiento`),
  KEY `fgnStateFk_idx` (`stateFk`),
  CONSTRAINT `fgnStateFk` FOREIGN KEY (`stateFk`) REFERENCES `state` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=16634920 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 `vn2008`.`Movimientos_mark_BEFORE_INSERT` BEFORE INSERT ON `Movimientos_mark` FOR EACH ROW
BEGIN
	IF(NEW.stateFk = 14) THEN
		SET NEW.Id_Accion = 3;
	END IF;

	IF(NEW.stateFk = 8) THEN
		SET NEW.Id_Accion = 4;
	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 `Movimientos_revisar`
--

DROP TABLE IF EXISTS `Movimientos_revisar`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Movimientos_revisar` (
  `Id_Movimiento` int(11) NOT NULL,
  `Comentario` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Revisado` tinyint(1) NOT NULL DEFAULT '0',
  `Id_Remitente` int(11) DEFAULT NULL,
  `Id_Destinatario` int(11) DEFAULT NULL,
  PRIMARY KEY (`Id_Movimiento`),
  KEY `Remitente` (`Id_Remitente`),
  KEY `Destinatario` (`Id_Destinatario`),
  CONSTRAINT `Movimientos_revisar_ibfk_1` FOREIGN KEY (`Id_Movimiento`) REFERENCES `Movimientos` (`Id_Movimiento`) 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 `Objetivos`
--

DROP TABLE IF EXISTS `Objetivos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Objetivos` (
  `Periodo` int(11) NOT NULL,
  `Objetivo` double NOT NULL,
  PRIMARY KEY (`Periodo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Ordenes`
--

DROP TABLE IF EXISTS `Ordenes`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Ordenes` (
  `Id_ORDEN` int(11) NOT NULL AUTO_INCREMENT,
  `ORDEN` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `datORDEN` datetime DEFAULT NULL,
  `datTICKET` datetime DEFAULT NULL,
  `CodVENDEDOR` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `CodCOMPRADOR` varchar(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'NOE',
  `CANTIDAD` int(11) DEFAULT NULL,
  `PRECIOMAX` double DEFAULT NULL,
  `PREU` double DEFAULT NULL,
  `Id_ARTICLE` double DEFAULT NULL,
  `Id_CLIENTE` int(11) DEFAULT NULL,
  `COMENTARIO` longtext COLLATE utf8_unicode_ci,
  `OK` tinyint(1) NOT NULL DEFAULT '0',
  `TOTAL` int(11) DEFAULT NULL,
  `datCOMPRA` datetime DEFAULT NULL,
  `KO` tinyint(1) NOT NULL DEFAULT '0',
  `Id_Movimiento` int(11) DEFAULT NULL,
  `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `isOk` tinyint(1) DEFAULT NULL,
  `requesterFk` int(11) DEFAULT NULL,
  `atenderFk` int(11) DEFAULT NULL,
  `ticketFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`Id_ORDEN`),
  UNIQUE KEY `Id_Movimiento_UNIQUE` (`Id_Movimiento`),
  KEY `Id_ARTICLE` (`Id_ARTICLE`),
  KEY `Id_CLIENTE` (`Id_CLIENTE`),
  KEY `Id_Comprador` (`CodCOMPRADOR`),
  KEY `Id_Movimiento` (`Id_Movimiento`),
  KEY `Id_Vendedor` (`CodVENDEDOR`),
  KEY `fgnRequester_idx` (`requesterFk`),
  KEY `fgnAtender_idx` (`atenderFk`),
  KEY `fgnTicket_idx` (`ticketFk`),
  CONSTRAINT `fgbMovimiento` FOREIGN KEY (`Id_Movimiento`) REFERENCES `Movimientos` (`Id_Movimiento`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `fgnAtender` FOREIGN KEY (`atenderFk`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE,
  CONSTRAINT `fgnRequester` FOREIGN KEY (`requesterFk`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE,
  CONSTRAINT `fgnTicket` FOREIGN KEY (`ticketFk`) REFERENCES `Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=43961 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 `vn2008`.`Ordenes_BEFORE_INSERT` BEFORE INSERT ON `Ordenes` FOR EACH ROW
BEGIN
	IF NEW.ticketFk IS NULL THEN
		SET NEW.ticketFk = (SELECT m.Id_Ticket FROM Movimientos m WHERE m.Id_Movimiento = NEW.Id_Movimiento);
	END IF;
    
	IF NEW.requesterFk IS NULL THEN
		SET NEW.requesterFk = (SELECT t.Id_Trabajador FROM Trabajadores t WHERE t.CodigoTrabajador = NEW.CodVENDEDOR);
	END IF;
    
	IF NEW.atenderFk IS NULL THEN
		SET NEW.atenderFk = (SELECT t.Id_Trabajador FROM Trabajadores t WHERE t.CodigoTrabajador = NEW.CodCOMPRADOR);
	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 `vn2008`.`Ordenes_BEFORE_UPDATE` BEFORE UPDATE ON `Ordenes` FOR EACH ROW
BEGIN
	IF NEW.Id_Movimiento <> OLD.Id_Movimiento THEN
		SET NEW.ticketFk = (SELECT m.Id_Ticket FROM Movimientos m WHERE m.Id_Movimiento = NEW.Id_Movimiento);
	END IF;
    
	IF NEW.CodVENDEDOR <> OLD.CodVENDEDOR THEN
		SET NEW.requesterFk = (SELECT t.Id_Trabajador FROM Trabajadores t WHERE t.CodigoTrabajador = NEW.CodVENDEDOR);
	END IF;
    
	IF NEW.CodCOMPRADOR <> OLD.CodCOMPRADOR THEN
		SET NEW.atenderFk = (SELECT t.Id_Trabajador FROM Trabajadores t WHERE t.CodigoTrabajador = NEW.CodCOMPRADOR);
	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 `Origen`
--

DROP TABLE IF EXISTS `Origen`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Origen` (
  `id` tinyint(2) unsigned NOT NULL AUTO_INCREMENT,
  `Abreviatura` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `Origen` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `warehouse_id` smallint(5) unsigned DEFAULT '4',
  `bandera` blob,
  `nl` tinyint(4) NOT NULL DEFAULT '0',
  `Id_Paises` mediumint(8) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `Abreviatura` (`Abreviatura`),
  KEY `warehouse_id` (`warehouse_id`),
  KEY `Id_Paises` (`Id_Paises`),
  CONSTRAINT `Origen_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=59 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Pagares`
--

DROP TABLE IF EXISTS `Pagares`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Pagares` (
  `kk_Vencimiento` datetime DEFAULT NULL,
  `kk_Importe` double DEFAULT '0',
  `Fechaemision` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `Id_Pagare` int(11) NOT NULL AUTO_INCREMENT,
  `Concepto` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `kk_id_proveedor` int(11) DEFAULT NULL,
  `kk_empresa_id` smallint(5) unsigned DEFAULT NULL,
  `pago_id` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`Id_Pagare`),
  KEY `empresa_id` (`kk_empresa_id`),
  KEY `pago_id` (`pago_id`),
  CONSTRAINT `Pagares_ibfk_2` FOREIGN KEY (`pago_id`) REFERENCES `pago` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2868 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Paises`
--

DROP TABLE IF EXISTS `Paises`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Paises` (
  `Id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `Pais` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `CEE` tinyint(1) NOT NULL DEFAULT '1',
  `Codigo` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Id_Moneda` tinyint(3) unsigned NOT NULL DEFAULT '1',
  `Id_Paisreal` mediumint(8) unsigned NOT NULL COMMENT 'Pais Real(apaño por culpa del España Exento)',
  `nst_geo_id` int(11) DEFAULT NULL,
  `nst_name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `geoFk` int(11) DEFAULT NULL,
  `isUeeMember` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`Id`),
  KEY `Id_Paisreal` (`Id_Paisreal`)
) ENGINE=InnoDB AUTO_INCREMENT=70 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Permisos`
--

DROP TABLE IF EXISTS `Permisos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Permisos` (
  `Id_Grupo` int(10) unsigned NOT NULL,
  `Id_Trabajador` int(10) unsigned NOT NULL,
  `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442',
  PRIMARY KEY (`Id_Grupo`,`Id_Trabajador`),
  KEY `empresa_id` (`empresa_id`),
  CONSTRAINT `Permisos_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `Permisos_ibfk_2` FOREIGN KEY (`Id_Grupo`) REFERENCES `Grupos` (`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 `PreciosEspeciales`
--

DROP TABLE IF EXISTS `PreciosEspeciales`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `PreciosEspeciales` (
  `Id_PrecioEspecial` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Cliente` int(11) NOT NULL DEFAULT '0',
  `Id_Article` int(11) NOT NULL DEFAULT '0',
  `PrecioEspecial` double NOT NULL DEFAULT '0',
  PRIMARY KEY (`Id_PrecioEspecial`),
  UNIQUE KEY `Id_Cliente_2` (`Id_Cliente`,`Id_Article`),
  KEY `Id_Article` (`Id_Article`),
  KEY `Id_Cliente` (`Id_Cliente`),
  CONSTRAINT `sp_article_id` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON UPDATE CASCADE,
  CONSTRAINT `sp_customer_id` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE,
  CONSTRAINT `{01A99AF1-3D3F-4B15-AC0C-C7A834F319A3}` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `{EE4ADEF6-0AC6-401F-B7C4-D797972FC065}` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) 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 `Prioridades`
--

DROP TABLE IF EXISTS `Prioridades`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Prioridades` (
  `Id_Prioridad` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `Prioridad` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`Id_Prioridad`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Proveedores`
--

DROP TABLE IF EXISTS `Proveedores`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Proveedores` (
  `Id_Proveedor` int(11) NOT NULL AUTO_INCREMENT,
  `Proveedor` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `cuenta` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Domicilio` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `CP` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Localidad` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `province_id` smallint(5) unsigned DEFAULT NULL,
  `pais_id` mediumint(8) unsigned DEFAULT NULL,
  `NIF` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `oficial` tinyint(1) NOT NULL DEFAULT '1',
  `Agricola` tinyint(1) NOT NULL DEFAULT '0',
  `cuentaret` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Telefono` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Fax` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ComisionProveedor` float NOT NULL DEFAULT '0',
  `Alias` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `pay_met_id` tinyint(3) unsigned NOT NULL,
  `pay_day` tinyint(4) unsigned DEFAULT NULL,
  `pay_dem_id` tinyint(3) unsigned NOT NULL DEFAULT '7',
  `odbc_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `serious` tinyint(1) unsigned zerofill DEFAULT '1',
  `notas` text COLLATE utf8_unicode_ci,
  `postcode_id` int(11) unsigned DEFAULT NULL,
  `codpos` char(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `active` tinyint(4) DEFAULT '1',
  PRIMARY KEY (`Id_Proveedor`),
  UNIQUE KEY `cuenta` (`cuenta`),
  UNIQUE KEY `NIF` (`NIF`),
  KEY `pais_id` (`pais_id`),
  KEY `pay_met_id` (`pay_met_id`),
  KEY `province_id` (`province_id`),
  KEY `pay_dem_id` (`pay_dem_id`),
  KEY `codpos` (`codpos`,`CP`),
  CONSTRAINT `Id_Pais` FOREIGN KEY (`pais_id`) REFERENCES `Paises` (`Id`) ON UPDATE CASCADE,
  CONSTRAINT `pay_dem_id` FOREIGN KEY (`pay_dem_id`) REFERENCES `pay_dem` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `pay_met_id` FOREIGN KEY (`pay_met_id`) REFERENCES `pay_met` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `province_id` FOREIGN KEY (`province_id`) REFERENCES `province` (`province_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2775 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Proveedores_account`
--

DROP TABLE IF EXISTS `Proveedores_account`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Proveedores_account` (
  `Id_Proveedores_account` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Proveedor` int(11) NOT NULL,
  `IBAN` varchar(30) CHARACTER SET utf8 DEFAULT NULL,
  `office` varchar(4) CHARACTER SET utf8 DEFAULT NULL,
  `DC` varchar(2) CHARACTER SET utf8 DEFAULT NULL,
  `number` varchar(10) CHARACTER SET utf8 DEFAULT NULL,
  `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `bic_sufix` varchar(3) CHARACTER SET utf8 NOT NULL DEFAULT '',
  `entity_id` int(10) DEFAULT NULL,
  `Id_Banco` int(11) DEFAULT NULL,
  PRIMARY KEY (`Id_Proveedores_account`),
  KEY `fk_proveedores_proveedores_account_idx` (`Id_Proveedor`),
  KEY `fk_Proveedores_account_entity1_idx` (`entity_id`),
  KEY `fk_banco_prov_account_idx` (`Id_Banco`),
  CONSTRAINT `fk_banco_prov_account` FOREIGN KEY (`Id_Banco`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=784 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Proveedores_cargueras`
--

DROP TABLE IF EXISTS `Proveedores_cargueras`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Proveedores_cargueras` (
  `Id_Proveedor` int(11) NOT NULL,
  PRIMARY KEY (`Id_Proveedor`),
  CONSTRAINT `proveedores_cargueras_fk1` FOREIGN KEY (`Id_Proveedor`) REFERENCES `Proveedores` (`Id_Proveedor`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla de espcializacion para señalar las compañias que prestan servicio de transitario';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Proveedores_comunicados`
--

DROP TABLE IF EXISTS `Proveedores_comunicados`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Proveedores_comunicados` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Proveedor` int(11) NOT NULL,
  `escrito_id` int(11) NOT NULL,
  `fecha` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `Proveedor` (`Id_Proveedor`),
  KEY `Escrito` (`escrito_id`),
  CONSTRAINT `Proveedores_comunicados_ibfk_3` FOREIGN KEY (`Id_Proveedor`) REFERENCES `Proveedores` (`Id_Proveedor`) ON UPDATE CASCADE,
  CONSTRAINT `Proveedores_comunicados_ibfk_4` FOREIGN KEY (`escrito_id`) REFERENCES `Proveedores_escritos` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=173 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Proveedores_escritos`
--

DROP TABLE IF EXISTS `Proveedores_escritos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Proveedores_escritos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `escrito` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `informe` 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 `Proveedores_gestdoc`
--

DROP TABLE IF EXISTS `Proveedores_gestdoc`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Proveedores_gestdoc` (
  `Id_Proveedor` int(11) NOT NULL,
  `gestdoc_id` int(11) NOT NULL,
  PRIMARY KEY (`Id_Proveedor`,`gestdoc_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Recibos`
--

DROP TABLE IF EXISTS `Recibos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Recibos` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Factura` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Entregado` decimal(10,2) NOT NULL DEFAULT '0.00',
  `Pendiente` decimal(10,2) NOT NULL DEFAULT '0.00',
  `Fechacobro` datetime DEFAULT NULL,
  `Id_Trabajador` int(11) DEFAULT '0',
  `Id_Banco` int(11) DEFAULT '0',
  `Id_Cliente` int(11) DEFAULT '0',
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442',
  `conciliado` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0',
  PRIMARY KEY (`Id`),
  KEY `Id_Banco` (`Id_Banco`),
  KEY `Id_Trabajador` (`Id_Trabajador`),
  KEY `empresa_id` (`empresa_id`),
  KEY `clientDate` (`Id_Cliente`,`Fechacobro`),
  CONSTRAINT `Recibos_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `Recibos_ibfk_2` FOREIGN KEY (`Id_Banco`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE,
  CONSTRAINT `recibo_customer_id` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=563772 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 `vn2008`.`RecibosAfterInsert`
AFTER INSERT ON `Recibos`
FOR EACH ROW
	CALL bi.customer_risk_update (NEW.Id_Cliente, NEW.empresa_id, -NEW.Entregado) */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `vn2008`.`RecibosBeforeUpdate`
BEFORE UPDATE ON `Recibos`
FOR EACH ROW
BEGIN
	CALL bi.customer_risk_update (OLD.Id_Cliente, OLD.empresa_id, OLD.Entregado);
	CALL bi.customer_risk_update (NEW.Id_Cliente, NEW.empresa_id, -NEW.Entregado);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `vn2008`.`RecibosBeforeDelete`
BEFORE DELETE ON `Recibos`
FOR EACH ROW
	CALL bi.customer_risk_update (OLD.Id_Cliente, OLD.empresa_id, OLD.Entregado) */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `Recibos_recorded`
--

DROP TABLE IF EXISTS `Recibos_recorded`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Recibos_recorded` (
  `Id_Recibos` int(11) NOT NULL,
  `recorded` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'Marcado si se ha contabilizado',
  PRIMARY KEY (`Id_Recibos`),
  CONSTRAINT `Recibos_recorded_ibfk_1` FOREIGN KEY (`Id_Recibos`) REFERENCES `Recibos` (`Id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Recibos (Contrareembolso) contabilizados';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Relaciones`
--

DROP TABLE IF EXISTS `Relaciones`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Relaciones` (
  `Id_Relacion` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Contacto` int(10) unsigned NOT NULL,
  `Id_Proveedor` int(10) unsigned DEFAULT NULL,
  `Id_Cliente` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`Id_Relacion`),
  KEY `Id_Contacto` (`Id_Contacto`),
  KEY `Id_Proveedor` (`Id_Proveedor`),
  KEY `Id_Cliente` (`Id_Cliente`)
) ENGINE=InnoDB AUTO_INCREMENT=2706 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Remesas`
--

DROP TABLE IF EXISTS `Remesas`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Remesas` (
  `Id_Remesa` int(11) NOT NULL AUTO_INCREMENT,
  `Fecha Remesa` datetime DEFAULT NULL,
  `Banco` int(11) DEFAULT '0',
  `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442',
  PRIMARY KEY (`Id_Remesa`),
  KEY `Id_Banco` (`Banco`),
  KEY `empresa_id` (`empresa_id`),
  CONSTRAINT `Remesas_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `Remesas_ibfk_2` FOREIGN KEY (`Banco`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1274 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Reservas`
--

DROP TABLE IF EXISTS `Reservas`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Reservas` (
  `Id_Reserva` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Ticket` int(11) DEFAULT '0',
  `Fecha` datetime DEFAULT NULL,
  `Alias` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `article` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `medida` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `categoria` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `color` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `origen` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `cantidad` int(11) DEFAULT '0',
  `Id_Article` double DEFAULT '0',
  PRIMARY KEY (`Id_Reserva`),
  KEY `Id_1` (`Id_Ticket`),
  KEY `Id_Article` (`Id_Article`)
) ENGINE=InnoDB AUTO_INCREMENT=669 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Rutas`
--

DROP TABLE IF EXISTS `Rutas`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Rutas` (
  `Id_Ruta` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Trabajador` int(10) unsigned DEFAULT NULL,
  `Fecha` date NOT NULL,
  `Id_Vehiculo` int(10) unsigned DEFAULT NULL,
  `Id_Agencia` int(11) DEFAULT NULL,
  `Hora` datetime DEFAULT NULL,
  `ok` tinyint(1) unsigned NOT NULL DEFAULT '0',
  `km_start` mediumint(9) NOT NULL,
  `km_end` mediumint(9) NOT NULL,
  `date_start` datetime NOT NULL,
  `date_end` datetime NOT NULL,
  `gestdoc_id` int(11) DEFAULT NULL,
  `cost` double unsigned DEFAULT NULL,
  `m3` decimal(10,1) unsigned DEFAULT NULL,
  `description` text COLLATE utf8_unicode_ci,
  PRIMARY KEY (`Id_Ruta`),
  KEY `Id_Agencia` (`Id_Agencia`),
  KEY `Fecha` (`Fecha`),
  KEY `gestdoc_id` (`gestdoc_id`),
  CONSTRAINT `Rutas_ibfk_1` FOREIGN KEY (`gestdoc_id`) REFERENCES `gestdoc` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=52190 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 `vn2008`.`Rutas_BEFORE_UPDATE` BEFORE UPDATE ON `Rutas` FOR EACH ROW
BEGIN
	IF NEW.ok <> FALSE AND OLD.ok = FALSE THEN
			SET NEW.m3 = (SELECT SUM(volume)
							FROM vn2008.v_Movimientos_Volumen_shipping_charge
							WHERE Id_Ruta = NEW.Id_Ruta);
	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              = '' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `Rutas_au` AFTER UPDATE ON `Rutas` FOR EACH ROW
BEGIN
	
	IF IFNULL(NEW.gestdoc_id,0) <> IFNULL(OLD.gestdoc_id,0) AND NEW.gestdoc_id > 0 THEN
		-- JGF 09/09/14 cuando se añade un gestdoc a una ruta, se le asigna automagicamente a todos sus Tickets
		
		-- Inserta el gestdoc en todos los tickets de la ruta
		INSERT INTO tickets_gestdoc(Id_Ticket,gestdoc_id)
			SELECT Id_Ticket, NEW.gestdoc_id FROM Tickets WHERE Id_Ruta = NEW.Id_Ruta
		ON DUPLICATE KEY UPDATE gestdoc_id = NEW.gestdoc_id;

		-- Update del firmado 
		UPDATE Tickets t JOIN tickets_gestdoc tg ON t.Id_Ticket = tg.Id_Ticket 
			SET Firmado = 1  WHERE t.Id_Ruta = NEW.Id_Ruta;
	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 `Rutas_Master`
--

DROP TABLE IF EXISTS `Rutas_Master`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Rutas_Master` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `warehouse_id` smallint(6) unsigned DEFAULT NULL,
  `km` int(11) NOT NULL DEFAULT '0',
  `bultos` int(11) NOT NULL DEFAULT '0',
  `vehiculos_coste` decimal(10,2) NOT NULL DEFAULT '0.00',
  `personal_coste` decimal(10,2) NOT NULL DEFAULT '0.00',
  `vehiculos_numero` decimal(10,2) NOT NULL DEFAULT '0.00',
  `personal_numero` decimal(10,2) NOT NULL DEFAULT '0.00',
  `gasoil` int(11) NOT NULL DEFAULT '0',
  `autonomos` decimal(10,2) NOT NULL DEFAULT '0.00',
  `año` int(11) NOT NULL DEFAULT '0',
  `mes` int(11) NOT NULL DEFAULT '0',
  `gastos` decimal(10,2) NOT NULL DEFAULT '0.00',
  `bultos_autonomos` int(11) NOT NULL DEFAULT '0',
  `coste_km` decimal(10,2) NOT NULL DEFAULT '0.00',
  `coste_bulto` decimal(10,2) NOT NULL DEFAULT '0.00',
  `coste_bulto_autonomo` decimal(10,2) NOT NULL DEFAULT '0.00',
  `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `fk_rutas_warehouse_id_idx` (`warehouse_id`),
  CONSTRAINT `fk_rutas_warehouse_id` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=106 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Rutas_dits`
--

DROP TABLE IF EXISTS `Rutas_dits`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Rutas_dits` (
  `idRutas_dits` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `idaccion_dits` int(11) NOT NULL,
  `ODBC_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `Id_Ticket` int(11) unsigned NOT NULL,
  `Id_Trabajador` int(11) NOT NULL,
  `value_old` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value_new` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`idRutas_dits`),
  KEY `index2` (`idaccion_dits`),
  KEY `index3` (`Id_Ticket`),
  KEY `index4` (`Id_Trabajador`),
  CONSTRAINT `fk_Id_Trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE,
  CONSTRAINT `fk_Id_ruta` FOREIGN KEY (`Id_Ticket`) REFERENCES `Rutas` (`Id_Ruta`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fk_action_dits` FOREIGN KEY (`idaccion_dits`) REFERENCES `accion_dits` (`idaccion_dits`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=300164 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Rutas_monitor`
--

DROP TABLE IF EXISTS `Rutas_monitor`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Rutas_monitor` (
  `Id_Ruta` int(10) unsigned NOT NULL,
  `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Ubicacion` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `pedidosEncajados` int(11) DEFAULT NULL,
  `pedidosLibres` int(11) DEFAULT NULL,
  `bultos` int(11) DEFAULT NULL,
  `notas` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `pedidosProduccion` int(11) DEFAULT NULL,
  `fecha` date DEFAULT NULL,
  `dockFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`Id_Ruta`),
  KEY `Rutas_monitor_fk_2_idx` (`dockFk`),
  CONSTRAINT `Rutas_monitor_fk_1` FOREIGN KEY (`Id_Ruta`) REFERENCES `Rutas` (`Id_Ruta`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `Rutas_monitor_fk_2` FOREIGN KEY (`dockFk`) REFERENCES `dock` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Permite ubicar y controlar el estado de preparacion de las rutas';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Salarios`
--

DROP TABLE IF EXISTS `Salarios`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Salarios` (
  `Id_Trabajador` int(11) NOT NULL,
  `Salario_Bruto` double DEFAULT '0',
  `Incentivo` double DEFAULT '0',
  `SS` double DEFAULT '0',
  `warehouse_id` smallint(6) NOT NULL DEFAULT '1',
  PRIMARY KEY (`Id_Trabajador`),
  CONSTRAINT `trabajadaor_id` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Saldos_Prevision`
--

DROP TABLE IF EXISTS `Saldos_Prevision`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Saldos_Prevision` (
  `Saldos_Prevision_id` int(11) NOT NULL AUTO_INCREMENT,
  `Descripcion` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Importe` double NOT NULL DEFAULT '0',
  `Fecha` date NOT NULL,
  `Id_Banco` int(11) DEFAULT NULL,
  `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442',
  PRIMARY KEY (`Saldos_Prevision_id`),
  KEY `Fecha_indice` (`Fecha`),
  KEY `banco_prevision_idx` (`Id_Banco`),
  KEY `empresa_prevision_idx` (`empresa_id`),
  CONSTRAINT `banco_prevision` FOREIGN KEY (`Id_Banco`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE,
  CONSTRAINT `empresa_prevision` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=205 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Aqui ponemos los gastos e ingresos pendientes de introducir ';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Series`
--

DROP TABLE IF EXISTS `Series`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Series` (
  `Id_Serie` varchar(2) COLLATE utf8_unicode_ci NOT NULL,
  `Serie` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Cuenta` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`Id_Serie`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Split_lines`
--

DROP TABLE IF EXISTS `Split_lines`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Split_lines` (
  `Id_Split_lines` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Split` int(11) NOT NULL,
  `Id_Article` int(11) DEFAULT NULL,
  `Id_Compra` int(11) DEFAULT NULL,
  PRIMARY KEY (`Id_Split_lines`),
  KEY `Id_Split` (`Id_Split`),
  KEY `Id_Compra` (`Id_Compra`),
  CONSTRAINT `Id_Compra` FOREIGN KEY (`Id_Compra`) REFERENCES `Compres` (`Id_Compra`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `Split_lines_ibfk_1` FOREIGN KEY (`Id_Split`) REFERENCES `Splits` (`Id_Split`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=353542 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Splits`
--

DROP TABLE IF EXISTS `Splits`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Splits` (
  `Id_Split` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Ticket` int(11) DEFAULT NULL,
  `Id_Entrada` int(11) DEFAULT NULL,
  `Fecha` datetime DEFAULT NULL,
  `Notas` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`Id_Split`),
  KEY `Id_Entrada` (`Id_Entrada`)
) ENGINE=InnoDB AUTO_INCREMENT=36641 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Stockcontrol`
--

DROP TABLE IF EXISTS `Stockcontrol`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Stockcontrol` (
  `Id_Control` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Article` int(11) NOT NULL,
  `Id_Remitente` int(11) NOT NULL,
  `Id_Solver` int(11) NOT NULL,
  `Problema` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `Solucion` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `Listo` tinyint(1) NOT NULL,
  `Air` tinyint(1) NOT NULL,
  `Datestart` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `Dateend` datetime DEFAULT NULL,
  PRIMARY KEY (`Id_Control`),
  KEY `Id_Article` (`Id_Article`),
  KEY `Id_Remitente` (`Id_Remitente`),
  KEY `Id_Solver` (`Id_Solver`),
  CONSTRAINT `Stockcontrol_ibfk_1` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `Stockcontrol_ibfk_2` FOREIGN KEY (`Id_Remitente`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `Stockcontrol_ibfk_3` FOREIGN KEY (`Id_Solver`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=24055 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Tickets`
--

DROP TABLE IF EXISTS `Tickets`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Tickets` (
  `Id_Ticket` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Cliente` int(11) NOT NULL DEFAULT '0',
  `warehouse_id` smallint(6) unsigned NOT NULL DEFAULT '1',
  `Fecha` datetime NOT NULL,
  `Alias` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Notas` longtext COLLATE utf8_unicode_ci,
  `Factura` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `factura_id` int(10) unsigned DEFAULT NULL COMMENT 'eliminar',
  `Anotadoencaja` tinyint(1) NOT NULL DEFAULT '0',
  `Id_Consigna` int(11) NOT NULL DEFAULT '0',
  `Id_Trabajador` int(11) DEFAULT NULL,
  `Observaciones` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'eliminar',
  `Firmado` tinyint(1) NOT NULL DEFAULT '0',
  `Etiquetasemitidas` tinyint(1) NOT NULL DEFAULT '0',
  `PedidoImpreso` tinyint(1) NOT NULL DEFAULT '0',
  `Bultos` smallint(10) unsigned DEFAULT '0',
  `Localizacion` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Hora` int(11) DEFAULT '0',
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `blocked` tinyint(1) NOT NULL DEFAULT '1',
  `Solucion` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Id_Ruta` int(10) unsigned DEFAULT NULL,
  `Prioridad` tinyint(3) unsigned DEFAULT NULL,
  `priority` tinyint(1) unsigned NOT NULL DEFAULT '1',
  `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442',
  `Id_Agencia` int(11) NOT NULL,
  `landing` date DEFAULT NULL,
  `boxed` tinyint(2) NOT NULL DEFAULT '0',
  `isDeleted` tinyint(2) NOT NULL DEFAULT '0',
  PRIMARY KEY (`Id_Ticket`),
  KEY `Id_Cliente` (`Id_Cliente`),
  KEY `Id_Consigna` (`Id_Consigna`),
  KEY `Id_Trabajador` (`Id_Trabajador`),
  KEY `warehouse_id` (`warehouse_id`),
  KEY `empresa_id` (`empresa_id`),
  KEY `Id_Agencia` (`Id_Agencia`),
  KEY `Factura` (`Factura`),
  KEY `Id_Ruta` (`Id_Ruta`),
  KEY `warehouse_date` (`warehouse_id`,`Fecha`),
  KEY `Fecha` (`Fecha`,`Id_Cliente`),
  CONSTRAINT `Tickets_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `Tickets_ibfk_5` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `Tickets_ibfk_6` FOREIGN KEY (`Id_Consigna`) REFERENCES `Consignatarios` (`id_consigna`) ON UPDATE CASCADE,
  CONSTRAINT `Tickets_ibfk_8` FOREIGN KEY (`Id_Agencia`) REFERENCES `Agencias` (`Id_Agencia`),
  CONSTRAINT `Tickets_ibfk_9` FOREIGN KEY (`Id_Ruta`) REFERENCES `Rutas` (`Id_Ruta`) ON UPDATE CASCADE,
  CONSTRAINT `ticket_customer_id` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE,
  CONSTRAINT `tickets_fk10` FOREIGN KEY (`Factura`) REFERENCES `Facturas` (`Id_Factura`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2256546 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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `ticket_afterInsert`
	AFTER INSERT ON `Tickets`
    FOR EACH ROW
BEGIN
	DECLARE vEmployee INT;

	-- Borrar cuando se cambie el insert ticket en la APP móvil

	SELECT Id_Trabajador INTO vEmployee
		FROM Trabajadores WHERE user_id = account.userGetId();

	IF vEmployee IS NULL THEN
		SET vEmployee = 20;
	END IF;

	IF NEW.Id_Cliente = 400 OR NEW.Id_Cliente = 200
	THEN
		INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador)
			SELECT id, NEW.Id_Ticket, vEmployee 
				FROM state 
				WHERE `code` = 'DELIVERED';
	ELSE
		INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador)
			SELECT id, NEW.Id_Ticket, vEmployee 
				FROM state 
				WHERE `code` = 'FREE';
	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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `ticket_beforeUpdate`
	BEFORE UPDATE ON `Tickets`
    FOR EACH ROW
BEGIN
	DECLARE vAgency INT;
	DECLARE vEmployee INT;
    DECLARE vIsCee TINYINT;
    DECLARE vHasVies TINYINT;

	SELECT Id_Trabajador INTO vEmployee
		FROM Trabajadores WHERE user_id = account.userGetId();

	IF vEmployee IS NULL THEN
		SET vEmployee = 20;
	END IF;
    /*
    -- Comprobación de VIES
    
    IF NEW.empresa_id <> OLD.empresa_id AND vn.getUser() != 2 THEN
    
		SELECT CEE INTO vIsCee 
			FROM Proveedores AS pr 
				INNER JOIN Paises p ON p.Id = pr.pais_id 
            WHERE Id_Proveedor = NEW.empresa_id;
            
		SELECT isVies INTO vHasVies
			FROM vn.`client` 
            WHERE id = OLD.Id_Cliente;
            
		IF vIsCee = 1 AND NOT vHasVies Then
			CALL util.throw("NO_VALID_VIES");
		END IF;
        
    END IF;
    */

	IF NEW.Fecha < '2001-01-01'
	THEN
		SET NEW.Id_Ruta = NULL;

		IF NEW.Fecha < '2000-01-01' then
			SET NEW.Fecha = OLD.Fecha; 
		END IF;
		
		INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador)
			VALUES(17, NEW.Id_Ticket, vEmployee);
	END IF;
    
        IF NEW.isDeleted = 1 THEN
			SET NEW.Fecha = DATE_FORMAT(NEW.Fecha, '2000-%m-%d %T');
			SET NEW.landing = DATE_FORMAT(NEW.landing, '2000-%m-%d %T');
            SET NEW.Id_Ruta = 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 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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 `ticket_afterUpdate`
	AFTER UPDATE ON `Tickets`
    FOR EACH ROW
BEGIN
    IF !(NEW.Id_Ticket <=> OLD.Id_Ticket)
    OR !(NEW.warehouse_id <=> OLD.warehouse_id)
    OR !(NEW.Fecha <=> OLD.Fecha) THEN
		CALL stock.log_add('ticket', OLD.Id_Ticket, NEW.Id_Ticket);
	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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`ticket_beforeDelete`
	BEFORE DELETE ON `vn2008`.`Tickets`
    FOR EACH ROW
BEGIN
	DELETE FROM vn.sale WHERE ticketFk = OLD.Id_Ticket;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `Tickets_dits`
--

DROP TABLE IF EXISTS `Tickets_dits`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Tickets_dits` (
  `idTickets_dits` int(11) NOT NULL AUTO_INCREMENT,
  `idaccion_dits` int(11) NOT NULL,
  `ODBC_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `Id_Ticket` int(11) NOT NULL,
  `Id_Trabajador` int(11) DEFAULT NULL,
  `value_old` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value_new` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`idTickets_dits`),
  KEY `fgkey1_idx` (`idaccion_dits`),
  KEY `fgkey2_idx` (`Id_Ticket`),
  KEY `fgkey3_idx` (`Id_Trabajador`),
  CONSTRAINT `Tickets_dits_ibfk_1` FOREIGN KEY (`Id_Ticket`) REFERENCES `Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fgkey1` FOREIGN KEY (`idaccion_dits`) REFERENCES `accion_dits` (`idaccion_dits`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `fgkey3` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=64638685 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 `vn2008`.`Tickets_dits_AFTER_INSERT` AFTER INSERT ON `Tickets_dits` FOR EACH ROW
BEGIN
    DECLARE vAction TEXT;
    DECLARE message TEXT;  
    
	SELECT accion INTO vAction
		FROM vn2008.accion_dits ad 
        WHERE ad.idaccion_dits = NEW.idaccion_dits;
        
	IF COALESCE(NEW.value_old, '') <> '' OR COALESCE(NEW.value_new, '') <> '' THEN
		SET message = CONCAT(vAction, ' (', COALESCE(NEW.value_old, ''), ', ', COALESCE(NEW.value_new, ''), ')');
    ELSE
		SET message = vAction;
    END IF;
        
	INSERT INTO vn.ticketLog (originFk, userFk, `action`, description)
		VALUES (NEW.Id_Ticket, account.userGetId(), 'select', message);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `Tickets_stack`
--

DROP TABLE IF EXISTS `Tickets_stack`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Tickets_stack` (
  `Id_Ticket` int(11) NOT NULL,
  `orden` smallint(5) unsigned NOT NULL,
  `label_number` smallint(6) DEFAULT '0',
  `preparado` tinyint(4) DEFAULT '0',
  PRIMARY KEY (`Id_Ticket`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Orden para imprimir los F5.Se borra autom. lo de 2 meses';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Tickets_state`
--

DROP TABLE IF EXISTS `Tickets_state`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Tickets_state` (
  `Id_Ticket` int(11) NOT NULL DEFAULT '0',
  `inter_id` int(11) NOT NULL,
  `state_name` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`Id_Ticket`),
  KEY `double_foreign` (`Id_Ticket`,`inter_id`),
  CONSTRAINT `Id_Ticket` FOREIGN KEY (`Id_Ticket`) REFERENCES `Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `double_foreign` FOREIGN KEY (`Id_Ticket`, `inter_id`) REFERENCES `vncontrol`.`inter` (`Id_Ticket`, `inter_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 `Tickets_turno`
--

DROP TABLE IF EXISTS `Tickets_turno`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Tickets_turno` (
  `Id_Ticket` int(11) NOT NULL AUTO_INCREMENT,
  `weekDay` tinyint(1) DEFAULT NULL COMMENT 'funcion de mysql Lunes = 0, Domingo = 6',
  PRIMARY KEY (`Id_Ticket`),
  CONSTRAINT `Id_Ticket_fk` FOREIGN KEY (`Id_Ticket`) REFERENCES `Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2253858 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Tintas`
--

DROP TABLE IF EXISTS `Tintas`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Tintas` (
  `Id_Tinta` char(3) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Tinta` blob NOT NULL,
  `Orden` int(11) NOT NULL,
  `ball` blob,
  `cargex` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`Id_Tinta`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Tipos`
--

DROP TABLE IF EXISTS `Tipos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Tipos` (
  `tipo_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Tipo` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `Tipo` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `Orden` int(11) DEFAULT '0',
  `Temperatura` tinyint(1) unsigned NOT NULL DEFAULT '0',
  `reino_id` int(10) unsigned NOT NULL,
  `Id_Trabajador` int(11) NOT NULL,
  `inventory` tinyint(4) NOT NULL DEFAULT '1',
  `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `f11` tinyint(4) NOT NULL DEFAULT '0',
  `father_id` smallint(5) DEFAULT NULL,
  `transaction` tinyint(4) NOT NULL DEFAULT '0',
  `confeccion` int(10) unsigned DEFAULT NULL,
  `location` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `life` smallint(5) unsigned DEFAULT NULL,
  `maneuver` double NOT NULL DEFAULT '0.21',
  `target` double NOT NULL DEFAULT '0.15',
  `top_margin` double NOT NULL DEFAULT '0.3',
  `profit` double NOT NULL DEFAULT '0.02',
  `FV` tinyint(3) DEFAULT '1',
  `density` double NOT NULL DEFAULT '167' COMMENT 'Almacena el valor por defecto de la densidad en kg/m3 para el calculo de los portes aereos, en articulos se guarda la correcta',
  `promo` double NOT NULL DEFAULT '0',
  `box` tinyint(4) NOT NULL DEFAULT '0',
  `CYM` int(11) NOT NULL DEFAULT '0',
  `isPackaging` tinyint(1) NOT NULL DEFAULT '0',
  `hasComponents` tinyint(1) NOT NULL DEFAULT '1',
  `roleCodeFk` varchar(14) COLLATE utf8_unicode_ci DEFAULT NULL,
  `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`Id_Tipo`),
  UNIQUE KEY `tipo_id_UNIQUE` (`tipo_id`),
  UNIQUE KEY `Tipo_UNIQUE` (`Tipo`,`reino_id`),
  KEY `Trabajador` (`Id_Trabajador`),
  KEY `reino_id` (`reino_id`),
  KEY `Tipos_fk3_idx` (`confeccion`),
  KEY `tipos_fk4_idx` (`roleCodeFk`),
  KEY `warehouseFk5_idx` (`warehouseFk`),
  CONSTRAINT `Tipos_fk3` FOREIGN KEY (`confeccion`) REFERENCES `vn`.`confectionType` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `Tipos_ibfk_1` FOREIGN KEY (`reino_id`) REFERENCES `reinos` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `Tipos_ibfk_2` FOREIGN KEY (`roleCodeFk`) REFERENCES `account`.`role` (`name`) ON UPDATE CASCADE,
  CONSTRAINT `Trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE,
  CONSTRAINT `warehouseFk5` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=269 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Protege la tabla tipos de updates para los 4 parámetros de los compradores, en funcion del valor del campo CodigoRojo de tblContadores.';
/*!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 `Tipos_bu` BEFORE UPDATE ON `Tipos` FOR EACH ROW
-- Edit trigger body code below this line. Do not edit lines above this one
BEGIN
	DECLARE strCOD VARCHAR(40);

	SELECT CodigoRojo INTO strCOD FROM tblContadores LIMIT 1;

	IF strCOD <> 'tipos'
	THEN
		SET NEW.maneuver = OLD.maneuver ;
		SET NEW.target = OLD.target ;
		SET NEW.top_margin = OLD.top_margin ;
		SET NEW.profit = OLD.profit ;
	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 `Tipos_f11`
--

DROP TABLE IF EXISTS `Tipos_f11`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Tipos_f11` (
  `f11_id` tinyint(4) NOT NULL AUTO_INCREMENT,
  `description` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`f11_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 `Trabajadores`
--

DROP TABLE IF EXISTS `Trabajadores`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Trabajadores` (
  `Id_Trabajador` int(11) NOT NULL AUTO_INCREMENT,
  `CodigoTrabajador` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `Nombre` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Apellidos` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Password` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `extension` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `sub` int(11) unsigned DEFAULT NULL,
  `user` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  `Contrato_Tipo` varchar(30) CHARACTER SET utf8 DEFAULT 'no dejar vacio' COMMENT 'campo obsoleto, actualmente se rellena en laboral',
  `Categoria_Laboral` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Fecha_Inicio` datetime DEFAULT NULL,
  `Fecha_Fin` datetime DEFAULT NULL,
  `Notas` varchar(254) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Foto` blob,
  `dni` varchar(9) COLLATE utf8_unicode_ci DEFAULT NULL,
  `address` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `date_birth` date NOT NULL,
  `marital_status` enum('soltero/a','casado/a') COLLATE utf8_unicode_ci NOT NULL,
  `phone` varchar(9) COLLATE utf8_unicode_ci NOT NULL,
  `empresa_id` smallint(5) unsigned NOT NULL,
  `Id_Cliente_Interno` int(11) DEFAULT NULL,
  `user_id` int(10) unsigned DEFAULT NULL,
  `boss` int(11) NOT NULL DEFAULT '2',
  `DniExpiration` datetime DEFAULT NULL,
  `hasMachineryAutorized` tinyint(2) DEFAULT '0',
  PRIMARY KEY (`Id_Trabajador`),
  UNIQUE KEY `CodigoTrabajador_UNIQUE` (`CodigoTrabajador`),
  UNIQUE KEY `user` (`user`),
  UNIQUE KEY `user_id_UNIQUE` (`user_id`),
  UNIQUE KEY `Id_Cliente_Interno` (`Id_Cliente_Interno`),
  KEY `sub` (`sub`),
  CONSTRAINT `Clientes` FOREIGN KEY (`Id_Cliente_Interno`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE,
  CONSTRAINT `Trabajadores_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1297 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 `vn2008`.`TrabajadoresBeforeInsert`
	BEFORE INSERT ON `Trabajadores`
    FOR EACH ROW
BEGIN
	IF NEW.password = '' THEN 
		SET NEW.password = 'FALLO';
	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 `vn2008`.`TrabajadoresBeforeUpdate`
	BEFORE UPDATE ON `Trabajadores`
    FOR EACH ROW
BEGIN
	IF NEW.password = '' THEN 
		SET NEW.password = 'FALLO';
	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 `Tramos`
--

DROP TABLE IF EXISTS `Tramos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Tramos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Tramo` time NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `Tramo` (`Tramo`)
) ENGINE=InnoDB AUTO_INCREMENT=50 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `V_edi_item_track`
--

DROP TABLE IF EXISTS `V_edi_item_track`;
/*!50001 DROP VIEW IF EXISTS `V_edi_item_track`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `V_edi_item_track` AS SELECT 
 1 AS `item_id`,
 1 AS `s1`,
 1 AS `s2`,
 1 AS `s3`,
 1 AS `s4`,
 1 AS `s5`,
 1 AS `s6`,
 1 AS `kop`,
 1 AS `pac`,
 1 AS `cat`,
 1 AS `ori`,
 1 AS `pro`,
 1 AS `sub`,
 1 AS `package`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `Vehiculos`
--

DROP TABLE IF EXISTS `Vehiculos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Vehiculos` (
  `Id_Vehiculo` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Matricula` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `Modelo` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `Marca` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442',
  `m3` double DEFAULT NULL,
  `active` tinyint(4) NOT NULL DEFAULT '1',
  `warehouseFk` smallint(6) unsigned DEFAULT NULL,
  `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`Id_Vehiculo`),
  KEY `empresa_id` (`empresa_id`),
  KEY `provinceFk_idx` (`warehouseFk`),
  CONSTRAINT `Vehiculos_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `provinceFk` FOREIGN KEY (`warehouseFk`) REFERENCES `province` (`province_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=425 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Vehiculos_consumo`
--

DROP TABLE IF EXISTS `Vehiculos_consumo`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Vehiculos_consumo` (
  `Vehiculos_consumo_id` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Vehiculo` int(10) unsigned NOT NULL,
  `fecha` date NOT NULL,
  `km` int(20) unsigned NOT NULL,
  `litros` double unsigned NOT NULL,
  `precio` double unsigned NOT NULL,
  `adblue` decimal(10,2) NOT NULL DEFAULT '0.00',
  `peajes` double DEFAULT NULL,
  `descuento` double DEFAULT NULL,
  `silla` int(11) NOT NULL DEFAULT '0' COMMENT 'indica si han repostado en la gasolinera de la rotonda',
  `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `otros` double DEFAULT NULL,
  PRIMARY KEY (`Vehiculos_consumo_id`,`Id_Vehiculo`),
  KEY `fk_Vehiculos_consumo_Vehiculos_idx` (`Id_Vehiculo`),
  CONSTRAINT `fk_Vehiculos_consumo_Vehiculos` FOREIGN KEY (`Id_Vehiculo`) REFERENCES `Vehiculos` (`Id_Vehiculo`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=11249 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='En esta tabla apuntan el importe de los tickets de la gasolinera solred, con quien tenemos un contrato y nos facturan mensualmente';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `VerEspionaje`
--

DROP TABLE IF EXISTS `VerEspionaje`;
/*!50001 DROP VIEW IF EXISTS `VerEspionaje`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `VerEspionaje` AS SELECT 
 1 AS `CodigoTrabajador`,
 1 AS `Fecha`,
 1 AS `HoraEntrada`,
 1 AS `HoraSalida`,
 1 AS `Id_Equipo`,
 1 AS `Id_Trabajador`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `Vistas`
--

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

--
-- Table structure for table `XDiario`
--

DROP TABLE IF EXISTS `XDiario`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `XDiario` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ASIEN` double DEFAULT NULL,
  `FECHA` datetime DEFAULT NULL,
  `SUBCTA` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL,
  `CONTRA` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL,
  `CONCEPTO` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
  `EURODEBE` decimal(10,2) DEFAULT NULL,
  `EUROHABER` decimal(10,2) DEFAULT NULL,
  `BASEEURO` decimal(10,2) DEFAULT NULL,
  `SERIE` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `FACTURA` varchar(8) COLLATE utf8_unicode_ci DEFAULT '0',
  `BASEIMPO` decimal(10,2) DEFAULT NULL,
  `IVA` decimal(10,2) DEFAULT NULL,
  `RECEQUIV` decimal(10,2) DEFAULT '0.00',
  `DOCUMENTO` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `DEPARTA` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `CLAVE` int(11) DEFAULT NULL,
  `ESTADO` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `NCASADO` decimal(10,2) DEFAULT NULL,
  `TCASADO` decimal(10,2) DEFAULT NULL,
  `TRANS` decimal(10,2) DEFAULT NULL,
  `CAMBIO` decimal(10,2) DEFAULT NULL,
  `DEBEME` decimal(10,2) DEFAULT NULL,
  `HABERME` decimal(10,2) DEFAULT NULL,
  `PTAHABER` decimal(10,2) DEFAULT NULL,
  `AUXILIAR` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `SUCURSAL` varchar(4) COLLATE utf8_unicode_ci DEFAULT NULL,
  `PTADEBE` decimal(10,2) DEFAULT NULL,
  `CODDIVISA` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `IMPAUXME` decimal(10,2) DEFAULT NULL,
  `MONEDAUSO` varchar(1) COLLATE utf8_unicode_ci DEFAULT '2',
  `NOCONV` tinyint(1) NOT NULL DEFAULT '0',
  `NUMEROINV` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `TIPOOPE` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `NFACTICK` tinyint(1) NOT NULL DEFAULT '1',
  `TERIDNIF` tinyint(1) NOT NULL DEFAULT '2',
  `TERNIF` varchar(20) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'I.F.',
  `TERNOM` varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Nombre Importador',
  `OPBIENES` tinyint(1) NOT NULL DEFAULT '1',
  `TIPOFAC` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `TIPOIVA` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `L340` tinyint(2) NOT NULL DEFAULT '0',
  `enlazado` tinyint(1) NOT NULL DEFAULT '0',
  `FECHA_EX` date DEFAULT NULL COMMENT 'FEcha de expedicion de la factura',
  `LRECT349` tinyint(1) NOT NULL DEFAULT '0',
  `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442',
  `LDIFADUAN` tinyint(4) NOT NULL DEFAULT '0',
  `METAL` tinyint(1) NOT NULL DEFAULT '0',
  `METALIMP` decimal(10,2) NOT NULL DEFAULT '0.00',
  `CLIENTE` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL,
  `METALEJE` varchar(4) COLLATE utf8_unicode_ci DEFAULT NULL,
  `FECHA_OP` date DEFAULT NULL COMMENT 'FEcha de operacion',
  `FACTURAEX` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Numero de factura del proveedor',
  `TIPOCLAVE` int(3) DEFAULT NULL,
  `TIPOEXENCI` int(3) DEFAULT NULL,
  `TIPONOSUJE` int(3) DEFAULT NULL,
  `TIPOFACT` int(3) DEFAULT NULL,
  `TIPORECTIF` int(3) DEFAULT NULL,
  `SERIE_RT` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL,
  `FACTU_RT` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `BASEIMP_RT` decimal(10,2) DEFAULT NULL,
  `BASEIMP_RF` decimal(10,2) DEFAULT NULL,
  `RECTIFICA` int(1) NOT NULL DEFAULT '0',
  `FECHA_RT` date DEFAULT NULL,
  `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `updated` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `FECREGCON` date DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `empresa_id` (`empresa_id`),
  CONSTRAINT `XDiario_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3795836 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 `vn2008`.`XDiario_BEFORE_INSERT` BEFORE INSERT ON `XDiario` FOR EACH ROW
BEGIN
/*
	IF NEW.EURODEBE < 0 THEN
    
		SET NEW.EUROHABER = - NEW.EURODEBE;
        SET NEW.EURODEBE = NULL;
        
	END IF;

	IF NEW.EUROHABER < 0 THEN
    
		SET NEW.EURODEBE = - NEW.EUROHABER;
        SET NEW.EUROHABER = NULL;
        
	END IF;
    
	IF NEW.DEBEME < 0 THEN
    
		SET NEW.HABERME = - NEW.DEBEME;
        SET NEW.DEBEME = NULL;
        
	END IF;

	IF NEW.HABERME < 0 THEN
    
		SET NEW.DEBEME = - NEW.HABERME;
        SET NEW.HABERME = 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 `accion_dits`
--

DROP TABLE IF EXISTS `accion_dits`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `accion_dits` (
  `idaccion_dits` int(11) NOT NULL AUTO_INCREMENT,
  `accion` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`idaccion_dits`),
  UNIQUE KEY `accion_UNIQUE` (`accion`)
) ENGINE=InnoDB AUTO_INCREMENT=169 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `account_conciliacion`
--

DROP TABLE IF EXISTS `account_conciliacion`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `account_conciliacion` (
  `idaccount_conciliacion` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Proveedores_account` mediumint(8) unsigned NOT NULL,
  `Fechaoperacion` datetime NOT NULL,
  `FechaValor` datetime NOT NULL,
  `importe` double NOT NULL,
  `Concepto` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `DebeHaber` smallint(6) NOT NULL,
  `id_calculated` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`idaccount_conciliacion`),
  UNIQUE KEY `idaccount_conciliacion_UNIQUE` (`idaccount_conciliacion`),
  KEY `fg_accconciliacion_key1_idx` (`Id_Proveedores_account`),
  KEY `index_id_calculated` (`id_calculated`),
  CONSTRAINT `fg_key1_accountconc` FOREIGN KEY (`Id_Proveedores_account`) REFERENCES `Proveedores_account` (`Id_Proveedores_account`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=25763 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              = '' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`account_conciliacion_BEFORE_INSERT` 
BEFORE INSERT ON `account_conciliacion` FOR EACH ROW

set new.id_calculated = replace(
						replace(
							replace(
								replace(
										concat(new.Id_Proveedores_account,new.Fechaoperacion,new.importe,new.Concepto,new.DebeHaber)
                                        ,' ','')
									,":",'')
								,'-','')
							,'.','') */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `account_detail`
--

DROP TABLE IF EXISTS `account_detail`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `account_detail` (
  `account_detail_id` int(11) NOT NULL AUTO_INCREMENT,
  `value` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `account_detail_type_id` int(11) NOT NULL,
  `Id_Proveedores_account` mediumint(8) unsigned NOT NULL,
  PRIMARY KEY (`account_detail_id`),
  KEY `fk_account_detail_account_detail_type1_idx` (`account_detail_type_id`),
  KEY `fk_account_detail_Proveedores_account1_idx` (`Id_Proveedores_account`),
  CONSTRAINT `fk_account_detail_account_detail_type1` FOREIGN KEY (`account_detail_type_id`) REFERENCES `account_detail_type` (`account_detail_type_id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_account_detail_account_id_proveedores_account` FOREIGN KEY (`Id_Proveedores_account`) REFERENCES `Proveedores_account` (`Id_Proveedores_account`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=75 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `account_detail_type`
--

DROP TABLE IF EXISTS `account_detail_type`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `account_detail_type` (
  `account_detail_type_id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`account_detail_type_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 `accumulatorsReadingDate`
--

DROP TABLE IF EXISTS `accumulatorsReadingDate`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `accumulatorsReadingDate` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `pagoSdcfk` int(11) NOT NULL,
  `readingDate` date NOT NULL COMMENT 'dia en que se revisa la cotizacion del dolar',
  `amount` double DEFAULT NULL COMMENT 'cantidad aumentada tras la lectura del tipo de cambio',
  PRIMARY KEY (`id`),
  KEY `pagoSdcFk_idx` (`pagoSdcfk`),
  CONSTRAINT `pagoSdcFk` FOREIGN KEY (`pagoSdcfk`) REFERENCES `pago_sdc` (`pago_sdc_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=275 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `agencia_descuadre`
--

DROP TABLE IF EXISTS `agencia_descuadre`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agencia_descuadre` (
  `agencia_descuadre_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Ticket` int(11) NOT NULL,
  `date` date NOT NULL,
  `price` double(7,2) NOT NULL,
  `Consignatario` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `Tipo` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`agencia_descuadre_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `agency`
--

DROP TABLE IF EXISTS `agency`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agency` (
  `agency_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `warehouse_id` smallint(5) unsigned DEFAULT NULL COMMENT 'A nulo si se puede enrutar desde todos los almacenes',
  `por_volumen` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'Si el calculo del porte se hacer por volumen',
  `Id_Banco` int(11) NOT NULL DEFAULT '8' COMMENT 'para realizar los reembolsos',
  `warehouse_alias_id` smallint(5) unsigned DEFAULT NULL,
  `propios` tinyint(1) NOT NULL DEFAULT '0',
  `zone_label` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`agency_id`),
  KEY `warehouse_id` (`warehouse_id`),
  KEY `Id_Banco` (`Id_Banco`),
  KEY `agencias_alias_idx` (`warehouse_alias_id`),
  CONSTRAINT `agency_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `agency_ibfk_2` FOREIGN KEY (`Id_Banco`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=282 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              = '' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`agency_ai`
AFTER INSERT ON `vn2008`.`agency`
FOR EACH ROW
BEGIN
	INSERT INTO Agencias(Agencia,agency_id) VALUES(NEW.name,NEW.agency_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 */ ;

--
-- Table structure for table `agency_hour`
--

DROP TABLE IF EXISTS `agency_hour`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agency_hour` (
  `agency_hour_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `week_day` tinyint(3) unsigned DEFAULT NULL COMMENT 'funcion de mysql Lunes = 0, Domingo = 6',
  `agency_id` smallint(5) unsigned DEFAULT NULL,
  `warehouse_id` smallint(5) unsigned DEFAULT NULL,
  `province_id` smallint(5) unsigned DEFAULT NULL,
  `subtract_day` tinyint(10) unsigned NOT NULL COMMENT 'dias a restar de la Fecha de entrega',
  `max_hour` tinyint(3) unsigned NOT NULL COMMENT 'maxima hora hasta la cual se pueden hacer pedidos',
  PRIMARY KEY (`agency_hour_id`),
  UNIQUE KEY `week_day` (`week_day`,`agency_id`,`warehouse_id`,`province_id`,`max_hour`),
  KEY `agency_id` (`agency_id`),
  KEY `warehouse_id` (`warehouse_id`),
  KEY `province_id` (`province_id`),
  CONSTRAINT `agency_hour_ibfk_1` FOREIGN KEY (`agency_id`) REFERENCES `agency` (`agency_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `agency_hour_ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `agency_hour_ibfk_3` FOREIGN KEY (`province_id`) REFERENCES `province` (`province_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5656 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 `vn2008`.`agency_hourBeforeInsert` BEFORE INSERT ON `agency_hour` FOR EACH ROW
BEGIN
	DECLARE vAlreadyExists BOOLEAN DEFAULT FALSE; 
	IF NEW.week_day IS NULL AND NEW.province_id IS NULL AND NEW.subtract_day = 0 AND NEW.max_hour = 0 THEN
		CALL util.throw ('FILL_MORE_FIELDS');
	END IF;
    
    SELECT COUNT(*) INTO vAlreadyExists
	FROM vn2008.agency_hour
	 WHERE NEW.week_day <=> week_day AND NEW.province_id <=> province_id 
		AND NEW.warehouse_id <=> warehouse_id AND NEW.max_hour <=> max_hour
        AND NEW.agency_id <=> agency_id;
        
	IF vAlreadyExists > 1 THEN
		CALL util.throw('ALREADY_EXISTS');
    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 `vn2008`.`agency_hour_AFTER_UPDATE` AFTER UPDATE ON `agency_hour` FOR EACH ROW
BEGIN
DECLARE vAlreadyExists BOOLEAN DEFAULT FALSE; 

    SELECT COUNT(*) INTO vAlreadyExists
	FROM vn2008.agency_hour
	 WHERE NEW.week_day <=> week_day AND NEW.province_id <=> province_id 
		AND NEW.warehouse_id <=> warehouse_id AND NEW.max_hour <=> max_hour
        AND NEW.agency_id <=> agency_id;
        
	IF vAlreadyExists > 1 THEN
		CALL util.throw('ALREADY_EXISTS');
    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 `agency_warehouse`
--

DROP TABLE IF EXISTS `agency_warehouse`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agency_warehouse` (
  `agency_id` smallint(5) unsigned NOT NULL,
  `warehouse_id` smallint(5) unsigned NOT NULL DEFAULT '1',
  `Vista` tinyint(3) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`agency_id`,`warehouse_id`),
  KEY `warehouse_id` (`warehouse_id`),
  CONSTRAINT `agency_warehouse_ibfk_1` FOREIGN KEY (`agency_id`) REFERENCES `agency` (`agency_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `agency_warehouse_ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Indica la vista para cada agencia';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `agency_weekday_bonus`
--

DROP TABLE IF EXISTS `agency_weekday_bonus`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agency_weekday_bonus` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `warehouse_id` smallint(6) unsigned DEFAULT NULL,
  `agency_id` smallint(5) unsigned DEFAULT NULL,
  `weekDay` tinyint(3) unsigned NOT NULL,
  `zona` tinyint(4) DEFAULT NULL,
  `bonus` decimal(10,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`id`),
  UNIQUE KEY `warehouse_id` (`warehouse_id`,`agency_id`,`weekDay`,`zona`)
) ENGINE=InnoDB AUTO_INCREMENT=171 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `airline`
--

DROP TABLE IF EXISTS `airline`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `airline` (
  `airline_id` smallint(2) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`airline_id`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `airport`
--

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

--
-- Table structure for table `albaran`
--

DROP TABLE IF EXISTS `albaran`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `albaran` (
  `albaran_id` int(11) NOT NULL AUTO_INCREMENT,
  `ref` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `note` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `fecha` date NOT NULL,
  `fecha_entrega` date DEFAULT NULL,
  `valor` double DEFAULT NULL,
  `Id_Proveedor` int(11) NOT NULL,
  `empresa_id` smallint(5) unsigned NOT NULL,
  `warehouse_id` smallint(6) unsigned NOT NULL,
  `albaran_state_id` int(11) NOT NULL,
  `Id_Trabajador` int(11) NOT NULL COMMENT 'Id_Trabajador hace referencia a la persona que ha introducido el albarán',
  `Id_Responsable` int(11) NOT NULL,
  `department_id` int(11) NOT NULL,
  `recibida_id` mediumint(8) unsigned DEFAULT NULL,
  PRIMARY KEY (`albaran_id`),
  KEY `fk_albaran_Proveedores_idx` (`Id_Proveedor`),
  KEY `fk_albaran_empresa1_idx` (`empresa_id`),
  KEY `fk_albaran_warehouse1_idx` (`warehouse_id`),
  KEY `fk_albaran_albaran_state1_idx` (`albaran_state_id`),
  KEY `fk_albaran_Trabajadores1_idx` (`Id_Trabajador`),
  KEY `fk_albaran_Trabajadores2_idx` (`Id_Responsable`),
  KEY `fk_albaran_department1_idx` (`department_id`),
  KEY `fk_albaran_recibida_idx` (`recibida_id`),
  CONSTRAINT `fk_albaran_Proveedores` FOREIGN KEY (`Id_Proveedor`) REFERENCES `Proveedores` (`Id_Proveedor`) ON UPDATE CASCADE,
  CONSTRAINT `fk_albaran_Trabajadores1` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE,
  CONSTRAINT `fk_albaran_Trabajadores2` FOREIGN KEY (`Id_Responsable`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE,
  CONSTRAINT `fk_albaran_albaran_state1` FOREIGN KEY (`albaran_state_id`) REFERENCES `albaran_state` (`albaran_state_id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_albaran_department1` FOREIGN KEY (`department_id`) REFERENCES `department` (`department_id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_albaran_empresa1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_albaran_recibida` FOREIGN KEY (`recibida_id`) REFERENCES `recibida` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `fk_albaran_warehouse1` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3209 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `albaran_gestdoc`
--

DROP TABLE IF EXISTS `albaran_gestdoc`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `albaran_gestdoc` (
  `gestdoc_id` int(11) NOT NULL,
  `albaran_id` int(11) NOT NULL,
  PRIMARY KEY (`gestdoc_id`,`albaran_id`),
  KEY `fk_albaran_gestdoc_gestdoc1_idx` (`gestdoc_id`),
  KEY `fk_albaran_gestdoc_albaran1_idx` (`albaran_id`),
  CONSTRAINT `fk_albaran_gestdoc_albaran1` FOREIGN KEY (`albaran_id`) REFERENCES `albaran` (`albaran_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fk_albaran_gestdoc_gestdoc1` FOREIGN KEY (`gestdoc_id`) REFERENCES `gestdoc` (`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 `albaran_state`
--

DROP TABLE IF EXISTS `albaran_state`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `albaran_state` (
  `albaran_state_id` int(11) NOT NULL AUTO_INCREMENT,
  `state` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`albaran_state_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 `awb`
--

DROP TABLE IF EXISTS `awb`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awb` (
  `id` smallint(11) unsigned NOT NULL AUTO_INCREMENT,
  `codigo` varchar(18) COLLATE utf8_unicode_ci NOT NULL,
  `bultos` float unsigned NOT NULL,
  `peso` float unsigned DEFAULT NULL,
  `MYSQL_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `transitario_id` int(11) NOT NULL DEFAULT '582',
  `iva_id` tinyint(3) unsigned DEFAULT '62',
  `duakk` varchar(18) COLLATE utf8_unicode_ci DEFAULT NULL,
  `gestdoc_id` int(11) DEFAULT NULL,
  `importe` double NOT NULL DEFAULT '0',
  `carguera_id` int(11) DEFAULT NULL,
  `m3` double unsigned DEFAULT NULL,
  `stems` int(10) unsigned DEFAULT NULL,
  `flight_id` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `volume_weight` float unsigned DEFAULT NULL,
  `hb` decimal(10,1) unsigned DEFAULT NULL,
  `rate` decimal(10,2) unsigned DEFAULT NULL,
  `booked` datetime DEFAULT NULL,
  `issued` datetime DEFAULT NULL,
  `operated` datetime DEFAULT NULL,
  `bookEntried` date DEFAULT NULL,
  `invoiceInFk` mediumint(8) unsigned DEFAULT NULL,
  `isChecked` tinyint(3) DEFAULT '0',
  `isTransitoryChecked` tinyint(3) DEFAULT '0',
  `year` int(4) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `codigo_UNIQUE` (`codigo`,`year`),
  KEY `proveedor_id` (`transitario_id`),
  KEY `iva_id` (`iva_id`),
  KEY `carguera_id` (`carguera_id`),
  KEY `flight_id` (`flight_id`),
  KEY `awbInvoiceIn` (`invoiceInFk`),
  CONSTRAINT `awbInvoiceIn` FOREIGN KEY (`invoiceInFk`) REFERENCES `recibida` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `awbTransitoryFk` FOREIGN KEY (`transitario_id`) REFERENCES `Proveedores` (`Id_Proveedor`) ON UPDATE CASCADE,
  CONSTRAINT `awb_ibfk_1` FOREIGN KEY (`iva_id`) REFERENCES `iva_codigo` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3206 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 `vn2008`.`awb_BEFORE_INSERT` BEFORE INSERT ON `awb` FOR EACH ROW
BEGIN
	
	SET NEW.year= year(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 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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 `awb_ai` AFTER INSERT ON `awb` FOR EACH ROW
BEGIN

	DECLARE lastrecibida_id INT;
	
    -- Eliminar cuando funcione el sistema DUA
    INSERT INTO recibida(proveedor_id,fecha,empresa_id)
		VALUES(NEW.transitario_id,CURDATE(),442);

	SELECT last_insert_id() into lastrecibida_id;

	INSERT INTO awb_recibida(awb_id,recibida_id)
		VALUES(NEW.id,lastrecibida_id);
        
	-- Sistema DUA
	INSERT INTO vn.dua(awbFk)
		VALUES(NEW.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              = '' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`awb_au` AFTER UPDATE ON `awb` FOR EACH ROW
begin	

IF NEW.importe <> OLD.importe THEN 

	CALL buy_tarifas_awb(NEW.codigo);  
  
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 `awb_cargo`
--

DROP TABLE IF EXISTS `awb_cargo`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awb_cargo` (
  `awbFk` smallint(11) unsigned NOT NULL,
  `id` int(11) DEFAULT NULL,
  `awb` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL,
  `awbmaster` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL,
  `descripcion` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `numawb` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL,
  `codcliente` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL,
  `nomcliente` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `codbroker` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL,
  `nombroker` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `numawbmaster` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL,
  `codclientemaster` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL,
  `tipoawb` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `fechaexportacion` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `cupo` int(11) DEFAULT NULL,
  `pesonetocajaestiamdo` double DEFAULT NULL,
  `pesovolumencajaestiamdo` double DEFAULT NULL,
  `pesonetoestiamdo` double DEFAULT NULL,
  `pesovolumenestiamdo` double DEFAULT NULL,
  `aeropuertosalida` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `aeropuertollegada` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `codvuelo` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL,
  `numvuelo` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ruta1` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ruta2` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ruta3` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `destinofinal` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL,
  `puertodestinofinal` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `tipopago` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `codbodegaentrega` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `bodegaentrega` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `codpaletizadora` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `paletizadora` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `mrn` varchar(24) COLLATE utf8_unicode_ci DEFAULT NULL,
  `cierre` int(11) DEFAULT NULL,
  `numebarque` int(11) DEFAULT NULL,
  `pesonetocorte` double DEFAULT NULL,
  `pesovolumencorte` double DEFAULT NULL,
  `pcsreservadas` int(11) DEFAULT NULL,
  `bxsreservadas` double DEFAULT NULL,
  `pcsconfirmadas` int(11) DEFAULT NULL,
  `bxsconfirmadas` double DEFAULT NULL,
  `codlineacamion` varchar(4) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`awbFk`),
  KEY `awb_cargo_fk1_idx` (`awbFk`),
  CONSTRAINT `awb_cargo_fk1` FOREIGN KEY (`awbFk`) REFERENCES `awb` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Aloja los datos correspondientes al embarque relativos a la carguera';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `awb_component`
--

DROP TABLE IF EXISTS `awb_component`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awb_component` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `awb_id` smallint(11) unsigned DEFAULT NULL,
  `Id_Proveedor` int(11) NOT NULL,
  `Fecha` date NOT NULL,
  `awb_component_type_id` mediumint(3) unsigned DEFAULT NULL,
  `awb_role_id` tinyint(1) unsigned NOT NULL DEFAULT '1',
  `awb_unit_id` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value` decimal(10,2) DEFAULT NULL,
  `Id_Moneda` tinyint(3) unsigned NOT NULL DEFAULT '2',
  `recibida_id` mediumint(8) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_idx` (`awb_id`,`Id_Proveedor`,`awb_component_type_id`,`Fecha`),
  KEY `Id_Moneda` (`Id_Moneda`),
  KEY `awb_component_fk` (`awb_component_type_id`),
  KEY `awb_role_fk` (`awb_role_id`),
  KEY `awb_unit_fk` (`awb_unit_id`),
  CONSTRAINT `Id_Monedafk` FOREIGN KEY (`Id_Moneda`) REFERENCES `Monedas` (`Id_Moneda`) ON DELETE CASCADE,
  CONSTRAINT `awb_component_` FOREIGN KEY (`awb_component_type_id`) REFERENCES `awb_component_type` (`awb_component_type_id`) ON UPDATE CASCADE,
  CONSTRAINT `awb_role_fk` FOREIGN KEY (`awb_role_id`) REFERENCES `awb_role` (`awb_role_id`) ON UPDATE CASCADE,
  CONSTRAINT `awb_unit_fk` FOREIGN KEY (`awb_unit_id`) REFERENCES `awb_unit` (`awb_unit_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=23406 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `awb_component_template`
--

DROP TABLE IF EXISTS `awb_component_template`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awb_component_template` (
  `awb_component_template_id` int(11) NOT NULL AUTO_INCREMENT,
  `carguera_id` int(11) DEFAULT NULL,
  `airport_in` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `airport_out` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `airline_id` smallint(2) unsigned DEFAULT NULL,
  `awb_component_type_id` mediumint(3) unsigned NOT NULL,
  `Fecha` date NOT NULL,
  `awb_role_id` tinyint(1) unsigned NOT NULL,
  `awb_unit_id` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value` decimal(10,3) DEFAULT NULL,
  `max_value` decimal(10,2) unsigned DEFAULT NULL,
  `min_value` decimal(10,2) unsigned DEFAULT NULL,
  `Id_Moneda` tinyint(3) unsigned NOT NULL DEFAULT '2',
  `days` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`awb_component_template_id`),
  UNIQUE KEY `carguera_id_UNIQUE` (`carguera_id`,`airport_in`,`airport_out`,`airline_id`,`awb_component_type_id`,`Fecha`,`days`),
  KEY `Id_Moneda` (`Id_Moneda`),
  KEY `airline_idx` (`airline_id`),
  KEY `role_idx` (`awb_role_id`),
  KEY `awb_unit_fk1` (`awb_unit_id`),
  CONSTRAINT `Id_Moneda` FOREIGN KEY (`Id_Moneda`) REFERENCES `Monedas` (`Id_Moneda`) ON UPDATE CASCADE,
  CONSTRAINT `awb_unit_fk1` FOREIGN KEY (`awb_unit_id`) REFERENCES `awb_unit` (`awb_unit_id`) ON UPDATE CASCADE,
  CONSTRAINT `role_fk` FOREIGN KEY (`awb_role_id`) REFERENCES `awb_role` (`awb_role_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=783 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `awb_component_type`
--

DROP TABLE IF EXISTS `awb_component_type`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awb_component_type` (
  `awb_component_type_id` mediumint(3) unsigned NOT NULL AUTO_INCREMENT,
  `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`awb_component_type_id`)
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='	';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `awb_coordinacion`
--

DROP TABLE IF EXISTS `awb_coordinacion`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awb_coordinacion` (
  `hawb` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `awb` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL,
  `codexportador` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL,
  `nomexportador` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `pcs` int(11) DEFAULT NULL,
  `bxs` double DEFAULT NULL,
  `producto` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `numdae` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `id` int(11) DEFAULT NULL,
  `descripcion` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `awbFk` smallint(11) unsigned DEFAULT NULL,
  PRIMARY KEY (`hawb`),
  KEY `awb_coordinacion_fk1_idx` (`awbFk`),
  CONSTRAINT `awb_coordinacion_fk1` FOREIGN KEY (`awbFk`) REFERENCES `awb` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Soporta la información relativa a las facturas que componen un embarque';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `awb_daes`
--

DROP TABLE IF EXISTS `awb_daes`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awb_daes` (
  `id` int(11) NOT NULL,
  `descripcion` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `numdae` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `fechainicial` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `fechafinal` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `aeropuertosalida` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `codpais` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL,
  `codexportador` varchar(8) COLLATE utf8_unicode_ci DEFAULT NULL,
  `supplierFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`numdae`),
  KEY `awb_daes_fk1_idx` (`supplierFk`),
  CONSTRAINT `awb_daes_fk1` FOREIGN KEY (`supplierFk`) REFERENCES `Proveedores` (`Id_Proveedor`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `awb_gestdoc`
--

DROP TABLE IF EXISTS `awb_gestdoc`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awb_gestdoc` (
  `awb_gestdoc_id` int(11) NOT NULL AUTO_INCREMENT,
  `awb_id` smallint(11) unsigned NOT NULL,
  `gestdoc_id` int(11) NOT NULL,
  PRIMARY KEY (`awb_gestdoc_id`),
  KEY `awb_gestdoc_awb_fk` (`awb_id`),
  KEY `awb_gestdoc_gestdoc_fk` (`gestdoc_id`),
  CONSTRAINT `awb_gestdoc_awb_fk` FOREIGN KEY (`awb_id`) REFERENCES `awb` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `awb_gestdoc_gestdoc_fk` FOREIGN KEY (`gestdoc_id`) REFERENCES `gestdoc` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2820 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `awb_recibida`
--

DROP TABLE IF EXISTS `awb_recibida`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awb_recibida` (
  `awb_id` smallint(5) unsigned NOT NULL,
  `recibida_id` mediumint(8) unsigned NOT NULL,
  `dua` varchar(18) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`recibida_id`),
  KEY `awb_id` (`awb_id`),
  CONSTRAINT `awb_recibida_ibfk_1` FOREIGN KEY (`awb_id`) REFERENCES `awb` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `awb_recibida_ibfk_2` FOREIGN KEY (`recibida_id`) REFERENCES `recibida` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) 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              = '' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `awb_recibida_ad` AFTER DELETE ON `awb_recibida` FOR EACH ROW
IF (SELECT COUNT(*) FROM recibida_iva where recibida_id = OLD.recibida_id) = 0
	AND
	(SELECT COUNT(*) FROM recibida_vencimiento where recibida_id = OLD.recibida_id) = 0
	AND 
	(SELECT contabilizada FROM recibida WHERE id = OLD.recibida_id) = 0
THEN
	DELETE FROM recibida WHERE id = OLD.recibida_id;
END IF */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `awb_role`
--

DROP TABLE IF EXISTS `awb_role`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awb_role` (
  `awb_role_id` tinyint(1) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`awb_role_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='	';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `awb_unit`
--

DROP TABLE IF EXISTS `awb_unit`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awb_unit` (
  `awb_unit_id` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `operation` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`awb_unit_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='tipos de unidades';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `awb_volume`
--

DROP TABLE IF EXISTS `awb_volume`;
/*!50001 DROP VIEW IF EXISTS `awb_volume`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `awb_volume` AS SELECT 
 1 AS `awb_id`,
 1 AS `volume`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `balance_nest_tree`
--

DROP TABLE IF EXISTS `balance_nest_tree`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `balance_nest_tree` (
  `lft` int(11) DEFAULT NULL,
  `rgt` int(11) DEFAULT NULL,
  `name` text COLLATE utf8_unicode_ci,
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Gasto` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `isSelected` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=394 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` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Article` int(11) NOT NULL,
  `code` varchar(22) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `code` (`code`),
  UNIQUE KEY `Id_Article_2` (`Id_Article`,`code`),
  KEY `Id_Article` (`Id_Article`),
  CONSTRAINT `barcodes_ibfk_1` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=40412 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `bionic_updating_options`
--

DROP TABLE IF EXISTS `bionic_updating_options`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bionic_updating_options` (
  `buo_id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`buo_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='En esta tabla pondremos las distintas opciones que se ofrecen al comecial o al cliente al cambiar alguno de los parametros básicos de un ticket';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `botanic_export`
--

DROP TABLE IF EXISTS `botanic_export`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `botanic_export` (
  `botanic_export_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `edi_genus_id` mediumint(8) unsigned NOT NULL,
  `edi_specie_id` mediumint(8) unsigned DEFAULT NULL,
  `Id_Paises` mediumint(8) unsigned DEFAULT NULL,
  `restriction` enum('Sin restriccion','Importacion Prohibida','pasaporte fitosanitario','pasaporte individual','declaracion origen') CHARACTER SET utf8 NOT NULL,
  `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `isProtectedZone` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`botanic_export_id`),
  KEY `Id_Paises` (`Id_Paises`),
  CONSTRAINT `botanic_export_ibfk_1` FOREIGN KEY (`Id_Paises`) REFERENCES `Paises` (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=340 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Especifica los generos y especies prohibidos en paises';
/*!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 `vn2008`.`botanic_exportBeforeInsert` BEFORE INSERT ON `botanic_export` FOR EACH ROW
BEGIN
	IF (SELECT botanic_export_is_updatable (NEW.edi_genus_id, NEW.edi_specie_id, NEW.id_Paises, NEW.restriction) ) > 0	THEN
		CALL util.throw ('Datos duplicados');
    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 `businessReasonEnd`
--

DROP TABLE IF EXISTS `businessReasonEnd`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `businessReasonEnd` (
  `id` tinyint(3) NOT NULL AUTO_INCREMENT,
  `reason` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `business_labour_payrroll`
--

DROP TABLE IF EXISTS `business_labour_payrroll`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `business_labour_payrroll` (
  `business_id` int(11) NOT NULL,
  `cod_tarifa` int(11) NOT NULL,
  `cod_categoria` int(11) NOT NULL,
  `cod_contrato` int(11) NOT NULL,
  `importepactado` double NOT NULL DEFAULT '0',
  PRIMARY KEY (`business_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `buy_edi`
--

DROP TABLE IF EXISTS `buy_edi`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `buy_edi` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `barcode` char(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `entry_year` smallint(5) unsigned NOT NULL,
  `delivery_number` bigint(20) unsigned DEFAULT NULL,
  `fec` date DEFAULT NULL,
  `hor` time DEFAULT NULL,
  `now` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `ptj` mediumint(8) unsigned DEFAULT NULL,
  `ref` int(11) NOT NULL,
  `item` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `pac` int(11) DEFAULT '0',
  `qty` int(10) NOT NULL,
  `ori` varchar(3) COLLATE utf8_unicode_ci DEFAULT 'NL',
  `cat` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL,
  `agj` int(11) DEFAULT NULL,
  `kop` int(11) DEFAULT NULL,
  `ptd` varchar(6) COLLATE utf8_unicode_ci DEFAULT NULL,
  `sub` mediumint(8) unsigned DEFAULT NULL,
  `pro` mediumint(8) unsigned NOT NULL,
  `pri` double NOT NULL,
  `package` int(10) unsigned DEFAULT NULL,
  `auction` smallint(5) unsigned DEFAULT NULL,
  `klo` smallint(5) unsigned DEFAULT NULL,
  `k01` smallint(5) unsigned DEFAULT NULL,
  `k02` smallint(5) unsigned DEFAULT NULL,
  `k03` tinyint(3) unsigned DEFAULT NULL,
  `k04` tinyint(3) unsigned DEFAULT NULL,
  `s1` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `s2` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `s3` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `s4` varchar(4) COLLATE utf8_unicode_ci DEFAULT NULL,
  `s5` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `s6` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ok` tinyint(4) NOT NULL DEFAULT '0',
  `trolley_id` int(11) DEFAULT NULL,
  `putOrderFk` int(10) unsigned DEFAULT NULL,
  `scanned` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE KEY `barcode_year` (`barcode`,`entry_year`),
  UNIQUE KEY `entry_year` (`delivery_number`,`entry_year`) USING BTREE,
  KEY `ref` (`ref`),
  KEY `ptj` (`ptj`),
  KEY `pro` (`pro`),
  KEY `kop` (`kop`),
  KEY `barcode` (`barcode`),
  KEY `fec` (`fec`),
  KEY `putOrderFk` (`putOrderFk`)
) ENGINE=InnoDB AUTO_INCREMENT=914073 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `buy_edi_k012`
--

DROP TABLE IF EXISTS `buy_edi_k012`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `buy_edi_k012` (
  `buy_edi_k012_id` smallint(6) unsigned NOT NULL,
  `description` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`buy_edi_k012_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Características negativas de los articulos de subasta';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `buy_edi_k03`
--

DROP TABLE IF EXISTS `buy_edi_k03`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `buy_edi_k03` (
  `buy_edi_k03_id` tinyint(3) unsigned NOT NULL,
  `description` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`buy_edi_k03_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Características fitosanitarias de los articulos de subasta';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `buy_edi_k04`
--

DROP TABLE IF EXISTS `buy_edi_k04`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `buy_edi_k04` (
  `buy_edi_k04_id` tinyint(3) unsigned NOT NULL,
  `description` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`buy_edi_k04_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Características calidad de los articulos de subasta';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `call_information`
--

DROP TABLE IF EXISTS `call_information`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `call_information` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `Descripcio` text COLLATE utf8_unicode_ci NOT NULL,
  `Conclusio` tinyint(3) unsigned NOT NULL,
  `Id_Cliente` int(11) NOT NULL,
  `fecha` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=164 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `call_option`
--

DROP TABLE IF EXISTS `call_option`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `call_option` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `descripcion` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `cdr`
--

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

--
-- Table structure for table `chanel`
--

DROP TABLE IF EXISTS `chanel`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `chanel` (
  `chanel_id` smallint(6) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`chanel_id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Canal por el que nos ha conocido un cliente y  se ha dado de';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `chat`
--

DROP TABLE IF EXISTS `chat`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `chat` (
  `chat_id` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Trabajador` int(11) NOT NULL,
  `msg` varchar(254) COLLATE utf8_unicode_ci DEFAULT NULL,
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`chat_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Para chatear los compradores, en el frmRESERVE de la COMPARATIVA';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `city`
--

DROP TABLE IF EXISTS `city`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `city` (
  `city_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `province_id` smallint(6) unsigned DEFAULT NULL,
  `nst_geo_id` int(11) DEFAULT NULL,
  `nst_name` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`city_id`),
  UNIQUE KEY `province_city_pk` (`province_id`,`name`),
  KEY `NST_CITY_FK_idx` (`nst_geo_id`),
  CONSTRAINT `nst_geo_city` FOREIGN KEY (`nst_geo_id`) REFERENCES `nst`.`geo` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `province_city_fk` FOREIGN KEY (`province_id`) REFERENCES `province` (`province_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4423 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 `vn2008`.`city_BEFORE_INSERT` BEFORE INSERT ON `city` FOR EACH ROW
BEGIN

SET new.nst_name = new.`name`;

END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`city_AFTER_DELETE` AFTER DELETE ON `city` FOR EACH ROW
BEGIN

CALL nst.del(OLD.nst_geo_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 */ ;

--
-- Table structure for table `cl_act`
--

DROP TABLE IF EXISTS `cl_act`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cl_act` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Movimiento` int(11) DEFAULT NULL,
  `cl_main_id` int(10) unsigned NOT NULL,
  `Id_Trabajador` int(11) NOT NULL DEFAULT '20',
  `cl_sol_id` tinyint(4) DEFAULT NULL,
  `greuge` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `cl_main_id` (`cl_main_id`),
  KEY `Id_Trabajador` (`Id_Trabajador`),
  KEY `Id_Movimiento` (`Id_Movimiento`),
  KEY `cl_sol_id` (`cl_sol_id`),
  CONSTRAINT `cl_act_ibfk_1` FOREIGN KEY (`Id_Movimiento`) REFERENCES `Movimientos` (`Id_Movimiento`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `cl_act_ibfk_3` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE,
  CONSTRAINT `cl_act_ibfk_4` FOREIGN KEY (`cl_main_id`) REFERENCES `cl_main` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=106818 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Acciones en respuesta a las reclamaciones';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cl_cau`
--

DROP TABLE IF EXISTS `cl_cau`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cl_cau` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `cl_main_id` int(10) unsigned NOT NULL,
  `cl_res_id` int(10) unsigned NOT NULL DEFAULT '1',
  `Id_Trabajador` int(11) NOT NULL DEFAULT '20',
  `cl_mot_id` int(10) unsigned NOT NULL DEFAULT '1',
  `cl_con_id` int(10) unsigned NOT NULL DEFAULT '1',
  `cl_dev` tinyint(3) unsigned NOT NULL DEFAULT '1',
  `cl_sol` tinyint(3) unsigned NOT NULL DEFAULT '2',
  PRIMARY KEY (`id`),
  KEY `cl_main_id` (`cl_main_id`),
  KEY `cl_res_id` (`cl_res_id`),
  KEY `Id_Trabajador` (`Id_Trabajador`),
  KEY `cl_mot_id` (`cl_mot_id`),
  KEY `cl_con_id` (`cl_con_id`),
  KEY `cl_dev` (`cl_dev`),
  KEY `cl_sol` (`cl_sol`),
  CONSTRAINT `cl_cau_ibfk_10` FOREIGN KEY (`cl_main_id`) REFERENCES `cl_main` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `cl_cau_ibfk_11` FOREIGN KEY (`cl_dev`) REFERENCES `cl_dev` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `cl_cau_ibfk_12` FOREIGN KEY (`cl_sol`) REFERENCES `cl_sol` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `cl_cau_ibfk_6` FOREIGN KEY (`cl_res_id`) REFERENCES `cl_res` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `cl_cau_ibfk_7` FOREIGN KEY (`cl_mot_id`) REFERENCES `cl_mot` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `cl_cau_ibfk_8` FOREIGN KEY (`cl_con_id`) REFERENCES `cl_con` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `cl_cau_ibfk_9` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=55411 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Causas de las reclamaciones';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cl_con`
--

DROP TABLE IF EXISTS `cl_con`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cl_con` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `consecuencia` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Consecuencias de los motivos';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cl_dep`
--

DROP TABLE IF EXISTS `cl_dep`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cl_dep` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `departamento` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='ELIMINAR Departamentos para las quejas';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cl_det`
--

DROP TABLE IF EXISTS `cl_det`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cl_det` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `cl_main_id` int(10) unsigned NOT NULL,
  `Id_Movimiento` int(11) DEFAULT NULL,
  `cl_que_id` int(10) unsigned NOT NULL DEFAULT '1',
  `cl_pet_id` int(1) unsigned NOT NULL DEFAULT '1',
  `numero` double DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `Id_Movimiento` (`Id_Movimiento`),
  KEY `cl_main_id` (`cl_main_id`),
  CONSTRAINT `cl_det_ibfk_7` FOREIGN KEY (`Id_Movimiento`) REFERENCES `Movimientos` (`Id_Movimiento`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `cl_det_ibfk_8` FOREIGN KEY (`cl_main_id`) REFERENCES `cl_main` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=141898 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Detalle de las reclamaciones';
/*!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 `vn2008`.`cl_det_AFTER_INSERT` AFTER INSERT ON `cl_det` FOR EACH ROW
BEGIN

	DECLARE vTicket INT;
    
		SELECT s.ticketFk INTO vTicket
			FROM vn.sale s
			WHERE  s.id = NEW.Id_Movimiento;
	
    UPDATE vn.claim 
		SET ticketFk = vTicket
		WHERE id = NEW.cl_main_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 */ ;

--
-- Table structure for table `cl_dev`
--

DROP TABLE IF EXISTS `cl_dev`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cl_dev` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `devolucion` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Método por el cual el cliente nos devuelve la mercancía';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cl_est`
--

DROP TABLE IF EXISTS `cl_est`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cl_est` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `estado` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Estados posibles de las reclamaciones';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cl_main`
--

DROP TABLE IF EXISTS `cl_main`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cl_main` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Fecha` date NOT NULL,
  `cl_dep_id` tinyint(3) unsigned DEFAULT NULL,
  `cl_est_id` int(10) unsigned NOT NULL DEFAULT '1',
  `notas` text COLLATE utf8_unicode_ci,
  `Id_Cliente` int(11) NOT NULL,
  `Id_Trabajador` int(11) NOT NULL,
  `sensib` int(1) unsigned NOT NULL DEFAULT '3',
  `mana` tinyint(1) NOT NULL DEFAULT '0',
  `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `ticketFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `cl_dep_id` (`cl_dep_id`),
  KEY `cl_est_id` (`cl_est_id`),
  KEY `Id_Cliente` (`Id_Cliente`),
  KEY `Id_Trabajador` (`Id_Trabajador`),
  KEY `cl_main_ticketFk_idx` (`ticketFk`),
  CONSTRAINT `cl_main_ibfk_3` FOREIGN KEY (`cl_est_id`) REFERENCES `cl_est` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `cl_main_ibfk_4` FOREIGN KEY (`cl_dep_id`) REFERENCES `cl_dep` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `cl_main_ibfk_5` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `cl_main_ticketFk` FOREIGN KEY (`ticketFk`) REFERENCES `Tickets` (`Id_Ticket`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=62732 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Reclamaciones, tabla principal';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cl_mot`
--

DROP TABLE IF EXISTS `cl_mot`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cl_mot` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `motivo` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Motivos de las fallos';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cl_pet`
--

DROP TABLE IF EXISTS `cl_pet`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cl_pet` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `peticion` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='ELIMINAR Peticiones de los cliente en relacion a las quejas';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cl_que`
--

DROP TABLE IF EXISTS `cl_que`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cl_que` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `queja` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='ELIMINAR Queja por linea de las reclamaciones';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cl_res`
--

DROP TABLE IF EXISTS `cl_res`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cl_res` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `responsable` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `sensibility` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'if=1 >sensib >culpa',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Responsables de las causas';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cl_sol`
--

DROP TABLE IF EXISTS `cl_sol`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cl_sol` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `solucion` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `addressFk` int(10) DEFAULT NULL COMMENT 'Indica el consignatario para el ticket que regulariza el inventario',
  PRIMARY KEY (`id`),
  KEY `clSolAddressFk_idx` (`addressFk`),
  CONSTRAINT `clSolAddressFk` FOREIGN KEY (`addressFk`) REFERENCES `Consignatarios` (`id_consigna`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Solucion ofrecida a la reclamación';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `clientMana`
--

DROP TABLE IF EXISTS `clientMana`;
/*!50001 DROP VIEW IF EXISTS `clientMana`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `clientMana` AS SELECT 
 1 AS `Id_Cliente`,
 1 AS `ManaUnitario`,
 1 AS `ManaTotal`,
 1 AS `Id_Ticket`,
 1 AS `Id_Article`,
 1 AS `Concepte`,
 1 AS `Cantidad`,
 1 AS `Preu`,
 1 AS `Fecha`,
 1 AS `Id_Movimiento`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `client_observation`
--

DROP TABLE IF EXISTS `client_observation`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `client_observation` (
  `client_observation_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Cliente` int(11) NOT NULL,
  `Id_Trabajador` int(11) NOT NULL,
  `text` text COLLATE utf8_unicode_ci NOT NULL,
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`client_observation_id`),
  KEY `Id_Trabajador` (`Id_Trabajador`),
  KEY `Id_Cliente` (`Id_Cliente`),
  CONSTRAINT `client_observation_ibfk_1` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `client_observation_ibfk_2` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=74758 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Todas las observaciones referentes a un ticket';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `clientes_gestdoc`
--

DROP TABLE IF EXISTS `clientes_gestdoc`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientes_gestdoc` (
  `Id_Cliente` int(11) NOT NULL,
  `gest_doc_id` int(11) NOT NULL,
  PRIMARY KEY (`Id_Cliente`,`gest_doc_id`),
  KEY `gest_doc_id` (`gest_doc_id`),
  CONSTRAINT `clientes_gestdoc_ibfk_2` FOREIGN KEY (`gest_doc_id`) REFERENCES `gestdoc` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `clientes_gestdoc_ibfk_3` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `clientes_regalos_enc`
--

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

--
-- Table structure for table `clientes_regalos_lista_enc`
--

DROP TABLE IF EXISTS `clientes_regalos_lista_enc`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientes_regalos_lista_enc` (
  `Id_Regalo` int(11) NOT NULL AUTO_INCREMENT,
  `Descripcion` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `Activo` bit(1) NOT NULL DEFAULT b'0',
  `foto` blob,
  `datstart` date DEFAULT NULL,
  `datend` date DEFAULT NULL,
  `warehouse_id` smallint(6) unsigned DEFAULT '1',
  `province_id` smallint(5) unsigned DEFAULT NULL,
  `countryFk` smallint(5) unsigned DEFAULT NULL,
  PRIMARY KEY (`Id_Regalo`)
) ENGINE=InnoDB AUTO_INCREMENT=193 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `clientes_tipo`
--

DROP TABLE IF EXISTS `clientes_tipo`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientes_tipo` (
  `clientes_tipo_id` int(11) NOT NULL AUTO_INCREMENT,
  `code` varchar(20) CHARACTER SET utf8 NOT NULL,
  `tipo` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `isCreatedAsServed` tinyint(1) DEFAULT '0',
  PRIMARY KEY (`clientes_tipo_id`),
  UNIQUE KEY `code_UNIQUE` (`code`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Establece categorias para poder agrupar las ventas';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `commission`
--

DROP TABLE IF EXISTS `commission`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `commission` (
  `commisision_id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `percentage` tinyint(3) unsigned NOT NULL,
  `value` float unsigned NOT NULL,
  PRIMARY KEY (`commisision_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 `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(11) NOT NULL,
  `generic_item` int(11) NOT NULL COMMENT 'Id del artículo genérico',
  `edi_entry` int(11) NOT NULL COMMENT 'Entrada usada para los EKTs',
  `lastMana` int(11) NOT NULL DEFAULT '0',
  `lastNicho` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `lastReserve` varchar(10) COLLATE utf8_unicode_ci 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 `config_host`
--

DROP TABLE IF EXISTS `config_host`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `config_host` (
  `config_host_id` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `warehouse` smallint(6) unsigned NOT NULL DEFAULT '1',
  `empresa_id` smallint(6) unsigned NOT NULL DEFAULT '442',
  `caja` int(11) DEFAULT '13',
  `Id_Impresora` tinyint(3) unsigned DEFAULT '27',
  `Permanente` tinyint(1) unsigned DEFAULT '1',
  `route_days_before` smallint(6) DEFAULT '2',
  `route_days_after` smallint(6) DEFAULT '1',
  PRIMARY KEY (`config_host_id`),
  KEY `warehouse` (`warehouse`),
  KEY `empresa_id` (`empresa_id`),
  KEY `caja` (`caja`),
  KEY `Id_Impresora` (`Id_Impresora`),
  CONSTRAINT `config_host_ibfk_1` FOREIGN KEY (`caja`) REFERENCES `Bancos` (`Id_Banco`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `config_host_ibfk_2` FOREIGN KEY (`warehouse`) REFERENCES `warehouse` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `config_host_ibfk_3` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `config_host_ibfk_4` FOREIGN KEY (`Id_Impresora`) REFERENCES `Impresoras` (`Id_Impresora`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Sustituye al antiguo TPV_Settings';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `config_host_forms`
--

DROP TABLE IF EXISTS `config_host_forms`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `config_host_forms` (
  `config_host_id` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `formname` varchar(56) COLLATE utf8_unicode_ci NOT NULL,
  `x` int(8) NOT NULL,
  `y` int(8) NOT NULL,
  `h` int(8) NOT NULL,
  `l` int(8) NOT NULL,
  `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`config_host_id`,`formname`),
  CONSTRAINT `config_host_form_ibfk_1` FOREIGN KEY (`config_host_id`) REFERENCES `config_host` (`config_host_id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Registra las posiciones de los formularios';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `consignatarios_observation`
--

DROP TABLE IF EXISTS `consignatarios_observation`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `consignatarios_observation` (
  `consignatarios_observation_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Consigna` int(11) NOT NULL,
  `observation_type_id` tinyint(3) unsigned NOT NULL,
  `text` text COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`consignatarios_observation_id`),
  UNIQUE KEY `Id_Consigna` (`Id_Consigna`,`observation_type_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3821 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Observaciones de los consignatarios';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `container`
--

DROP TABLE IF EXISTS `container`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `container` (
  `container_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `Continente` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`container_id`)
) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cooler_path`
--

DROP TABLE IF EXISTS `cooler_path`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cooler_path` (
  `cooler_path_id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`cooler_path_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Define el orden en que se imprimen los F5';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cooler_path_detail`
--

DROP TABLE IF EXISTS `cooler_path_detail`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cooler_path_detail` (
  `cooler_path_detail_id` int(11) NOT NULL AUTO_INCREMENT,
  `cooler_path_id` int(11) NOT NULL DEFAULT '1',
  `pasillo` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`cooler_path_id`,`pasillo`),
  UNIQUE KEY `cooler_path_detail_id_UNIQUE` (`cooler_path_detail_id`)
) ENGINE=InnoDB AUTO_INCREMENT=721 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cp`
--

DROP TABLE IF EXISTS `cp`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cp` (
  `cp_id` int(11) NOT NULL AUTO_INCREMENT,
  `cpd` int(11) NOT NULL,
  `cph` int(11) NOT NULL,
  `zone_id` smallint(6) DEFAULT NULL,
  `town` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`cp_id`)
) ENGINE=InnoDB AUTO_INCREMENT=77 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Relacio de codis postals i el municipi al qual se asigna';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `credit`
--

DROP TABLE IF EXISTS `credit`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `credit` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Cliente` int(11) NOT NULL,
  `amount` double unsigned NOT NULL,
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `Id_Trabajador` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `workers_fk_idx` (`Id_Trabajador`),
  KEY `credit_ClienteFk` (`Id_Cliente`),
  CONSTRAINT `credit_ClienteFk` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `workers_fk` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=77168 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `credit_card`
--

DROP TABLE IF EXISTS `credit_card`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `credit_card` (
  `credit_card_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Cliente` int(10) NOT NULL,
  `number` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `expiration_month` tinyint(2) unsigned zerofill NOT NULL,
  `expiration_year` tinyint(2) unsigned zerofill NOT NULL,
  `priority` tinyint(3) unsigned NOT NULL DEFAULT '1',
  `obs` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`credit_card_id`),
  KEY `Id_Cliente` (`Id_Cliente`),
  CONSTRAINT `credit_card_ibfk_1` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=956 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cyc`
--

DROP TABLE IF EXISTS `cyc`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cyc` (
  `Id_Cliente` int(11) NOT NULL,
  `Riesgo` double DEFAULT NULL,
  `Fecha` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `cyc_id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`cyc_id`),
  KEY `Cliente` (`Id_Cliente`),
  CONSTRAINT `Cliente` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=467096 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Detalla los clientes que estan clasificados en Credito y Cau';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cyc_declaration`
--

DROP TABLE IF EXISTS `cyc_declaration`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cyc_declaration` (
  `factura_id` int(10) unsigned NOT NULL,
  `Riesgo` double DEFAULT NULL,
  `Fecha` date NOT NULL,
  `Vencimiento` int(10) NOT NULL DEFAULT '0',
  PRIMARY KEY (`factura_id`),
  CONSTRAINT `Factura` FOREIGN KEY (`factura_id`) REFERENCES `Facturas` (`factura_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Registro de las facturas declaradas a cyc';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `definitivo`
--

DROP TABLE IF EXISTS `definitivo`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `definitivo` (
  `definitivo_id` int(11) NOT NULL,
  `empresa_id` int(11) NOT NULL,
  `desde` bigint(20) NOT NULL,
  `hasta` bigint(20) NOT NULL,
  `fecha` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`definitivo_id`,`empresa_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `department`
--

DROP TABLE IF EXISTS `department`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `department` (
  `department_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `lft` int(11) NOT NULL,
  `rgt` int(11) NOT NULL,
  `Id_Trabajador` int(11) DEFAULT NULL COMMENT 'Id_Trabajador es el jefe del departamento',
  `company_id` int(11) NOT NULL,
  `father_id` int(11) DEFAULT NULL,
  `boss_id` int(11) DEFAULT NULL,
  `x` int(11) DEFAULT NULL,
  `y` int(11) DEFAULT NULL,
  `production` tinyint(4) NOT NULL DEFAULT '0',
  `isSelected` tinyint(1) NOT NULL DEFAULT '0',
  `depth` int(11) NOT NULL DEFAULT '0',
  `sons` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`department_id`),
  UNIQUE KEY `lft_UNIQUE` (`lft`),
  UNIQUE KEY `rgt_UNIQUE` (`rgt`),
  UNIQUE KEY `name_UNIQUE` (`name`),
  KEY `fk_department_Trabajadores1_idx` (`Id_Trabajador`),
  KEY `dep_org_ibfk_3_idx` (`company_id`),
  KEY `fk_department_department1_idx` (`father_id`),
  KEY `fk_department_department1_idx_idx` (`father_id`),
  CONSTRAINT `fk_department_Trabajadores1` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE,
  CONSTRAINT `fk_department_department1_idx` FOREIGN KEY (`father_id`) REFERENCES `department` (`department_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=91 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `device`
--

DROP TABLE IF EXISTS `device`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `device` (
  `device_id` int(11) NOT NULL AUTO_INCREMENT,
  `sn` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `model` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`device_id`),
  UNIQUE KEY `device_id_UNIQUE` (`device_id`),
  UNIQUE KEY `sn_UNIQUE` (`sn`)
) ENGINE=InnoDB AUTO_INCREMENT=295 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `device_user`
--

DROP TABLE IF EXISTS `device_user`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `device_user` (
  `device_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  PRIMARY KEY (`device_id`,`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `dhlKk`
--

DROP TABLE IF EXISTS `dhlKk`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dhlKk` (
  `codigo_postal` mediumint(8) unsigned NOT NULL,
  `frecuencia` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`codigo_postal`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `dock`
--

DROP TABLE IF EXISTS `dock`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dock` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `code` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
  `xPos` int(11) DEFAULT NULL,
  `yPos` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `code_UNIQUE` (`code`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Soporta la estructura de muelles de paletizacion';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `duaDismissed`
--

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

--
-- Temporary table structure for view `edi_article`
--

DROP TABLE IF EXISTS `edi_article`;
/*!50001 DROP VIEW IF EXISTS `edi_article`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `edi_article` AS SELECT 
 1 AS `id`,
 1 AS `product_name`,
 1 AS `name`,
 1 AS `plant_id`,
 1 AS `group_id`,
 1 AS `entry_date`,
 1 AS `expiry_date`,
 1 AS `change_date_time`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `edi_bucket`
--

DROP TABLE IF EXISTS `edi_bucket`;
/*!50001 DROP VIEW IF EXISTS `edi_bucket`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `edi_bucket` AS SELECT 
 1 AS `bucket_id`,
 1 AS `bucket_type_id`,
 1 AS `description`,
 1 AS `x_size`,
 1 AS `y_size`,
 1 AS `z_size`,
 1 AS `entry_date`,
 1 AS `expiry_date`,
 1 AS `change_date_time`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `edi_bucket_type`
--

DROP TABLE IF EXISTS `edi_bucket_type`;
/*!50001 DROP VIEW IF EXISTS `edi_bucket_type`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `edi_bucket_type` AS SELECT 
 1 AS `bucket_type_id`,
 1 AS `description`,
 1 AS `entry_date`,
 1 AS `expiry_date`,
 1 AS `change_date_time`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `edi_feature`
--

DROP TABLE IF EXISTS `edi_feature`;
/*!50001 DROP VIEW IF EXISTS `edi_feature`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `edi_feature` AS SELECT 
 1 AS `item_id`,
 1 AS `feature_type_id`,
 1 AS `feature_value`,
 1 AS `entry_date`,
 1 AS `expiry_date`,
 1 AS `change_date_time`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `edi_genus`
--

DROP TABLE IF EXISTS `edi_genus`;
/*!50001 DROP VIEW IF EXISTS `edi_genus`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `edi_genus` AS SELECT 
 1 AS `genus_id`,
 1 AS `latin_genus_name`,
 1 AS `entry_date`,
 1 AS `expiry_date`,
 1 AS `change_date_time`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `edi_item_feature`
--

DROP TABLE IF EXISTS `edi_item_feature`;
/*!50001 DROP VIEW IF EXISTS `edi_item_feature`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `edi_item_feature` AS SELECT 
 1 AS `item_id`,
 1 AS `presentation_order`,
 1 AS `feature`,
 1 AS `regulation_type`,
 1 AS `entry_date`,
 1 AS `expiry_date`,
 1 AS `change_date_time`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `edi_plant`
--

DROP TABLE IF EXISTS `edi_plant`;
/*!50001 DROP VIEW IF EXISTS `edi_plant`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `edi_plant` AS SELECT 
 1 AS `plant_id`,
 1 AS `genus_id`,
 1 AS `specie_id`,
 1 AS `entry_date`,
 1 AS `expiry_date`,
 1 AS `change_date_time`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `edi_specie`
--

DROP TABLE IF EXISTS `edi_specie`;
/*!50001 DROP VIEW IF EXISTS `edi_specie`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `edi_specie` AS SELECT 
 1 AS `specie_id`,
 1 AS `genus_id`,
 1 AS `latin_species_name`,
 1 AS `entry_date`,
 1 AS `expiry_date`,
 1 AS `change_date_time`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `edi_supplier`
--

DROP TABLE IF EXISTS `edi_supplier`;
/*!50001 DROP VIEW IF EXISTS `edi_supplier`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `edi_supplier` AS SELECT 
 1 AS `supplier_id`,
 1 AS `company_name`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `edi_testigos`
--

DROP TABLE IF EXISTS `edi_testigos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `edi_testigos` (
  `id` smallint(6) NOT NULL AUTO_INCREMENT,
  `table` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `field` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
  `testigo` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `edi_type`
--

DROP TABLE IF EXISTS `edi_type`;
/*!50001 DROP VIEW IF EXISTS `edi_type`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `edi_type` AS SELECT 
 1 AS `type_id`,
 1 AS `type_group_id`,
 1 AS `description`,
 1 AS `entry_date`,
 1 AS `expiry_date`,
 1 AS `change_date_time`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `edi_value`
--

DROP TABLE IF EXISTS `edi_value`;
/*!50001 DROP VIEW IF EXISTS `edi_value`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `edi_value` AS SELECT 
 1 AS `type_id`,
 1 AS `type_value`,
 1 AS `type_description`,
 1 AS `entry_date`,
 1 AS `expiry_date`,
 1 AS `change_date_time`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `emp_day_pay`
--

DROP TABLE IF EXISTS `emp_day_pay`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `emp_day_pay` (
  `id` smallint(5) unsigned NOT NULL,
  `emp_day_pay` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`id`,`emp_day_pay`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `empresa`
--

DROP TABLE IF EXISTS `empresa`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `empresa` (
  `id` smallint(5) unsigned NOT NULL,
  `abbreviation` char(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `registro` varchar(120) COLLATE utf8_unicode_ci NOT NULL,
  `gerente_id` int(11) NOT NULL,
  `alta` date NOT NULL,
  `baja` date DEFAULT NULL,
  `logo` longblob,
  `oficial` tinyint(1) unsigned NOT NULL DEFAULT '1',
  `cyc` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0',
  `rgb` varchar(6) COLLATE utf8_unicode_ci NOT NULL,
  `mail` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `cuno` blob,
  `ODBC_DATE` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
  `Id_Cliente` int(11) DEFAULT NULL,
  `digito_factura` int(2) DEFAULT NULL,
  `Id_Proveedores_account` mediumint(8) unsigned DEFAULT NULL,
  `morosidad` tinyint(4) NOT NULL DEFAULT '0',
  `empresa_grupo` int(11) NOT NULL DEFAULT '1',
  `CodigoEmpresa` int(2) DEFAULT NULL COMMENT 'Campo para movConta',
  `footnotes` longtext COLLATE utf8_unicode_ci COMMENT 'pie de paginas en las facturas',
  `phytosanitary` longtext COLLATE utf8_unicode_ci,
  PRIMARY KEY (`id`),
  KEY `gerente_id` (`gerente_id`),
  KEY `empresa_cliente_idx` (`Id_Cliente`),
  KEY `Id_Proveedores_account` (`Id_Proveedores_account`),
  KEY `empresa_grupo_fk_idx` (`empresa_grupo`),
  CONSTRAINT `empresa_cliente` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `empresa_fk4` FOREIGN KEY (`Id_Proveedores_account`) REFERENCES `Proveedores_account` (`Id_Proveedores_account`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `empresa_ibfk_1` FOREIGN KEY (`gerente_id`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE,
  CONSTRAINT `fk_empresa_grupo` FOREIGN KEY (`empresa_grupo`) REFERENCES `empresa_grupo` (`empresa_grupo_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 `empresa_grupo`
--

DROP TABLE IF EXISTS `empresa_grupo`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `empresa_grupo` (
  `empresa_grupo_id` int(11) NOT NULL AUTO_INCREMENT,
  `grupo` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`empresa_grupo_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 `entity`
--

DROP TABLE IF EXISTS `entity`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `entity` (
  `pais_id` mediumint(8) unsigned NOT NULL DEFAULT '1',
  `entity_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `bic` varchar(11) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`entity_id`),
  UNIQUE KEY `bic_UNIQUE` (`bic`),
  KEY `fg_entity1_idx` (`pais_id`),
  CONSTRAINT `fg_entity1` FOREIGN KEY (`pais_id`) REFERENCES `Paises` (`Id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=30036 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Entidades bancarias	';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `escritos`
--

DROP TABLE IF EXISTS `escritos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `escritos` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `abrev` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `descripcion` varchar(105) COLLATE utf8_unicode_ci NOT NULL,
  `visible` tinyint(4) NOT NULL DEFAULT '1',
  `hasCompany` varchar(45) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `escritos_det`
--

DROP TABLE IF EXISTS `escritos_det`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `escritos_det` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Cliente` int(10) unsigned NOT NULL,
  `escritos_id` int(10) unsigned NOT NULL,
  `fecha` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `Id_Trabajador` int(10) unsigned NOT NULL,
  `Saldo` float NOT NULL,
  `empresa_id` smallint(5) unsigned DEFAULT NULL,
  `escritos_detcol` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `userFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `empresa_id` (`empresa_id`),
  CONSTRAINT `escritos_det_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=17463 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `expeditions`
--

DROP TABLE IF EXISTS `expeditions`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expeditions` (
  `expeditions_id` int(11) NOT NULL AUTO_INCREMENT,
  `agency_id` int(11) NOT NULL,
  `ticket_id` int(10) NOT NULL,
  `EsBulto` int(11) DEFAULT '1',
  `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `reembolso` bit(1) DEFAULT b'0',
  `recogida` bit(1) DEFAULT b'0',
  `Id_Article` int(11) DEFAULT NULL,
  `counter` smallint(5) unsigned NOT NULL,
  `checked` tinyint(4) NOT NULL DEFAULT '0',
  `workerFk` int(11) DEFAULT NULL,
  `externalId` bigint(25) DEFAULT NULL,
  PRIMARY KEY (`expeditions_id`),
  KEY `index1` (`agency_id`),
  KEY `index2` (`EsBulto`),
  KEY `index3` (`odbc_date`),
  KEY `index4` (`ticket_id`),
  CONSTRAINT `Id_Agencia` FOREIGN KEY (`agency_id`) REFERENCES `Agencias` (`Id_Agencia`) ON UPDATE CASCADE,
  CONSTRAINT `ticket_id` FOREIGN KEY (`ticket_id`) REFERENCES `Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3041462 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 `expeditionsBeforeInsert`
BEFORE INSERT ON `expeditions` FOR EACH ROW
-- Edit trigger body code below this line. Do not edit lines above this one
BEGIN
	DECLARE intcounter INT;
    DECLARE vShipFk INT;

	IF NEW.EsBulto > 0 THEN 

		UPDATE Tickets SET Bultos = nz(Bultos) + 1 WHERE Id_Ticket = NEW.ticket_id;
		SELECT IFNULL(MAX(counter),0) +1 INTO intcounter FROM expeditions e 
				INNER JOIN Tickets t1 ON e.ticket_id = t1.Id_Ticket 
                LEFT JOIN vn.ticketState ts ON ts.ticket = t1.Id_Ticket
				INNER JOIN Tickets t2 ON t2.Id_Consigna = t1.Id_Consigna AND DATE(t2.Fecha) = DATE(t1.Fecha) AND t1.warehouse_id = t2.warehouse_id
			WHERE t2.Id_Ticket = NEW.ticket_id AND ts.alertLevel < 3 AND t1.empresa_id = t2.empresa_id AND t1.Id_Agencia = t2.Id_Agencia;
		SET NEW.`counter` = intcounter;
	END IF;
	SET NEW.workerFk=get_Trabajador();
    
    -- JGF 14/01/19 si existe un polizon queda anulado
    SELECT shipFk INTO vShipFk FROM vn.stowaway WHERE id = NEW.ticket_id;
    IF vShipFk THEN
		CALL vn.stowawayUnBoarding(vShipFk, NEW.ticket_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 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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 `vn2008`.`expeditionsBeforeUpdate`
BEFORE UPDATE ON `vn2008`.`expeditions`
FOR EACH ROW
-- Edit trigger body code below this line. Do not edit lines above this one
BEGIN
	IF NEW.counter <> OLD.counter THEN
		IF (SELECT COUNT(*) FROM expeditions e 
				INNER JOIN Tickets t1 ON e.ticket_id = t1.Id_Ticket
				INNER JOIN Tickets t2 ON t2.Id_Consigna = t1.Id_Consigna AND DATE(t2.Fecha) = DATE(t1.Fecha) 
			WHERE t1.Id_Ticket = NEW.ticket_id AND counter = NEW.counter) > 0 THEN
			SET NEW.expeditions_id = NULL;
		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 `vn2008`.`expeditionsBeforeDelete`
BEFORE DELETE ON `expeditions` FOR EACH ROW
BEGIN
    UPDATE Tickets SET Bultos = (SELECT COUNT(counter)-1 
		FROM expeditions WHERE ticket_id = OLD.ticket_id and EsBulto)
		WHERE Id_Ticket = OLD.ticket_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 */ ;

--
-- Table structure for table `expeditions_deleted`
--

DROP TABLE IF EXISTS `expeditions_deleted`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expeditions_deleted` (
  `expeditions_id` int(11) NOT NULL AUTO_INCREMENT,
  `agency_id` int(11) NOT NULL,
  `ticket_id` int(10) NOT NULL,
  `EsBulto` int(11) DEFAULT '1',
  `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `reembolso` bit(1) DEFAULT b'0',
  `recogida` bit(1) DEFAULT b'0',
  `Id_Article` int(11) DEFAULT NULL,
  `counter` smallint(5) unsigned NOT NULL,
  `checked` tinyint(4) NOT NULL DEFAULT '0',
  `completed` tinyint(4) DEFAULT '0',
  `expedicion` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Id_Trabajador` int(11) DEFAULT NULL,
  PRIMARY KEY (`expeditions_id`),
  KEY `index1` (`agency_id`),
  KEY `index2` (`EsBulto`),
  KEY `index3` (`odbc_date`),
  KEY `index4` (`ticket_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2445855 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `expeditions_pictures`
--

DROP TABLE IF EXISTS `expeditions_pictures`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expeditions_pictures` (
  `Id_Article` int(11) NOT NULL,
  `NoImprimirEtiqueta` bit(1) DEFAULT b'0',
  PRIMARY KEY (`Id_Article`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `filtros`
--

DROP TABLE IF EXISTS `filtros`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `filtros` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `sql` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `Estanteria` tinyint(1) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=142 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `financialProductType`
--

DROP TABLE IF EXISTS `financialProductType`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `financialProductType` (
  `id` varchar(2) COLLATE utf8_unicode_ci NOT NULL,
  `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `isAcumulattor` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `description_UNIQUE` (`description`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Distintos tipos de productos financieros: seguros de cambio, polizas de credito, acumuladores....';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `flight`
--

DROP TABLE IF EXISTS `flight`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `flight` (
  `flight_id` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `duration` tinyint(2) unsigned DEFAULT NULL,
  `route` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `days` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL,
  `airline_id` smallint(2) unsigned DEFAULT NULL,
  `airport_out` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `airport_in` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`flight_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `form_query`
--

DROP TABLE IF EXISTS `form_query`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `form_query` (
  `form_query_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `query` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `response1` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `response2` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `type_id` enum('gest_doc') COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`form_query_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 `gastos_resumen`
--

DROP TABLE IF EXISTS `gastos_resumen`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `gastos_resumen` (
  `Id_Gasto` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `year` int(4) NOT NULL,
  `month` int(2) NOT NULL,
  `importe` decimal(10,2) DEFAULT NULL,
  `empresa_id` int(11) NOT NULL,
  PRIMARY KEY (`Id_Gasto`,`year`,`month`,`empresa_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Sirve para resumir los gastos que se ponen a mano en el contaplus';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `gestdoc`
--

DROP TABLE IF EXISTS `gestdoc`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `gestdoc` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `gesttip_id` int(11) NOT NULL DEFAULT '1',
  `sref` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `brief` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,
  `emp_id` smallint(5) unsigned NOT NULL DEFAULT '791',
  `orden` mediumint(8) unsigned DEFAULT NULL,
  `file` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,
  `original` tinyint(4) NOT NULL DEFAULT '0',
  `trabajador_id` int(11) NOT NULL,
  `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `gestdoccol` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `warehouse_id` smallint(5) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `emp_id` (`emp_id`,`orden`,`warehouse_id`),
  KEY `trabajador_id` (`trabajador_id`),
  KEY `warehouse_id` (`warehouse_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1239493 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='document managment system';
/*!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 `vn2008`.`gestdoc_bi`
BEFORE INSERT ON `vn2008`.`gestdoc`
FOR EACH ROW
BEGIN

   DECLARE intORD int;
   IF NEW.warehouse_id = 44 THEN
		SET NEW.warehouse_id = 1;
	END IF;
	IF NEW.original THEN
		SELECT 1 + MAX(orden) INTO intORD FROM gestdoc WHERE emp_id = NEW.emp_id AND warehouse_id = NEW.warehouse_id ;
    
		SET NEW.orden = IFNULL(intORD,1) ;
    END IF;
-- Marca Firmado a uno cada vez que se escanea un Ticket de forma que desaparezca del TNAC JGF 27/08/13
	IF NEW.gesttip_id = 14 THEN
		UPDATE Tickets SET Firmado = 1 WHERE Id_Ticket = NEW.sref;
	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              = '' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`gestdoc_bu`
BEFORE UPDATE ON `vn2008`.`gestdoc`
FOR EACH ROW
BEGIN

	DECLARE intORD int;
	IF (NEW.original <> 0) AND (OLD.original = 0) AND (NEW.orden IS NULL) THEN

		SELECT 1 + MAX(orden) INTO intORD FROM gestdoc WHERE emp_id = NEW.emp_id  AND warehouse_id = NEW.warehouse_id;
		SET NEW.orden = IFNULL(intORD,1);

    END IF;
IF ((NEW.orden = 0) OR NEW.orden IS NULL) AND (OLD.orden <> 0)  THEN
    
		SET NEW.original = 0;
    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 `gesttip`
--

DROP TABLE IF EXISTS `gesttip`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `gesttip` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `tipo` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `path` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `writeRoleFk` int(10) unsigned DEFAULT NULL,
  `readRoleFk` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `readRoleFk` (`readRoleFk`),
  KEY `writeRoleFk` (`writeRoleFk`),
  CONSTRAINT `readRoleFk` FOREIGN KEY (`readRoleFk`) REFERENCES `account`.`role` (`id`),
  CONSTRAINT `writeRoleFk` FOREIGN KEY (`writeRoleFk`) REFERENCES `account`.`role` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `guillen`
--

DROP TABLE IF EXISTS `guillen`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `guillen` (
  `bulto` tinyint(3) unsigned NOT NULL,
  `1` float unsigned NOT NULL,
  `2` float unsigned NOT NULL,
  `re_exp` float unsigned NOT NULL,
  PRIMARY KEY (`bulto`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `guillen_carry`
--

DROP TABLE IF EXISTS `guillen_carry`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `guillen_carry` (
  `carry` tinyint(3) unsigned NOT NULL,
  `1` float unsigned NOT NULL,
  `2` float unsigned NOT NULL,
  `re_exp` float unsigned NOT NULL,
  PRIMARY KEY (`carry`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `integra2`
--

DROP TABLE IF EXISTS `integra2`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `integra2` (
  `postal_code` mediumint(8) unsigned NOT NULL,
  `frequency` tinyint(3) unsigned NOT NULL,
  `warehouse_id` smallint(5) unsigned NOT NULL,
  PRIMARY KEY (`postal_code`,`frequency`,`warehouse_id`),
  KEY `postal_code` (`postal_code`),
  KEY `warehouse_id` (`warehouse_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `integra2_escala`
--

DROP TABLE IF EXISTS `integra2_escala`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `integra2_escala` (
  `province_id` smallint(6) unsigned NOT NULL,
  `warehouse_id` smallint(6) unsigned NOT NULL,
  PRIMARY KEY (`province_id`,`warehouse_id`),
  KEY `warehouse_escala_idx` (`warehouse_id`),
  CONSTRAINT `province_escala` FOREIGN KEY (`province_id`) REFERENCES `province` (`province_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `warehouse_escala` FOREIGN KEY (`warehouse_id`) REFERENCES `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 `integra2_province`
--

DROP TABLE IF EXISTS `integra2_province`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `integra2_province` (
  `province_id` smallint(6) unsigned NOT NULL,
  `franquicia` varchar(65) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`province_id`),
  CONSTRAINT `integra2_province_id` FOREIGN KEY (`province_id`) REFERENCES `province` (`province_id`) 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 `intervalos`
--

DROP TABLE IF EXISTS `intervalos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `intervalos` (
  `id` int(11) NOT NULL,
  `hour` time 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 `intrastat_data`
--

DROP TABLE IF EXISTS `intrastat_data`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `intrastat_data` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `recibida_id` mediumint(8) unsigned NOT NULL,
  `neto` decimal(10,2) DEFAULT NULL,
  `intrastat_id` int(8) unsigned zerofill NOT NULL DEFAULT '06049190',
  `importe` double NOT NULL,
  `unidades` int(11) NOT NULL,
  `Paises_Id` mediumint(8) unsigned DEFAULT NULL,
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `valorestadistico` double NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `intrastat_id` (`intrastat_id`),
  KEY `recibida` (`recibida_id`),
  CONSTRAINT `intrastat_data_ibfk_1` FOREIGN KEY (`intrastat_id`) REFERENCES `Intrastat` (`Codintrastat`) ON UPDATE CASCADE,
  CONSTRAINT `intrastat_data_ibfk_2` FOREIGN KEY (`recibida_id`) REFERENCES `recibida` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=75627 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `invoiceCorrection`
--

DROP TABLE IF EXISTS `invoiceCorrection`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceCorrection` (
  `correctingFk` int(10) unsigned NOT NULL COMMENT 'Factura rectificativa',
  `correctedFk` int(10) unsigned NOT NULL COMMENT 'Factura rectificada',
  `cplusRectificationTypeFk` int(10) unsigned NOT NULL,
  `cplusInvoiceType477Fk` int(10) unsigned NOT NULL,
  `invoiceCorrectionTypeFk` int(11) NOT NULL DEFAULT '3',
  PRIMARY KEY (`correctingFk`),
  KEY `correctedFk_idx` (`correctedFk`),
  KEY `invoiceCorrection_ibfk_1_idx` (`cplusRectificationTypeFk`),
  KEY `cplusInvoiceTyoeFk_idx` (`cplusInvoiceType477Fk`),
  KEY `invoiceCorrectionTypeFk_idx` (`invoiceCorrectionTypeFk`),
  CONSTRAINT `corrected_fk` FOREIGN KEY (`correctedFk`) REFERENCES `Facturas` (`factura_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `correcting_fk` FOREIGN KEY (`correctingFk`) REFERENCES `Facturas` (`factura_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `cplusInvoiceTyoeFk` FOREIGN KEY (`cplusInvoiceType477Fk`) REFERENCES `vn`.`cplusInvoiceType477` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `invoiceCorrectionType_Fk33` FOREIGN KEY (`invoiceCorrectionTypeFk`) REFERENCES `vn`.`invoiceCorrectionType` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `invoiceCorrection_ibfk_1` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `vn`.`cplusRectificationType` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Relacion entre las facturas rectificativas y las rectificadas.';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `invoice_observation`
--

DROP TABLE IF EXISTS `invoice_observation`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoice_observation` (
  `invoice_observation_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `desde` date NOT NULL,
  `hasta` date NOT NULL,
  `serie` varchar(1) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0',
  `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '0',
  `text` text COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`invoice_observation_id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `itemTag`
--

DROP TABLE IF EXISTS `itemTag`;
/*!50001 DROP VIEW IF EXISTS `itemTag`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemTag` AS SELECT 
 1 AS `id`,
 1 AS `itemFk`,
 1 AS `tagFk`,
 1 AS `value`,
 1 AS `priority`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `item_entry_in`
--

DROP TABLE IF EXISTS `item_entry_in`;
/*!50001 DROP VIEW IF EXISTS `item_entry_in`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `item_entry_in` AS SELECT 
 1 AS `warehouse_id`,
 1 AS `dat`,
 1 AS `item_id`,
 1 AS `amount`,
 1 AS `received`,
 1 AS `isVirtualStock`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `item_entry_out`
--

DROP TABLE IF EXISTS `item_entry_out`;
/*!50001 DROP VIEW IF EXISTS `item_entry_out`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `item_entry_out` AS SELECT 
 1 AS `warehouse_id`,
 1 AS `dat`,
 1 AS `item_id`,
 1 AS `amount`,
 1 AS `delivered`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `item_out`
--

DROP TABLE IF EXISTS `item_out`;
/*!50001 DROP VIEW IF EXISTS `item_out`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `item_out` AS SELECT 
 1 AS `warehouse_id`,
 1 AS `dat`,
 1 AS `item_id`,
 1 AS `amount`,
 1 AS `ok`,
 1 AS `Reservado`,
 1 AS `invoice`,
 1 AS `saleFk`,
 1 AS `ticketFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `iva_codigo`
--

DROP TABLE IF EXISTS `iva_codigo`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `iva_codigo` (
  `id` tinyint(2) unsigned NOT NULL AUTO_INCREMENT,
  `fecha` date NOT NULL,
  `codigo` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `iva_tipo_id` tinyint(2) NOT NULL,
  `iva` decimal(4,1) NOT NULL DEFAULT '0.0',
  `recargo` decimal(4,1) NOT NULL DEFAULT '0.0',
  `tipo` char(1) COLLATE utf8_unicode_ci NOT NULL,
  `link` tinyint(4) unsigned NOT NULL DEFAULT '0' COMMENT 'las que tienen el mismo valor se contabilizan emparejadas',
  `isActive` tinyint(2) NOT NULL DEFAULT '1',
  `updated` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `transactionCode` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `iva_tipo_id` (`iva_tipo_id`),
  KEY `codigo` (`codigo`),
  KEY `tipo_index` (`tipo`),
  CONSTRAINT `iva_codigo_ibfk_1` FOREIGN KEY (`iva_tipo_id`) REFERENCES `iva_tipo` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=123 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `iva_group`
--

DROP TABLE IF EXISTS `iva_group`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `iva_group` (
  `iva_group_id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `description` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `code` varchar(1) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'R',
  PRIMARY KEY (`iva_group_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 `iva_group_codigo`
--

DROP TABLE IF EXISTS `iva_group_codigo`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `iva_group_codigo` (
  `iva_group_id` tinyint(3) unsigned NOT NULL,
  `date` date NOT NULL,
  `iva_codigo_id` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`iva_group_id`,`date`,`iva_codigo_id`),
  KEY `iva_codigo_id` (`iva_codigo_id`),
  CONSTRAINT `iva_group_codigo_ibfk_1` FOREIGN KEY (`iva_group_id`) REFERENCES `iva_group` (`iva_group_id`) ON UPDATE CASCADE,
  CONSTRAINT `iva_group_codigo_ibfk_2` FOREIGN KEY (`iva_codigo_id`) REFERENCES `iva_codigo` (`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 `iva_tipo`
--

DROP TABLE IF EXISTS `iva_tipo`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `iva_tipo` (
  `id` tinyint(2) NOT NULL AUTO_INCREMENT,
  `alias` varchar(6) COLLATE utf8_unicode_ci NOT NULL,
  `isAccrued` tinyint(4) NOT NULL DEFAULT '0',
  `serie_id` char(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `TIPOOPE` varchar(1) COLLATE utf8_unicode_ci NOT NULL DEFAULT ' ',
  `descripcion` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `Id_Pais` mediumint(8) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `serie_id` (`serie_id`),
  KEY `Id_Pais` (`Id_Pais`),
  CONSTRAINT `iva_tipo_ibfk_1` FOREIGN KEY (`Id_Pais`) REFERENCES `Paises` (`Id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `jerarquia`
--

DROP TABLE IF EXISTS `jerarquia`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `jerarquia` (
  `worker_id` int(11) NOT NULL,
  `boss_id` int(11) NOT NULL,
  `vinculado` tinyint(3) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`worker_id`,`boss_id`),
  KEY `worker_trabajador` (`worker_id`),
  KEY `boss_trabajador` (`boss_id`),
  CONSTRAINT `boss_trabajador` FOREIGN KEY (`boss_id`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE,
  CONSTRAINT `worker_trabajador` FOREIGN KEY (`worker_id`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE
) ENGINE=InnoDB 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) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `active` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`code`)
) ENGINE=InnoDB 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_Cliente` int(11) NOT NULL,
  `Id_Proveedor` int(11) NOT NULL,
  PRIMARY KEY (`Id_Cliente`,`Id_Proveedor`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `log_articles`
--

DROP TABLE IF EXISTS `log_articles`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `log_articles` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Article` int(11) NOT NULL,
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `Fecha_old` datetime DEFAULT NULL,
  `cantidad_old` double DEFAULT NULL,
  `Id_Ticket_old` int(11) DEFAULT NULL,
  `wh_old` smallint(6) unsigned DEFAULT NULL,
  `Fecha_new` datetime DEFAULT NULL,
  `cantidad_new` double DEFAULT NULL,
  `Id_Ticket_new` int(11) DEFAULT NULL,
  `wh_new` smallint(6) DEFAULT NULL,
  `accion` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `Id_Article_log` (`Id_Article`),
  KEY `Id_Ticket_log` (`Id_Ticket_old`),
  KEY `Id_Ticket_new_log` (`Id_Ticket_new`),
  CONSTRAINT `Id_Article_log_Articles` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los movimientos de los articulos para intentar encontrar los procesos que generan negativos';
/*!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` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `to` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `reply_to` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `subject` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `text` text COLLATE utf8_unicode_ci NOT NULL,
  `sent` tinyint(2) NOT NULL DEFAULT '0',
  `DATE_ODBC` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `path` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `error` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'OK',
  `senderFk` int(11) DEFAULT NULL,
  `recipientFk` int(11) DEFAULT NULL,
  `plainTextBody` text COLLATE utf8_unicode_ci,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1716246 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `mail_templates`
--

DROP TABLE IF EXISTS `mail_templates`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mail_templates` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `countryCode` char(2) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'ES',
  `name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `subject` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `body` text COLLATE utf8_unicode_ci NOT NULL,
  `attachment` text COLLATE utf8_unicode_ci,
  PRIMARY KEY (`id`,`countryCode`,`name`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `manaByTicket`
--

DROP TABLE IF EXISTS `manaByTicket`;
/*!50001 DROP VIEW IF EXISTS `manaByTicket`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `manaByTicket` AS SELECT 
 1 AS `Id_Ticket`,
 1 AS `Fecha`,
 1 AS `Id_Cliente`,
 1 AS `mana`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `mandato`
--

DROP TABLE IF EXISTS `mandato`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mandato` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Cliente` int(11) NOT NULL,
  `empresa_id` smallint(5) unsigned NOT NULL,
  `Id_mandato` varchar(32) COLLATE utf8_unicode_ci DEFAULT NULL,
  `FAlta` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `Fbaja` timestamp NULL DEFAULT NULL,
  `idmandato_tipo` smallint(5) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `mandato_fgkey1_idx` (`Id_Cliente`),
  KEY `mandato_fgkey2_idx` (`empresa_id`),
  KEY `mandato_fgkey3_idx` (`idmandato_tipo`),
  CONSTRAINT `mandato_fgkey1` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `mandato_fgkey2` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `mandato_fgkey3` FOREIGN KEY (`idmandato_tipo`) REFERENCES `mandato_tipo` (`idmandato_tipo`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=16433 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              = '' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 trigger mandato_ins before insert
on mandato
for each row
begin
	if (NEW.Id_mandato IS NULL) THEN
		SET NEW.Id_mandato=CONCAT(NEW.Id_Cliente,'-',(SELECT AUTO_INCREMENT 
		from information_schema.TABLES 
		where TABLE_SCHEMA='vn2008' and TABLE_NAME='mandato'));
    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 `mandato_tipo`
--

DROP TABLE IF EXISTS `mandato_tipo`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mandato_tipo` (
  `idmandato_tipo` smallint(5) NOT NULL AUTO_INCREMENT,
  `Nombre` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`idmandato_tipo`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `movement_label`
--

DROP TABLE IF EXISTS `movement_label`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `movement_label` (
  `Id_movimiento` int(11) NOT NULL,
  `label` mediumint(8) unsigned NOT NULL,
  `stem` mediumint(8) unsigned NOT NULL,
  PRIMARY KEY (`Id_movimiento`),
  CONSTRAINT `movement_label_ibfk_1` FOREIGN KEY (`Id_movimiento`) REFERENCES `Movimientos` (`Id_Movimiento`) ON DELETE CASCADE ON UPDATE CASCADE
) 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              = '' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `movement_label_au` AFTER UPDATE ON `movement_label` FOR EACH ROW
-- Edit trigger body code below this line. Do not edit lines above this one
IF NEW.stem >= (SELECT Cantidad FROM Movimientos WHERE Id_Movimiento = NEW.Id_Movimiento) THEN
	UPDATE Movimientos SET OK = 1 WHERE Id_Movimiento = NEW.Id_Movimiento;
END IF */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `nichos`
--

DROP TABLE IF EXISTS `nichos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `nichos` (
  `id` varchar(5) 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 `observation_type`
--

DROP TABLE IF EXISTS `observation_type`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `observation_type` (
  `observation_type_id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `description` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`observation_type_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `order`
--

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

--
-- Table structure for table `order_Tickets`
--

DROP TABLE IF EXISTS `order_Tickets`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `order_Tickets` (
  `order_id` int(10) unsigned NOT NULL,
  `Id_Ticket` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`Id_Ticket`,`order_id`),
  KEY `order_id` (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

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

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

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

--
-- Table structure for table `pago`
--

DROP TABLE IF EXISTS `pago`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `pago` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `fecha` date NOT NULL,
  `id_proveedor` int(11) NOT NULL,
  `importe` decimal(10,2) NOT NULL DEFAULT '0.00',
  `id_moneda` tinyint(3) unsigned NOT NULL DEFAULT '1',
  `divisa` decimal(10,2) DEFAULT NULL,
  `id_banco` int(11) NOT NULL DEFAULT '0',
  `pay_met_id` tinyint(3) unsigned NOT NULL,
  `g_bancarios` double(6,2) unsigned NOT NULL DEFAULT '0.00',
  `concepte` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,
  `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442',
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `conciliado` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0',
  `pago_sdc_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `empresa_id` (`empresa_id`),
  KEY `id_banco` (`id_banco`),
  KEY `id_moneda` (`id_moneda`),
  KEY `pay_met` (`pay_met_id`),
  KEY `proveedor_pago` (`id_proveedor`),
  KEY `fk_pago_pago_sdc1_idx` (`pago_sdc_id`),
  CONSTRAINT `pago_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `pago_ibfk_2` FOREIGN KEY (`id_banco`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE,
  CONSTRAINT `pago_moneda` FOREIGN KEY (`id_moneda`) REFERENCES `Monedas` (`Id_Moneda`) ON UPDATE CASCADE,
  CONSTRAINT `pago_pay_met` FOREIGN KEY (`pay_met_id`) REFERENCES `pay_met` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `proveedor_pago` FOREIGN KEY (`id_proveedor`) REFERENCES `Proveedores` (`Id_Proveedor`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=48841 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 `pago_bi` BEFORE INSERT ON `pago` FOR EACH ROW
-- Edit trigger body code below this line. Do not edit lines above this one
BEGIN
		DECLARE cuenta_banco,cuenta_proveedor DOUBLE;
		DECLARE max_asien INT;
        DECLARE bolCASH BOOLEAN;
        
       
        
        -- PAK 10/02/15 No se asientan los pagos directamente, salvo en el caso de las cajas de CASH
        SELECT (cash = 1) INTO bolCASH FROM Bancos WHERE Bancos.Id_Banco = NEW.id_banco ;
        
        IF bolCASH  THEN -- AND NEW.id_pago <> 1
        
					SELECT Cuenta INTO cuenta_banco FROM Bancos WHERE Id_Banco = NEW.id_banco;
					SELECT Cuenta INTO cuenta_proveedor FROM Proveedores WHERE Id_Proveedor=NEW.id_proveedor;
					SELECT MAX(asien)+1 INTO max_asien FROM XDiario;
					
					INSERT INTO XDiario (ASIEN,FECHA,SUBCTA,CONTRA,CONCEPTO,EURODEBE,EUROHABER,empresa_id)
						SELECT max_asien,NEW.fecha,SUBCTA,CONTRA,NEW.concepte,EURODEBE,EUROHABER,NEW.empresa_id FROM
							( SELECT cuenta_banco SUBCTA,cuenta_proveedor CONTRA,
								0 EURODEBE, NEW.importe + NEW.g_bancarios EUROHABER
					UNION ALL
						SELECT cuenta_proveedor SUBCTA, cuenta_banco CONTRA,
							NEW.importe EURODEBE, 0 EUROHABER) gf;
						
					IF NEW.g_bancarios <> 0 THEN
						INSERT INTO XDiario (ASIEN,FECHA,SUBCTA,CONTRA,CONCEPTO,EURODEBE,EUROHABER,empresa_id)
						SELECT max_asien,NEW.fecha,IF(Id = 1,6260000002,IF(CEE = 1,6260000003,6260000004)),cuenta_banco,NEW.concepte,
							NEW.g_bancarios,0,NEW.empresa_id FROM Proveedores pr 
						JOIN Paises pa ON pr.pais_id = pa.Id WHERE Id_Proveedor = NEW.id_proveedor;
					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 `pago_sdc`
--

DROP TABLE IF EXISTS `pago_sdc`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `pago_sdc` (
  `pago_sdc_id` int(11) NOT NULL AUTO_INCREMENT,
  `importe` decimal(10,2) NOT NULL,
  `fecha` date NOT NULL,
  `vencimiento` date NOT NULL,
  `entity_id` int(10) unsigned NOT NULL,
  `ref` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `rate` decimal(10,4) NOT NULL,
  `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442',
  `financialProductTypefk` varchar(2) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'SC',
  `pago_sdccol` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `upperBarrier` decimal(10,2) DEFAULT NULL,
  `lowerBarrier` decimal(10,2) DEFAULT NULL,
  `strike` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`pago_sdc_id`),
  KEY `empresa_sdc_idx` (`empresa_id`),
  KEY `financial_type_fk_idx` (`financialProductTypefk`),
  KEY `pago_sdc_entity_fk_idx` (`entity_id`),
  CONSTRAINT `empresa_sdc` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `financial_type_fk` FOREIGN KEY (`financialProductTypefk`) REFERENCES `financialProductType` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `pago_sdc_entity_fk` FOREIGN KEY (`entity_id`) REFERENCES `entity` (`entity_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=49 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Seguros de cambio';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `pay_dem`
--

DROP TABLE IF EXISTS `pay_dem`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `pay_dem` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `pay_dem` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `pay_dem_det`
--

DROP TABLE IF EXISTS `pay_dem_det`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `pay_dem_det` (
  `id` tinyint(3) unsigned NOT NULL,
  `detalle` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`id`,`detalle`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `pay_met`
--

DROP TABLE IF EXISTS `pay_met`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `pay_met` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `solucion` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `deudaviva` tinyint(3) unsigned zerofill NOT NULL DEFAULT '000',
  `graceDays` int(11) unsigned NOT NULL DEFAULT '0',
  `ibanRequired` tinyint(3) DEFAULT '0',
  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 `payroll_basess`
--

DROP TABLE IF EXISTS `payroll_basess`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payroll_basess` (
  `id_payroll_Basess` int(11) NOT NULL AUTO_INCREMENT,
  `empresa_id` int(10) NOT NULL,
  `id_tipobasess` int(11) NOT NULL,
  `valor` double NOT NULL,
  `fechadesde` date NOT NULL,
  `fechahasta` date DEFAULT NULL,
  `contratotemporal` tinyint(1) DEFAULT '0',
  PRIMARY KEY (`id_payroll_Basess`),
  KEY `payroll_basess_1_idx` (`id_tipobasess`),
  KEY `payroll_basess_2_idx` (`empresa_id`),
  CONSTRAINT `payroll_basess_1` FOREIGN KEY (`id_tipobasess`) REFERENCES `payroll_tipobasess` (`id_payroll_tipobasess`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `payroll_basess_2` FOREIGN KEY (`empresa_id`) REFERENCES `payroll_centros` (`empresa_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 `payroll_bonificaciones`
--

DROP TABLE IF EXISTS `payroll_bonificaciones`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payroll_bonificaciones` (
  `codtrabajador` int(11) NOT NULL,
  `codempresa` int(11) NOT NULL,
  `Fecha` date NOT NULL,
  `bonificacionSS` double NOT NULL,
  PRIMARY KEY (`codtrabajador`,`codempresa`,`Fecha`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `payroll_categorias`
--

DROP TABLE IF EXISTS `payroll_categorias`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payroll_categorias` (
  `codcategoria` int(11) NOT NULL,
  `descripcion` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `Tarifa` tinyint(4) NOT NULL,
  PRIMARY KEY (`codcategoria`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `payroll_centros`
--

DROP TABLE IF EXISTS `payroll_centros`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payroll_centros` (
  `cod_centro` int(11) NOT NULL,
  `Centro` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `nss_cotizacion` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `domicilio` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `poblacion` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `cp` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
  `empresa_id` int(10) NOT NULL,
  `codempresa` int(11) DEFAULT NULL,
  PRIMARY KEY (`cod_centro`,`empresa_id`),
  KEY `payroll_centros_ix1` (`empresa_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `payroll_conceptos`
--

DROP TABLE IF EXISTS `payroll_conceptos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payroll_conceptos` (
  `conceptoid` int(11) NOT NULL,
  `concepto` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`conceptoid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `payroll_contratos`
--

DROP TABLE IF EXISTS `payroll_contratos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payroll_contratos` (
  `CodContrato` int(11) NOT NULL,
  `TipoCotizacion` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `DescContrato` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`CodContrato`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `payroll_datos`
--

DROP TABLE IF EXISTS `payroll_datos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payroll_datos` (
  `codtrabajador` int(11) NOT NULL,
  `codempresa` int(10) NOT NULL,
  `Fecha` date NOT NULL,
  `conceptoid` int(11) NOT NULL,
  `orden` tinyint(4) DEFAULT NULL,
  `dias` smallint(6) DEFAULT NULL,
  `Importe` decimal(8,2) NOT NULL,
  `DH` tinyint(4) DEFAULT NULL,
  `T_Paga` tinyint(4) NOT NULL,
  `TributaIRPF` tinyint(4) NOT NULL,
  PRIMARY KEY (`codtrabajador`,`codempresa`,`conceptoid`,`Fecha`),
  KEY `fgkey_payrolldatos_1_idx` (`conceptoid`),
  CONSTRAINT `fgkey_payrolldatos_1` FOREIGN KEY (`conceptoid`) REFERENCES `payroll_conceptos` (`conceptoid`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `payroll_embargos`
--

DROP TABLE IF EXISTS `payroll_embargos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payroll_embargos` (
  `codtrabajador` int(11) NOT NULL,
  `codempresa` int(10) NOT NULL,
  `conceptoid` int(11) NOT NULL,
  `Fecha` date NOT NULL,
  `pagado` double NOT NULL,
  `pendiente` double DEFAULT NULL,
  `total` double NOT NULL,
  PRIMARY KEY (`codtrabajador`,`codempresa`,`Fecha`,`conceptoid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `payroll_employee`
--

DROP TABLE IF EXISTS `payroll_employee`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payroll_employee` (
  `CodTrabajador` int(11) NOT NULL,
  `Person_id` int(11) NOT NULL,
  `nss` varchar(23) COLLATE utf8_unicode_ci NOT NULL,
  `codpuesto` int(10) NOT NULL,
  `codempresa` int(10) NOT NULL,
  `codcontrato` int(10) NOT NULL,
  `FAntiguedad` date NOT NULL,
  `grupotarifa` int(10) NOT NULL,
  `codcategoria` int(10) NOT NULL,
  `ContratoTemporal` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`CodTrabajador`,`codempresa`),
  KEY `sajvgfh_idx` (`codpuesto`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `payroll_pagarini`
--

DROP TABLE IF EXISTS `payroll_pagarini`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payroll_pagarini` (
  `fecha` date NOT NULL,
  `person_⁯id` int(11) NOT NULL,
  `saldotpv` double NOT NULL DEFAULT '0',
  `saldolab` double NOT NULL DEFAULT '0',
  `saldoprod` double NOT NULL DEFAULT '0',
  `saldobruto` double NOT NULL DEFAULT '0',
  `business_id` int(11) NOT NULL,
  `exportado` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`business_id`,`fecha`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `payroll_pais`
--

DROP TABLE IF EXISTS `payroll_pais`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payroll_pais` (
  `codpais` int(11) NOT NULL,
  `pais` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`codpais`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `payroll_tipobasess`
--

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

--
-- Table structure for table `payrroll_apEmpresarial`
--

DROP TABLE IF EXISTS `payrroll_apEmpresarial`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payrroll_apEmpresarial` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `codTrabajador` int(11) NOT NULL,
  `Fecha` date NOT NULL,
  `CosteEmpresaAT` decimal(8,2) NOT NULL,
  `costeEmpresaCC` decimal(8,2) NOT NULL,
  `costeEmpresaDesempleo` decimal(8,2) NOT NULL,
  `costeEmpresaFP` decimal(8,2) NOT NULL,
  `costeEmpresaFogasa` decimal(8,2) NOT NULL,
  `costeEmpresaExtra` decimal(8,2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1654 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `person_user`
--

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

--
-- Temporary table structure for view `person_user_idtrabajador`
--

DROP TABLE IF EXISTS `person_user_idtrabajador`;
/*!50001 DROP VIEW IF EXISTS `person_user_idtrabajador`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `person_user_idtrabajador` AS SELECT 
 1 AS `Id_Trabajador`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `plantpassport`
--

DROP TABLE IF EXISTS `plantpassport`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `plantpassport` (
  `producer_id` mediumint(3) unsigned NOT NULL,
  `plantpassport_authority_id` mediumint(3) unsigned NOT NULL,
  `number` varchar(25) CHARACTER SET utf8 DEFAULT NULL,
  `isRequested` tinyint(2) NOT NULL DEFAULT '0',
  PRIMARY KEY (`producer_id`,`plantpassport_authority_id`),
  KEY `plantpassport_authority_idx` (`plantpassport_authority_id`),
  KEY `producer_id_idx` (`producer_id`),
  CONSTRAINT `plantpassport_authority` FOREIGN KEY (`plantpassport_authority_id`) REFERENCES `plantpassport_authority` (`plantpassport_authority_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `producer` FOREIGN KEY (`producer_id`) REFERENCES `producer` (`producer_id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='tiene la asignacion de cada productor con la autoridad certificadora';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `plantpassport_authority`
--

DROP TABLE IF EXISTS `plantpassport_authority`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `plantpassport_authority` (
  `plantpassport_authority_id` mediumint(3) unsigned NOT NULL,
  `denomination` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Paises_Id` mediumint(8) unsigned DEFAULT NULL,
  PRIMARY KEY (`plantpassport_authority_id`),
  UNIQUE KEY `denomination_UNIQUE` (`denomination`),
  KEY `Pais_id_idx` (`Paises_Id`),
  CONSTRAINT `Pais_id` FOREIGN KEY (`Paises_Id`) REFERENCES `Paises` (`Id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='entidades certificadoras';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `preparation_exception`
--

DROP TABLE IF EXISTS `preparation_exception`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `preparation_exception` (
  `exception_day` date NOT NULL COMMENT 'preparation day',
  `warehouse_id` smallint(6) unsigned DEFAULT NULL,
  `percentage` tinyint(2) NOT NULL DEFAULT '0',
  UNIQUE KEY `exception_day_UNIQUE` (`exception_day`),
  UNIQUE KEY `warehouse_id_UNIQUE` (`warehouse_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `preparation_percentage`
--

DROP TABLE IF EXISTS `preparation_percentage`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `preparation_percentage` (
  `week_day` tinyint(1) unsigned NOT NULL COMMENT 'preparation day. Funcion de mysql Lunes = 0, Domingo = 6',
  `warehouse_id` smallint(6) unsigned DEFAULT NULL,
  `percentage` tinyint(2) NOT NULL DEFAULT '0',
  UNIQUE KEY `week_day_UNIQUE` (`week_day`),
  UNIQUE KEY `warehouse_id_UNIQUE` (`warehouse_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `price_fixed`
--

DROP TABLE IF EXISTS `price_fixed`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `price_fixed` (
  `item_id` int(10) NOT NULL,
  `rate_0` double NOT NULL,
  `rate_1` double NOT NULL,
  `rate_2` double NOT NULL,
  `rate_3` double NOT NULL,
  `date_start` date NOT NULL,
  `date_end` date NOT NULL,
  `bonus` double NOT NULL DEFAULT '0',
  `warehouse_id` smallint(5) unsigned NOT NULL DEFAULT '0',
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `price_fixed_id` int(11) NOT NULL AUTO_INCREMENT,
  `grouping` smallint(5) DEFAULT NULL,
  `Packing` int(11) DEFAULT NULL,
  `caja` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`item_id`,`date_start`,`date_end`,`warehouse_id`),
  UNIQUE KEY `price_fixed_id_UNIQUE` (`price_fixed_id`),
  KEY `item_id` (`item_id`),
  KEY `date_start` (`date_start`),
  KEY `date_end` (`date_end`),
  KEY `warehouse_id` (`warehouse_id`),
  CONSTRAINT `price_fixed_ibfk_1` FOREIGN KEY (`item_id`) REFERENCES `Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=62548 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              = '' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`price_fixed_bi` BEFORE INSERT ON `vn2008`.`price_fixed`
 FOR EACH ROW BEGIN
	DECLARE v_aux DATE;
		IF NEW.date_start > NEW.date_end THEN
			SET v_aux = NEW.date_start;
			SET NEW.date_start = NEW.date_end;
			SET NEW.date_end = v_aux;
		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              = '' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`price_fixed_bu` BEFORE UPDATE ON `vn2008`.`price_fixed`
 FOR EACH ROW BEGIN
	DECLARE v_aux DATE;
		IF NEW.date_start > NEW.date_end THEN
			SET v_aux = NEW.date_start;
			SET NEW.date_start = NEW.date_end;
			SET NEW.date_end = v_aux;
		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 `producer`
--

DROP TABLE IF EXISTS `producer`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `producer` (
  `producer_id` mediumint(3) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `visible` tinyint(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`producer_id`),
  UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=9646 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `profile_labour_payroll`
--

DROP TABLE IF EXISTS `profile_labour_payroll`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `profile_labour_payroll` (
  `profile_id` int(11) NOT NULL,
  `codpais` int(11) NOT NULL,
  `nivelformativo` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `NSSProvincia` tinyint(2) unsigned zerofill NOT NULL,
  `NssNumero` varchar(8) COLLATE utf8_unicode_ci NOT NULL,
  `NssDC` char(2) COLLATE utf8_unicode_ci NOT NULL,
  `sexo` enum('H','M') COLLATE utf8_unicode_ci NOT NULL,
  `estadocivil` enum('S','C') COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`profile_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `proveedores_clientes`
--

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

--
-- Table structure for table `province`
--

DROP TABLE IF EXISTS `province`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `province` (
  `province_id` smallint(6) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `Paises_Id` mediumint(8) unsigned NOT NULL,
  `warehouse_id` smallint(6) unsigned DEFAULT NULL COMMENT 'warehouse responsable de las rutas',
  `zone` tinyint(4) DEFAULT NULL,
  `nst_geo_id` int(11) DEFAULT NULL,
  `nst_name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `geoFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`province_id`),
  KEY `Paises_Id` (`Paises_Id`),
  KEY `warehouse_Id` (`warehouse_id`),
  KEY `provicne_zone_fk_idx` (`zone`),
  CONSTRAINT `province_ibfk_1` FOREIGN KEY (`Paises_Id`) REFERENCES `Paises` (`Id`) ON UPDATE CASCADE,
  CONSTRAINT `province_zone_fk` FOREIGN KEY (`zone`) REFERENCES `zones` (`zone_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `warehouse_Id` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=194 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 `vn2008`.`provinceBeforeInsert`
	BEFORE INSERT ON `province` FOR EACH ROW
BEGIN
	IF NEW.`name` = '' THEN
		CALL util.throw ('EMPTY_NAME');
	END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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 `vn2008`.`provinceBeforeUpdate`
	BEFORE UPDATE ON `province` FOR EACH ROW
BEGIN
	IF NEW.`name` = '' THEN
		CALL util.throw ('EMPTY_NAME');
	END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;

--
-- Table structure for table `rec_translator`
--

DROP TABLE IF EXISTS `rec_translator`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `rec_translator` (
  `Id_Article` int(11) NOT NULL,
  `denominacion` varchar(85) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`Id_Article`,`denominacion`),
  KEY `id_article_rec_idx` (`Id_Article`),
  CONSTRAINT `id_article_rec` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Equipara las denominaciones de las fincas de ecuador con nuestro Id_Article';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `recibida`
--

DROP TABLE IF EXISTS `recibida`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `recibida` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `num_recibida` mediumint(11) unsigned DEFAULT NULL COMMENT 'insertado por Trigger',
  `serie` char(1) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'R',
  `proveedor_id` int(11) NOT NULL,
  `fecha` date NOT NULL COMMENT 'Fecha de emision de la factura',
  `sref` varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0',
  `contabilizada` tinyint(1) NOT NULL DEFAULT '0',
  `moneda_id` tinyint(3) unsigned NOT NULL DEFAULT '1',
  `MYSQL_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442',
  `gestdoc_id` int(11) DEFAULT NULL,
  `dateBooking` date DEFAULT NULL COMMENT 'Fecha de contabilizacion',
  `dateOperation` date DEFAULT NULL COMMENT 'Fecha de entrega de la mercancia o el suministro',
  `cplusInvoiceType472Fk` int(10) unsigned DEFAULT '1',
  `cplusRectificationTypeFk` int(10) unsigned DEFAULT '1',
  `cplusSubjectOpFk` int(10) unsigned DEFAULT '1',
  `cplusTaxBreakFk` int(10) unsigned DEFAULT '1',
  `cplusTrascendency472Fk` int(10) unsigned DEFAULT '1',
  `bookEntried` date DEFAULT NULL,
  `isVatDeductible` tinyint(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  KEY `proveedor_id` (`proveedor_id`),
  KEY `empresa_id` (`empresa_id`),
  KEY `serie` (`serie`),
  KEY `num_recibida_2` (`num_recibida`),
  KEY `gestdoc_id` (`gestdoc_id`),
  KEY `fecha` (`fecha`),
  KEY `recibida_ibfk_3_idx` (`cplusSubjectOpFk`),
  KEY `recibida_ibfk_4_idx` (`cplusTaxBreakFk`),
  KEY `recibida_ibfk_5_idx` (`cplusInvoiceType472Fk`),
  KEY `recibida_ibfk_6` (`cplusRectificationTypeFk`),
  KEY `recibida_ibfk_7` (`cplusTrascendency472Fk`),
  CONSTRAINT `recibida_ibfk_1` FOREIGN KEY (`proveedor_id`) REFERENCES `Proveedores` (`Id_Proveedor`) ON UPDATE CASCADE,
  CONSTRAINT `recibida_ibfk_2` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `recibida_ibfk_3` FOREIGN KEY (`cplusSubjectOpFk`) REFERENCES `vn`.`cplusSubjectOp` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `recibida_ibfk_4` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `vn`.`cplusTaxBreak` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `recibida_ibfk_5` FOREIGN KEY (`cplusInvoiceType472Fk`) REFERENCES `vn`.`cplusInvoiceType472` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `recibida_ibfk_6` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `vn`.`cplusRectificationType` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `recibida_ibfk_7` FOREIGN KEY (`cplusTrascendency472Fk`) REFERENCES `vn`.`cplusTrascendency472` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=81370 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 `vn2008`.`recibida_bi`
BEFORE INSERT ON `vn2008`.`recibida`
FOR EACH ROW
BEGIN
		DECLARE v_serie CHAR(1) DEFAULT 'R';
		DECLARE v_num_recibida INT;
		DECLARE pais_emisor, pais_receptor INT;
        DECLARE vActive TINYINT;
       

		SELECT pais_id, active into pais_emisor, vActive FROM Proveedores WHERE Id_Proveedor = NEW.proveedor_id;
		SELECT pais_id into pais_receptor FROM Proveedores WHERE Id_Proveedor = NEW.empresa_id;

		IF vActive = 0 THEN
        	CALL util.throw('INACTIVE_PROVIDER');
		END IF;
        
		SELECT CASE WHEN (SELECT Cuenta FROM Proveedores where Id_Proveedor = NEW.proveedor_id) LIKE '___3______' THEN 'C'
					WHEN (SELECT pais_emisor=pais_receptor from Paises p1 join Paises p2 ON p2.Id = pais_receptor AND p1.Id = pais_emisor 
								where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'R'
					WHEN (SELECT pais_emisor <> pais_receptor from Paises p1 join Paises p2 ON p2.Id = pais_receptor AND p1.Id = pais_emisor 
								where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'E' 
					WHEN (SELECT pais_emisor<>pais_receptor from Paises p1 join Paises p2 ON p2.Id = pais_receptor AND p1.Id = pais_emisor
								where NOT p1.CEE < 2 AND not p1.Id = 1) = 1 THEN 'W'
					
				END INTO v_serie;
		
		SET NEW.serie =  IFNULL(v_serie,'R');
	
		IF v_serie LIKE 'W' THEN
		
			SELECT IFNULL(MAX(num_recibida) + 1,1) INTO v_num_recibida FROM recibida 
			WHERE serie LIKE NEW.serie 
			AND YEAR(fecha) = YEAR(NEW.fecha)
			AND empresa_id = NEW.empresa_id;
		
			SET NEW.num_recibida = v_num_recibida;
            
		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 `recibida_bu` BEFORE UPDATE ON `recibida` FOR EACH ROW
-- Edit trigger body code below this line. Do not edit lines above this one
BEGIN

    DECLARE cta_proveed VARCHAR(10);
    DECLARE cta_proveeda VARCHAR(10);
    DECLARE v_num_recibida INT;
    DECLARE dblRefRate,dblRefMin,dblRef DOUBLE;
    DECLARE vActive TINYINT;

	SELECT active INTO vActive FROM Proveedores WHERE Id_Proveedor = NEW.proveedor_id;
    
	IF vActive = 0 THEN
		CALL util.throw('INACTIVE_PROVIDER');
	END IF;
	
    IF NEW.empresa_id <> OLD.empresa_id THEN
       SET NEW.num_recibida = NULL;
        SET NEW.contabilizada = FALSE ;
    END IF;
    
  

/* PAK 27/11/17  ESto tiene pinta de no hacer falta....

IF NEW.contabilizada = 1 AND OLD.contabilizada = 0 AND NEW.fecha < '2017-07-01' THEN

    SELECT rate INTO dblRefRate FROM reference_rate WHERE date = (SELECT MAX(date) FROM reference_rate 
            WHERE date <= (SELECT  t.shipment FROM
    recibida_entrada re 
    INNER JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada
    LEFT JOIN travel t ON t.id = e.travel_id 
    WHERE re.awb_recibida = NEW.id GROUP BY re.awb_recibida));
        
    SELECT rate INTO dblRefMin FROM reference_min  WHERE date=(SELECT MAX(date) FROM reference_min 
            WHERE date<=(SELECT  t.shipment FROM
    recibida_entrada re 
    INNER JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada
    LEFT JOIN travel t ON t.id = e.travel_id 
    WHERE re.awb_recibida = NEW.id GROUP BY re.awb_recibida));

    -- IF dblRefMin < dblRefRate THEN
    --    SET dblRef = dblRefRate;
    -- ELSE
    --     SET dblRef =dblRefMin;
    -- END IF;
    SELECT IFNULL(MAX(r.num_recibida) + 1,1) INTO v_num_recibida FROM recibida r
            WHERE r.serie LIKE NEW.serie 
            AND YEAR(r.fecha) = YEAR(NEW.fecha)
            AND r.empresa_id = NEW.empresa_id GROUP BY r.empresa_id;
            
    SET NEW.num_recibida = IFNULL(v_num_recibida,1);	
    SELECT REPLACE(cuenta,' ','') INTO cta_proveed FROM Proveedores WHERE Id_Proveedor=NEW.proveedor_id;

                 INSERT INTO XDiario(ASIEN,FECHA,SUBCTA,CONTRA,CONCEPTO,EURODEBE, EUROHABER,BASEEURO, SERIE,FACTURA,IVA,DOCUMENTO,
								L340,LRECT349,TIPOOPE,AUXILIAR,empresa_id,LDIFADUAN)
SELECT a,NEW.fecha,subcta,contra,concepto,eurodebe,eurohaber,baseeuro,serie,NEW.sref,iva,
        (SELECT CONCAT(serie,'/', LPAD(v_num_recibida,5,'0'))),l340,LRECT349,TIPOOPE,AUXILIAR,NEW.empresa_id,LDIFADUAN
			FROM

			(SELECT MAX(ASIEN) + 1 as a FROM XDiario) t

			INNER JOIN

			(

 SELECT *,NEW.serie,0 LDIFADUAN FROM 

 (SELECT CONCAT('s/fra',RIGHT(sref,8),':',LEFT(Proveedor, 10)) concepto FROM Proveedores

 INNER JOIN recibida ON Id_Proveedor = proveedor_id WHERE id = NEW.id) t4

 INNER JOIN(
        -- Linea del proveedor/acreedor
				SELECT subcta,'' contra,eurodebe,ROUND(SUM(eurohaber) + 0.0001,2)	eurohaber,baseeuro,0 iva, l340,LRECT349,TIPOOPE,'' AUXILIAR

						FROM (

							SELECT cta_proveed  subcta,

							NULL eurodebe, ROUND((1+(iva/100)*(r.serie = 'R'))*SUM(bi),2) eurohaber, NULL baseeuro,ri.recibida_id, 0 l340,0 LRECT349,' ' TIPOOPE

							FROM recibida r

							INNER JOIN recibida_iva ri ON ri.recibida_id = r.id	INNER JOIN iva_codigo ic ON ri.iva_id = ic.id 

							INNER JOIN Proveedores p ON p.Id_Proveedor=r.proveedor_id
							INNER JOIN Proveedores p2 ON p2.Id_Proveedor =  r.empresa_id

								WHERE r.id = NEW.id GROUP BY iva) t

							GROUP BY recibida_id

			UNION ALL
        -- Linea de iva
				SELECT ic.codigo,cta_proveed  contra,

					ROUND(iva/100*SUM(ri.bi) + 0.0001,2) eurodebe, NULL eurohaber,

					ROUND(SUM(ri.bi),2) baseeuro,iva, 1 l340,(NOT ((p.pais_id <> p2.pais_id) AND pa.CEE < 2)) LRECT349,TIPOOPE,
					IF(pa.CEE < 2 AND ri2.gastos_id IS NULL,'','*')  AUXILIAR
							FROM recibida r

						INNER JOIN recibida_iva ri ON ri.recibida_id = r.id 

						LEFT JOIN recibida_iva ri2 ON ri2.recibida_id = r.id AND ri2.gastos_id LIKE '4751______'
						
						INNER JOIN iva_codigo ic ON ri.iva_id = ic.id

						INNER JOIN iva_tipo it ON it.id = ic.iva_tipo_id

						INNER JOIN Gastos g ON ri.gastos_id = g.Id_Gasto AND g.iva_tipo_id = ic.iva_tipo_id
						
						INNER JOIN Proveedores p ON p.Id_Proveedor=r.proveedor_id
						
						INNER JOIN Paises pa ON p.pais_id = pa.Id
						
						INNER JOIN Proveedores p2 ON p2.Id_Proveedor =  r.empresa_id
						
						INNER JOIN Paises pa2 ON p2.pais_id = pa2.Id
							WHERE r.id = NEW.id AND ic.tipo <> '-' AND link GROUP BY iva 
								-- JGF 2016-05-05    g.conbase
			UNION ALL
        -- Linea iva inversor sujeto pasivo
				SELECT ic2.codigo,cta_proveed  contra,

					 NULL eurodebe, ROUND(ic2.iva/100*SUM(bi) + 0.0001,2) eurohaber,

					ROUND(SUM(bi),2) baseeuro,ic2.iva, 1  l340,0 LRECT349,TIPOOPE,'*' AUXILIAR

						FROM recibida r

						INNER JOIN recibida_iva ri ON ri.recibida_id = r.id 

						INNER JOIN iva_codigo ic ON ri.iva_id = ic.id

						INNER JOIN iva_codigo ic2 ON ic2.link = ic.link AND ic.id <> ic2.id						

						INNER JOIN iva_tipo it ON ic.iva_tipo_id = it.id

							WHERE r.id = NEW.id AND ic2.link GROUP BY ic2.iva

			UNION ALL
        -- Linea de Gastos
				SELECT if(gastos_id  LIKE '4751______',LPAD(RIGHT(cta_proveed ,5),10,gastos_id),gastos_id),cta_proveed ,

					if(gastos_id LIKE '4751______',NULL,ABS(ROUND(SUM(bi),2))) ,

					if(gastos_id LIKE '4751______',ABS(ROUND(SUM(bi),2)),NULL) ,

					NULL ,0, 0 l340,0 LRECT349,' ' TIPOOPE,'' AUXILIAR

				FROM recibida r

					INNER JOIN recibida_iva ri ON ri.recibida_id = r.id

					INNER JOIN Proveedores p ON p.Id_Proveedor=r.proveedor_id            

				WHERE r.id = NEW.id AND gastos_id <> 5660000002 GROUP BY gastos_id
					
        UNION ALL
				-- Iva Importacion pendiente
                 -- JGF 17/02/15 cambia la forma de declarar este tipo de importaciones, sólo afecta a transitarios
				SELECT '4700000999',NULL,NULL ,ROUND(SUM(importe * (iva/100)),2),NULL ,0, 0 l340,0 LRECT349,' ' TIPOOPE,'' AUXILIAR

					FROM recibida r
						JOIN recibida_intrastat ri ON r.id = ri.recibida_id
                        JOIN Intrastat i ON i.Codintrastat = ri.Codintrastat
						JOIN iva_codigo ic ON ic.id = i.iva_codigo_id
					WHERE ri.recibida_id = NEW.id GROUP BY ri.recibida_id

 ) t2

 UNION ALL


     -- Extracomunitarias gasto contra proveedor/acreedor   
     SELECT CONCAT('COMPRA s/fra ',sref,':',LEFT(p.Proveedor, 10)) concepto ,gastos_id,cuenta,

        ROUND(SUM(bi)/IF(r.serie='W' AND ri.divisa IS NULL,dblRefRate,1)* (re.percentage / 100),2),NULL ,IF( @a:=@a+1 ,NULL,NULL) ,0, 0 l340,0 LRECT349,' ' TIPOOPE,'' AUXILIAR,r.serie,0 LDIFADUAN

        FROM recibida_entrada re
		
            INNER JOIN recibida_iva ri ON re.recibida_id = ri.recibida_id
			
            INNER JOIN recibida r ON r.id = ri.recibida_id

            INNER JOIN Proveedores p ON p.Id_Proveedor = r.proveedor_id

            INNER JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada

            LEFT JOIN travel t ON t.id = e.travel_id
			
			INNER JOIN (SELECT @a:=0,@cont:=1,@total:=0,@base:=2) t1

                WHERE re.awb_recibida = NEW.id AND re.percentage GROUP BY r.id

UNION ALL

     -- Extracomunitarias proveedor contra gasto
     SELECT CONCAT('COMPRA s/fra ',sref,':',LEFT(p.Proveedor, 10)) concepto ,p.cuenta subcta,gastos_id,

        NULL eurodebe, ROUND((1+(iva/100)*(r.serie = 'R'))*SUM(bi)/IF(r.serie='W' AND ri.divisa IS NULL,dblRefRate,1)* (re.percentage / 100),2) eurohaber,

        NULL baseeuro,0 iva, 0 l340,0 LRECT349,' ' TIPOOPE,'' AUXILIAR,r.serie,0 LDIFADUAN
        -- antes sols iva
            FROM recibida_entrada re 

                INNER JOIN recibida_iva ri ON re.recibida_id = ri.recibida_id

                INNER JOIN recibida r ON r.id = ri.recibida_id

                INNER JOIN iva_codigo ic ON ri.iva_id = ic.id 

                INNER JOIN Proveedores p ON Id_Proveedor = r.proveedor_id
				
				INNER JOIN Proveedores p2 ON p2.Id_Proveedor =  r.empresa_id

                    WHERE re.awb_recibida = NEW.id AND re.percentage GROUP BY r.id

UNION ALL

        -- Linea de iva adquisicion
				SELECT CONCAT('ADQUI. INTRA FRA ',sref),ic.codigo,p.cuenta contra,

					ROUND(iva/100*SUM(ri.importe) + 0.0001,2) eurodebe, NULL eurohaber,

					ROUND(SUM(ri.importe),2) baseeuro,iva, 1 l340,1 LRECT349,TIPOOPE,'' AUXILIAR,r.serie,0 LDIFADUAN

						FROM awb_recibida ar
						
						JOIN awb a ON ar.awb_id = a.id

						JOIN iva_codigo ic ON a.iva_id = ic.id

						JOIN iva_tipo it ON ic.iva_tipo_id = it.id

						JOIN Proveedores p ON a.transitario_id = p.Id_Proveedor

						JOIN recibida_intrastat ri ON ri.recibida_id = ar.recibida_id

						JOIN recibida r ON r.id = ri.recibida_id
						
						JOIN Proveedores p2 ON p2.Id_Proveedor =  r.empresa_id

							WHERE ar.recibida_id = NEW.id AND (p.pais_id <> p2.pais_id)
							GROUP BY iva

			UNION ALL
    
        -- Linea de iva adquisicion
				SELECT CONCAT('ADQUI. INTRA FRA ',sref),ic2.codigo,p.cuenta contra,

					 NULL eurodebe, ROUND(ic2.iva/100*SUM(ri.importe) + 0.0001,2) eurohaber,

					ROUND(SUM(ri.importe),2) baseeuro,ic2.iva, 1 l340,0 LRECT349, TIPOOPE,'' AUXILIAR,r.serie,0 LDIFADUAN

						FROM awb_recibida ar
						
						JOIN awb a ON ar.awb_id = a.id 

						JOIN iva_codigo ic ON a.iva_id = ic.id

						JOIN iva_codigo ic2 ON ic2.link = ic.link AND ic.id <> ic2.id						

						JOIN iva_tipo it ON ic.iva_tipo_id = it.id

						JOIN Proveedores p ON a.transitario_id = p.Id_Proveedor

						JOIN recibida_intrastat ri ON ri.recibida_id = ar.recibida_id

						JOIN recibida r ON r.id = ar.recibida_id
						
						JOIN Proveedores p1 ON p1.Id_Proveedor = r.proveedor_id
												
						JOIN Proveedores p2 ON p2.Id_Proveedor =  r.empresa_id

							WHERE ar.recibida_id = NEW.id AND (p.pais_id <> p2.pais_id) GROUP BY ic2.iva
                            
        UNION ALL
            -- Linea iva importacion
            SELECT concepto,subcta,Cuenta,
            IF (NOT ((ppais_id <> p2pais_id) AND CEE < 2),
               
                    eurodebe
            ,NULL)eurodebe,eurohaber,baseeuro, iva,
            IF(@total:=@total+eurodebe ,0,0) l340, 0 LRECT349,
            IF(@cont:=@cont+1,'','') TIPOOPE,'*' AUXILIAR,serie,1 LDIFADUAN FROM (
            
            SELECT CONCAT('COMPRA FRA ',p.Proveedor) concepto,ic2.codigo subcta,p.Cuenta,ic2.iva,
            ROUND(sum(costefijo * Cantidad / sub1.costetotal * sub2.importe)*(ic2.iva/100),2) eurodebe,NULL eurohaber, -- JGF 17/02/15 canvie 0.21 per ic.iva
            ROUND(sum(costefijo * Cantidad / sub1.costetotal * sub2.importe),2) baseeuro,r.serie,pa.CEE,pa.Id_Paisreal ppais_id,
            p2.pais_id p2pais_id,SUM(sub3.SumIntrastat *(ic2.iva/100)) SumIntrastat, p.Id_Proveedor,Codintrastat

            FROM awb_recibida ar
						
            JOIN recibida_entrada re ON ar.recibida_id = re.awb_recibida
			
			JOIN Compres c ON c.Id_Entrada = re.Id_Entrada

            INNER JOIN Articles a ON a.Id_Article = c.Id_Article

            INNER JOIN (

                SELECT a.Codintrastat, sum(c.costefijo * c.Cantidad) as costetotal

                FROM Compres c 

                JOIN Articles a ON a.Id_Article = c.Id_Article

                JOIN recibida_entrada re ON re.Id_Entrada = c.Id_Entrada
				
				JOIN awb_recibida ar ON ar.recibida_id = re.awb_recibida
						
				JOIN awb aw ON ar.awb_id = aw.id

                WHERE ar.recibida_id = NEW.id AND re.percentage

                GROUP BY a.Codintrastat

                ) sub1 USING(Codintrastat)

            INNER JOIN (

                SELECT Codintrastat,ri.importe, i.iva_codigo_id

                FROM recibida_intrastat ri
                JOIN Intrastat i USING(Codintrastat)

                WHERE ri.recibida_id = NEW.id

            ) sub2 USING(Codintrastat)
            
			INNER JOIN (

                SELECT SUM(ri.importe)  SumIntrastat

                FROM recibida_intrastat ri

                WHERE ri.recibida_id = NEW.id

            ) sub3 

            JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada

            JOIN Proveedores p ON p.Id_Proveedor = e.Id_Proveedor
			
			JOIN Paises pa ON p.pais_id = pa.Id
							                        
            JOIN recibida r ON r.id = re.recibida_id
			
			JOIN Proveedores p2 ON p2.Id_Proveedor =  r.empresa_id
            
            JOIN iva_codigo ic2 ON ic2.id = sub2.iva_codigo_id -- JGF 15/04/15 nou canvi llei (Ali)

            WHERE re.awb_recibida = NEW.id AND re.percentage 
             -- canvie el cta_proveed like '___1______' per cero cuidao en les van de put

            GROUP BY p.Id_Proveedor, sub2.iva_codigo_id
            
) t3 GROUP BY Id_Proveedor, iva)t4;

-- linea que estava a l'ultim WHERE  
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 `vn2008`.`recibida_au` AFTER UPDATE ON `recibida` FOR EACH ROW
BEGIN

	IF 	NEW.fecha != OLD.fecha 
		OR
        NEW.moneda_id != OLD.moneda_id 
		THEN
    
			CALL recibidaIvaDivisaUpdate(NEW.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 */ ;

--
-- Table structure for table `recibida_agricola`
--

DROP TABLE IF EXISTS `recibida_agricola`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `recibida_agricola` (
  `recibida_id` mediumint(8) unsigned NOT NULL,
  `num` smallint(5) unsigned NOT NULL,
  PRIMARY KEY (`recibida_id`),
  CONSTRAINT `recibida_agricola_ibfk_1` FOREIGN KEY (`recibida_id`) REFERENCES `recibida` (`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 `recibida_entrada`
--

DROP TABLE IF EXISTS `recibida_entrada`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `recibida_entrada` (
  `recibida_entrada_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `recibida_id` mediumint(8) unsigned NOT NULL,
  `Id_Entrada` int(11) NOT NULL,
  `percentage` decimal(10,2) unsigned NOT NULL DEFAULT '0.00',
  `awb_recibida` mediumint(8) unsigned NOT NULL,
  `Contabilizado` tinyint(3) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`recibida_entrada_id`),
  KEY `awb_recibida` (`awb_recibida`),
  KEY `Id_Entrada` (`Id_Entrada`),
  KEY `recibida_id` (`recibida_id`),
  CONSTRAINT `recibida_entrada_ibfk_2` FOREIGN KEY (`Id_Entrada`) REFERENCES `Entradas` (`Id_Entrada`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=10708 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              = '' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `recibida_entrada_bi` BEFORE INSERT ON `recibida_entrada` FOR EACH ROW
BEGIN
	DECLARE intRecibida INT;
	IF NEW.recibida_id = 0 THEN
		SELECT recibida_id INTO intRecibida FROM recibida_entrada WHERE Id_Entrada = NEW.Id_Entrada;
		SET NEW.recibida_id = intRecibida;
	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              = '' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `recibida_entrada_bu` BEFORE UPDATE ON `recibida_entrada` FOR EACH ROW
BEGIN
	DECLARE intRecibida INT;
	IF NEW.recibida_id = 0 THEN
		SELECT recibida_id INTO intRecibida FROM recibida_entrada WHERE Id_Entrada = NEW.Id_Entrada;
		SET NEW.recibida_id = intRecibida;
	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 `recibida_intrastat`
--

DROP TABLE IF EXISTS `recibida_intrastat`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `recibida_intrastat` (
  `recibida_id` mediumint(8) unsigned NOT NULL,
  `Codintrastat` int(8) unsigned zerofill NOT NULL,
  `importe` decimal(10,2) NOT NULL,
  PRIMARY KEY (`recibida_id`,`Codintrastat`),
  KEY `Codintrastat` (`Codintrastat`),
  KEY `recibida_id` (`recibida_id`),
  CONSTRAINT `recibida_intrastat_ibfk_1` FOREIGN KEY (`recibida_id`) REFERENCES `recibida` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `recibida_intrastat_ibfk_2` FOREIGN KEY (`Codintrastat`) REFERENCES `Intrastat` (`Codintrastat`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `recibida_iva`
--

DROP TABLE IF EXISTS `recibida_iva`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `recibida_iva` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `recibida_id` mediumint(8) unsigned NOT NULL,
  `iva_id` tinyint(2) unsigned NOT NULL,
  `bi` decimal(10,2) NOT NULL,
  `gastos_id` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `divisa` decimal(10,2) DEFAULT NULL,
  `MYSQL_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `gastos_id` (`gastos_id`),
  KEY `recibida_id` (`recibida_id`),
  KEY `recibida_iva_ibfk_2` (`iva_id`),
  CONSTRAINT `recibida_iva_ibfk_2` FOREIGN KEY (`iva_id`) REFERENCES `iva_codigo` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `recibida_iva_ibfk_5` FOREIGN KEY (`recibida_id`) REFERENCES `recibida` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `recibida_iva_ibfk_6` FOREIGN KEY (`gastos_id`) REFERENCES `Gastos` (`Id_Gasto`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=132318 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `recibida_vencimiento`
--

DROP TABLE IF EXISTS `recibida_vencimiento`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `recibida_vencimiento` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `recibida_id` mediumint(8) unsigned NOT NULL,
  `fecha` date NOT NULL,
  `banco_id` int(11) NOT NULL DEFAULT '3117',
  `cantidad` decimal(10,2) NOT NULL DEFAULT '0.00',
  `divisa` decimal(10,2) DEFAULT NULL,
  `stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `recibida_id` (`recibida_id`),
  KEY `banco_id` (`banco_id`),
  CONSTRAINT `recibida_vencimiento_ibfk_6` FOREIGN KEY (`banco_id`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE,
  CONSTRAINT `recibida_vencimiento_ibfk_7` FOREIGN KEY (`recibida_id`) REFERENCES `recibida` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=130058 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 `vn2008`.`recibida_vencimiento_bi`
BEFORE INSERT ON `vn2008`.`recibida_vencimiento`
FOR EACH ROW
BEGIN/*
    IF NEW.cantidad = 0 THEN
        SET NEW.id = 5;
    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 `recovery`
--

DROP TABLE IF EXISTS `recovery`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `recovery` (
  `recovery_id` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Cliente` int(11) NOT NULL DEFAULT '0',
  `dstart` date NOT NULL COMMENT 'Fecha a partir de la que comienza el recobro',
  `dend` date DEFAULT NULL COMMENT 'Fecha en la que acaba',
  `amount` double NOT NULL,
  `period` tinyint(3) unsigned NOT NULL DEFAULT '7' COMMENT 'numero de dias que indica cada cuanto hare el recobro',
  PRIMARY KEY (`recovery_id`),
  KEY `cliente_idx` (`Id_Cliente`),
  CONSTRAINT `cliente333` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE,
  CONSTRAINT `cliente_cliente` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=299 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='En esta tabla apuntaremos los acuerdos de recobro semanal a ';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `recovery_asset`
--

DROP TABLE IF EXISTS `recovery_asset`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `recovery_asset` (
  `recovery_asset_id` int(11) NOT NULL AUTO_INCREMENT,
  `dreceipt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `amount` double NOT NULL,
  `Id_Cliente` int(11) NOT NULL,
  PRIMARY KEY (`recovery_asset_id`),
  KEY `Cliente_Recovery_detalle_idx` (`Id_Cliente`),
  CONSTRAINT `Cliente_Recovery_detalle` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=723 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='En esta tabla se registra el detalle de los recobros definid';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `reference_min`
--

DROP TABLE IF EXISTS `reference_min`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `reference_min` (
  `date` date NOT NULL,
  `rate` decimal(10,4) NOT NULL,
  `moneda_id` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`date`,`moneda_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `reference_rate`
--

DROP TABLE IF EXISTS `reference_rate`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `reference_rate` (
  `moneda_id` tinyint(3) unsigned NOT NULL,
  `date` date NOT NULL,
  `rate` float unsigned NOT NULL,
  PRIMARY KEY (`moneda_id`,`date`),
  KEY `date` (`date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `reinos`
--

DROP TABLE IF EXISTS `reinos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `reinos` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `reino` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `orden` int(10) unsigned DEFAULT NULL,
  `display` tinyint(4) NOT NULL DEFAULT '1',
  `color` char(6) COLLATE utf8_unicode_ci DEFAULT NULL,
  `efimero` int(11) NOT NULL DEFAULT '0' COMMENT 'Sirve para filtrar aquellos reinos que tienen precios estables',
  `mercancia` tinyint(1) NOT NULL DEFAULT '1',
  `icon` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `reino_UNIQUE` (`reino`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `reparacion`
--

DROP TABLE IF EXISTS `reparacion`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `reparacion` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_user` int(2) DEFAULT NULL,
  `config_host` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `problema` text COLLATE utf8_unicode_ci NOT NULL,
  `solucion` text COLLATE utf8_unicode_ci NOT NULL,
  `estado` enum('No atendida','Vista','En Proceso','Solucionada') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'No atendida',
  `fecha` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `id_reparador` int(2) DEFAULT NULL,
  `ref` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `articulo` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,
  `marca` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `config_host` (`config_host`),
  KEY `id_user` (`id_user`),
  KEY `id_reparador` (`id_reparador`),
  CONSTRAINT `reparacion_ibfk_1` FOREIGN KEY (`id_user`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `reparacion_ibfk_2` FOREIGN KEY (`config_host`) REFERENCES `config_host` (`config_host_id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `reparacion_ibfk_4` FOREIGN KEY (`id_reparador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `rounding`
--

DROP TABLE IF EXISTS `rounding`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `rounding` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `amount` double NOT NULL DEFAULT '0',
  `price` double DEFAULT '0',
  `discount` double NOT NULL DEFAULT '0',
  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 `route`
--

DROP TABLE IF EXISTS `route`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `route` (
  `agency_id` smallint(5) unsigned NOT NULL,
  `week_day` tinyint(3) unsigned NOT NULL COMMENT 'weekday de access el domingo = 1, sabado = 7. Intentar cambiar al de Mysql Lunes = 0',
  PRIMARY KEY (`agency_id`,`week_day`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `ruta_location`
--

DROP TABLE IF EXISTS `ruta_location`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ruta_location` (
  `Id_Ruta` int(10) unsigned NOT NULL,
  `longitude` decimal(11,7) NOT NULL,
  `latitude` decimal(11,7) NOT NULL,
  `time_location` datetime NOT NULL,
  PRIMARY KEY (`Id_Ruta`),
  CONSTRAINT `Id_Ruta_Location` FOREIGN KEY (`Id_Ruta`) REFERENCES `Rutas` (`Id_Ruta`) 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 `salarioDits`
--

DROP TABLE IF EXISTS `salarioDits`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `salarioDits` (
  `idSalario_dits` int(11) NOT NULL AUTO_INCREMENT,
  `idaccion_dits` int(11) NOT NULL,
  `ODBC_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `Id_Ticket` int(11) NOT NULL,
  `Id_Trabajador` int(11) NOT NULL,
  `value_old` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value_new` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`idSalario_dits`)
) ENGINE=InnoDB AUTO_INCREMENT=96 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `scan`
--

DROP TABLE IF EXISTS `scan`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `scan` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `lft` int(11) NOT NULL,
  `rgt` int(11) NOT NULL,
  `name` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=93136 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Se borra automaticamente 8 dias en el pasado desde vn2008.clean';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `scanTree`
--

DROP TABLE IF EXISTS `scanTree`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `scanTree` (
  `id` int(11) NOT NULL DEFAULT '0',
  `name` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
  `lft` int(11) NOT NULL,
  `rgt` int(11) NOT NULL,
  `depth` bigint(22) NOT NULL DEFAULT '0',
  `sons` decimal(10,0) DEFAULT NULL,
  `lastScanned` datetime DEFAULT NULL,
  `routeCount` int(11) DEFAULT NULL,
  `minRoute` int(11) DEFAULT NULL,
  `maxRoute` int(11) DEFAULT NULL,
  `scanned` 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 `scan_line`
--

DROP TABLE IF EXISTS `scan_line`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `scan_line` (
  `scan_line_id` int(11) NOT NULL AUTO_INCREMENT,
  `scan_id` int(11) NOT NULL,
  `code` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`scan_line_id`),
  KEY `id_scan_id_idx` (`scan_id`),
  CONSTRAINT `id_scan_id` FOREIGN KEY (`scan_id`) REFERENCES `scan` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1163000 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `sharingcart`
--

DROP TABLE IF EXISTS `sharingcart`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sharingcart` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Trabajador` int(11) NOT NULL,
  `datSTART` date NOT NULL,
  `datEND` date NOT NULL,
  `Id_Suplente` int(11) NOT NULL,
  `odbc_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `Worker` (`Id_Trabajador`),
  KEY `Suplent` (`Id_Suplente`),
  CONSTRAINT `Suplent_key` FOREIGN KEY (`Id_Suplente`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE,
  CONSTRAINT `Trabajador_key` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2052 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 `sharingcart_bi` BEFORE INSERT ON `sharingcart` FOR EACH ROW

BEGIN

 SET NEW.datSTART = GREATEST(CURDATE(),NEW.datSTART);
 SET NEW.datEND = GREATEST(CURDATE(),NEW.datEND);
        
	IF NEW.Id_Trabajador =  NEW.Id_Suplente THEN
		SET NEW.Id_Trabajador = 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 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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 `sharingcart_bu` BEFORE UPDATE ON `sharingcart` FOR EACH ROW

BEGIN

 SET NEW.datSTART = GREATEST(CURDATE(),NEW.datSTART);
 SET NEW.datEND = GREATEST(CURDATE(),NEW.datEND);
 
	IF NEW.Id_Trabajador =  NEW.Id_Suplente THEN
		SET NEW.Id_Trabajador = 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 `sharingclient`
--

DROP TABLE IF EXISTS `sharingclient`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sharingclient` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Trabajador` int(11) NOT NULL,
  `datSTART` date NOT NULL,
  `datEND` date NOT NULL,
  `Id_Cliente` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `Worker` (`Id_Trabajador`),
  KEY `Client` (`Id_Cliente`),
  CONSTRAINT `Clients_key` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE,
  CONSTRAINT `Trabajadores_key` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=52 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 `vn2008`.`sharingclient_BEFORE_INSERT` BEFORE INSERT ON `sharingclient` FOR EACH ROW
BEGIN

SET NEW.datEND = GREATEST(CURDATE(),NEW.datEND);
SET NEW.datSTART = GREATEST(CURDATE(),NEW.datSTART);

END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `vn2008`.`sharingclient_BEFORE_UPDATE` BEFORE UPDATE ON `sharingclient` FOR EACH ROW
BEGIN

SET NEW.datEND = GREATEST(CURDATE(),NEW.datEND);
SET NEW.datSTART = GREATEST(CURDATE(),NEW.datSTART);

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

--
-- Temporary table structure for view `sms`
--

DROP TABLE IF EXISTS `sms`;
/*!50001 DROP VIEW IF EXISTS `sms`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `sms` AS SELECT 
 1 AS `id`,
 1 AS `Id_trabajador`,
 1 AS `Id_Cliente`,
 1 AS `from`,
 1 AS `to`,
 1 AS `text`,
 1 AS `sent`,
 1 AS `response`,
 1 AS `DATE_ODBC`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `state`
--

DROP TABLE IF EXISTS `state`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `state` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `order` tinyint(3) unsigned DEFAULT NULL,
  `alert_level` int(11) NOT NULL DEFAULT '0',
  `code` varchar(45) CHARACTER SET utf8 NOT NULL,
  `sectorProdPriority` tinyint(3) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `code_UNIQUE` (`code`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `tag`
--

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

--
-- Temporary table structure for view `tarifa_componentes`
--

DROP TABLE IF EXISTS `tarifa_componentes`;
/*!50001 DROP VIEW IF EXISTS `tarifa_componentes`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `tarifa_componentes` AS SELECT 
 1 AS `Id_Componente`,
 1 AS `Componente`,
 1 AS `tarifa_componentes_series_id`,
 1 AS `tarifa_class`,
 1 AS `tax`,
 1 AS `is_renewable`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `tarifa_componentes_series`
--

DROP TABLE IF EXISTS `tarifa_componentes_series`;
/*!50001 DROP VIEW IF EXISTS `tarifa_componentes_series`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `tarifa_componentes_series` AS SELECT 
 1 AS `tarifa_componentes_series_id`,
 1 AS `Serie`,
 1 AS `base`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `tarifas`
--

DROP TABLE IF EXISTS `tarifas`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tarifas` (
  `tarifa_id` int(11) NOT NULL AUTO_INCREMENT,
  `fecha` date NOT NULL,
  `warehouse_id` smallint(6) unsigned NOT NULL,
  `t0` double NOT NULL,
  `t1` double NOT NULL,
  `t2` double NOT NULL,
  `t3` double NOT NULL,
  PRIMARY KEY (`tarifa_id`),
  KEY `tarifa_warehouse` (`warehouse_id`),
  CONSTRAINT `tarifa_warehouse` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=177 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `tblContadores`
--

DROP TABLE IF EXISTS `tblContadores`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tblContadores` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ochoa` int(10) unsigned NOT NULL,
  `nfactura` int(11) DEFAULT '0',
  `nasiento` int(11) DEFAULT '0',
  `serieA` int(11) DEFAULT '0',
  `serieE` int(11) DEFAULT '0',
  `serieR` int(11) DEFAULT '0',
  `serieC` int(11) DEFAULT '0',
  `SerieH` int(11) NOT NULL,
  `serieP` int(11) DEFAULT '0',
  `serieT` int(11) DEFAULT '0',
  `FechaInventario` datetime DEFAULT NULL,
  `serieM` int(11) DEFAULT '0',
  `HistoricoArticulo` int(11) DEFAULT '0',
  `week_goal` int(11) DEFAULT NULL,
  `Rutafotos` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `numCaja` int(11) DEFAULT '0',
  `CodigoRojo` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Tablet_Hora` datetime DEFAULT NULL,
  `t0` int(11) NOT NULL DEFAULT '0',
  `t1` int(11) NOT NULL DEFAULT '0',
  `t2` int(11) NOT NULL DEFAULT '0',
  `t3` int(11) NOT NULL DEFAULT '0',
  `cc` double NOT NULL DEFAULT '0',
  `palet` double NOT NULL DEFAULT '0',
  `campaign` datetime NOT NULL,
  `campaign_life` tinyint(3) unsigned NOT NULL,
  `truck_days` tinyint(3) unsigned NOT NULL,
  `tasa_transporte` double NOT NULL,
  `escaner_path` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `turnoimpreso` int(4) DEFAULT NULL,
  `truck_length` int(11) DEFAULT '24',
  `fuel_consumption` int(11) DEFAULT NULL,
  `petrol` decimal(10,1) DEFAULT NULL,
  `maintenance` decimal(10,1) DEFAULT NULL,
  `hour_price` decimal(10,1) DEFAULT NULL,
  `meter_price` decimal(10,1) DEFAULT NULL,
  `km_price` decimal(10,1) DEFAULT NULL,
  `route_option` int(11) DEFAULT '1',
  `dbproduccion` tinyint(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 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 `vn2008`.`tblContadores_bi` BEFORE INSERT ON `tblContadores` FOR EACH ROW
BEGIN
	DECLARE v_count INT;

	SELECT COUNT(*) INTO v_count FROM tblContadores;

	IF v_count > 0 THEN
		SIGNAL SQLSTATE '45000'
			SET MESSAGE_TEXT = 'ONLY_ONE_ROW_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 `tblIVA`
--

DROP TABLE IF EXISTS `tblIVA`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tblIVA` (
  `tipoiva` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `iva` smallint(6) NOT NULL DEFAULT '0',
  `cuenta` double DEFAULT '0',
  `cuentaRE` double DEFAULT '0',
  `cuentaivaRE` double DEFAULT '0',
  `REQ` double DEFAULT '0',
  PRIMARY KEY (`tipoiva`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `template_bionic_component`
--

DROP TABLE IF EXISTS `template_bionic_component`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `template_bionic_component` (
  `warehouse_id` smallint(5) unsigned NOT NULL,
  `item_id` int(11) NOT NULL,
  `component_id` int(10) unsigned NOT NULL,
  `cost` decimal(10,4) NOT NULL,
  UNIQUE KEY `item_warehouse_component` (`item_id`,`warehouse_id`,`component_id`) USING HASH,
  KEY `item_warehouse` (`item_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 `template_bionic_lot`
--

DROP TABLE IF EXISTS `template_bionic_lot`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `template_bionic_lot` (
  `warehouse_id` smallint(5) unsigned NOT NULL,
  `item_id` int(11) NOT NULL,
  `available` double DEFAULT NULL,
  `buy_id` int(11) DEFAULT NULL,
  `fix` tinyint(3) unsigned DEFAULT '0',
  UNIQUE KEY `warehouse_id` (`warehouse_id`,`item_id`),
  KEY `item_id` (`item_id`)
) ENGINE=MEMORY DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `template_bionic_price`
--

DROP TABLE IF EXISTS `template_bionic_price`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `template_bionic_price` (
  `warehouse_id` smallint(5) unsigned NOT NULL,
  `item_id` int(11) NOT NULL,
  `rate` tinyint(3) unsigned NOT NULL,
  `items` int(11) DEFAULT NULL,
  `grouping` int(11) DEFAULT NULL,
  `price` decimal(10,2) DEFAULT NULL,
  UNIQUE KEY `warehouse_id` (`warehouse_id`,`item_id`,`rate`),
  KEY `item_id` (`item_id`) USING BTREE
) ENGINE=MEMORY DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `thermograph`
--

DROP TABLE IF EXISTS `thermograph`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `thermograph` (
  `thermograph_id` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `model` enum('TL30','SENSITECH','TREKVIEW1','TREKVIEW2','DISPOSABLE') COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`thermograph_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `ticketCreationData`
--

DROP TABLE IF EXISTS `ticketCreationData`;
/*!50001 DROP VIEW IF EXISTS `ticketCreationData`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketCreationData` AS SELECT 
 1 AS `DiadelaSemana`,
 1 AS `Hora`,
 1 AS `Fecha`,
 1 AS `Dispositivo`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `ticket_location`
--

DROP TABLE IF EXISTS `ticket_location`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticket_location` (
  `Id_Ticket` int(11) NOT NULL,
  `longitude` decimal(11,7) DEFAULT NULL,
  `latitude` decimal(11,7) DEFAULT NULL,
  PRIMARY KEY (`Id_Ticket`),
  CONSTRAINT `Id_Ticket_Location` FOREIGN KEY (`Id_Ticket`) REFERENCES `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 `ticket_observation`
--

DROP TABLE IF EXISTS `ticket_observation`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticket_observation` (
  `ticket_observation_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Ticket` int(11) NOT NULL,
  `observation_type_id` tinyint(3) unsigned NOT NULL,
  `text` text COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`ticket_observation_id`),
  UNIQUE KEY `Id_Ticket` (`Id_Ticket`,`observation_type_id`),
  KEY `observation_type_id` (`observation_type_id`),
  CONSTRAINT `ticket_observation_ibfk_1` FOREIGN KEY (`Id_Ticket`) REFERENCES `Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `ticket_observation_ibfk_2` FOREIGN KEY (`observation_type_id`) REFERENCES `observation_type` (`observation_type_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1355598 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Todas las observaciones referentes a un ticket';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `tickets_gestdoc`
--

DROP TABLE IF EXISTS `tickets_gestdoc`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tickets_gestdoc` (
  `Id_Ticket` int(11) NOT NULL,
  `gestdoc_id` int(11) NOT NULL,
  PRIMARY KEY (`Id_Ticket`,`gestdoc_id`),
  KEY `gestdoc_id` (`gestdoc_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `time`
--

DROP TABLE IF EXISTS `time`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `time` (
  `date` date NOT NULL,
  `period` int(6) NOT NULL,
  `month` int(2) NOT NULL,
  `year` int(4) NOT NULL,
  `day` int(2) NOT NULL,
  `week` int(2) NOT NULL,
  `yearMonth` int(6) NOT NULL,
  PRIMARY KEY (`date`),
  KEY `day_index` (`day`) USING HASH,
  KEY `week_index` (`week`) USING HASH,
  KEY `year_index` (`year`) USING HASH,
  KEY `month_index` (`month`) USING HASH,
  KEY `periodo` (`period`) USING HASH,
  KEY `yearMonth` (`yearMonth`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla de referencia para las semanas, años y meses';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `tipsa`
--

DROP TABLE IF EXISTS `tipsa`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tipsa` (
  `kilos` tinyint(3) unsigned NOT NULL,
  `importe` double unsigned NOT NULL,
  `zona` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`kilos`,`zona`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `tmpNEWTARIFAS`
--

DROP TABLE IF EXISTS `tmpNEWTARIFAS`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tmpNEWTARIFAS` (
  `Id_Cliente` int(11) NOT NULL,
  `Cliente` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `Consumo_medio_mensual` double(17,0) DEFAULT NULL,
  `Tarifa_Actual` int(11) DEFAULT '0',
  `Nueva_Tarifa` int(11) DEFAULT NULL,
  `Id_Trabajador` int(11) DEFAULT '20',
  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 `transport`
--

DROP TABLE IF EXISTS `transport`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `transport` (
  `wday` tinyint(4) NOT NULL,
  PRIMARY KEY (`wday`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `travel`
--

DROP TABLE IF EXISTS `travel`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `travel` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `shipment` date DEFAULT NULL,
  `shipment_hour` time DEFAULT NULL,
  `landing` date NOT NULL,
  `landing_hour` time DEFAULT NULL,
  `warehouse_id` smallint(6) unsigned DEFAULT NULL,
  `warehouse_id_out` smallint(6) unsigned DEFAULT NULL,
  `agency_id` int(11) DEFAULT NULL,
  `ref` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `delivered` tinyint(1) NOT NULL DEFAULT '0',
  `received` tinyint(1) NOT NULL DEFAULT '0',
  `m3` decimal(10,2) unsigned DEFAULT NULL,
  `kg` decimal(10,0) unsigned DEFAULT NULL,
  `cargoSupplierFk` int(11) DEFAULT NULL,
  `totalEntries` tinyint(4) unsigned DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `shipment_2` (`shipment`,`landing`,`warehouse_id`,`warehouse_id_out`,`agency_id`,`ref`),
  KEY `agency_id` (`agency_id`),
  KEY `shipment` (`shipment`),
  KEY `landing` (`landing`),
  KEY `warehouse_landing` (`warehouse_id`,`landing`),
  KEY `warehouse_out_shipment` (`warehouse_id_out`,`shipment`),
  KEY `travel_ibfk_4_idx` (`cargoSupplierFk`),
  CONSTRAINT `travel_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `travel_ibfk_2` FOREIGN KEY (`warehouse_id_out`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `travel_ibfk_3` FOREIGN KEY (`agency_id`) REFERENCES `Agencias` (`Id_Agencia`) ON UPDATE CASCADE,
  CONSTRAINT `travel_ibfk_4` FOREIGN KEY (`cargoSupplierFk`) REFERENCES `Proveedores_cargueras` (`Id_Proveedor`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=130347 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `travel_beforeInsert`
	BEFORE INSERT ON `travel`
    FOR EACH ROW
BEGIN	
	CALL vn.travel_checkDates(NEW.shipment, NEW.landing);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `travel_beforeUpdate`
	BEFORE UPDATE ON `travel`
    FOR EACH ROW
BEGIN	
	IF !(NEW.landing <=> OLD.landing)
	OR !(NEW.shipment <=> OLD.shipment) THEN
		CALL vn.travel_checkDates(NEW.shipment, NEW.landing);
	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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `travel_afterUpdate`
	AFTER UPDATE ON `travel`
    FOR EACH ROW
BEGIN	
	CALL stock.log_add('travel', OLD.id, NEW.id);

    IF !(NEW.shipment <=> OLD.shipment) THEN
		UPDATE vn.entry 
			SET commission = vn.entry_calcCommission(commission, travelFk, currencyFk)
			WHERE travelFk = NEW.id;
    END IF;

	IF !(ABS(NEW.delivered) <=> ABS(OLD.delivered))
    THEN
		INSERT INTO vn2008.travel_dits SET
			idaccion_dits = 89,
			Id_Trabajador = vn.getWorker(),
            Id_Ticket = NEW.id,
            value_old = OLD.delivered,
            value_new = NEW.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 */ ;

--
-- Table structure for table `travel_dits`
--

DROP TABLE IF EXISTS `travel_dits`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `travel_dits` (
  `idtravel_dits` int(11) NOT NULL AUTO_INCREMENT,
  `idaccion_dits` int(11) NOT NULL,
  `ODBC_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `Id_Ticket` int(11) NOT NULL,
  `Id_Trabajador` int(11) DEFAULT NULL,
  `value_old` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value_new` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`idtravel_dits`),
  KEY `fgkey1_idx` (`idaccion_dits`),
  KEY `fgkey2_idx` (`Id_Ticket`),
  KEY `fgkey3_idx` (`Id_Trabajador`),
  CONSTRAINT `travel_dits_ibfk_1` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=220286 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `travel_pattern`
--

DROP TABLE IF EXISTS `travel_pattern`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `travel_pattern` (
  `travel_pattern_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `week_start` tinyint(3) unsigned NOT NULL,
  `week_end` tinyint(3) unsigned NOT NULL,
  `warehouse_out` smallint(5) unsigned NOT NULL,
  `warehouse_in` smallint(5) unsigned NOT NULL,
  `agency_id` int(11) NOT NULL,
  `day_out` tinyint(3) unsigned NOT NULL,
  `duration` tinyint(3) unsigned NOT NULL,
  `ref` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `cargoSupplierFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`travel_pattern_id`),
  KEY `warehouse_out` (`warehouse_out`),
  KEY `warehouse_in` (`warehouse_in`),
  KEY `agency_id` (`agency_id`),
  KEY `travel_pattern_ibfk_6_idx` (`cargoSupplierFk`),
  CONSTRAINT `travel_pattern_ibfk_3` FOREIGN KEY (`warehouse_out`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `travel_pattern_ibfk_4` FOREIGN KEY (`agency_id`) REFERENCES `Agencias` (`Id_Agencia`) ON UPDATE CASCADE,
  CONSTRAINT `travel_pattern_ibfk_5` FOREIGN KEY (`warehouse_in`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `travel_pattern_ibfk_6` FOREIGN KEY (`cargoSupplierFk`) REFERENCES `Proveedores` (`Id_Proveedor`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=341 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `travel_reserve`
--

DROP TABLE IF EXISTS `travel_reserve`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `travel_reserve` (
  `travel_reserve_id` int(11) NOT NULL AUTO_INCREMENT,
  `travel_id` int(11) unsigned NOT NULL,
  `Id_Trabajador` int(11) NOT NULL,
  `reserved` decimal(4,1) DEFAULT NULL,
  `buyed` decimal(4,1) DEFAULT NULL,
  `askingfor` decimal(4,1) DEFAULT NULL,
  `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `labeled` decimal(4,1) unsigned NOT NULL DEFAULT '0.0',
  PRIMARY KEY (`Id_Trabajador`,`travel_id`),
  UNIQUE KEY `travel_reserve_id_UNIQUE` (`travel_reserve_id`),
  KEY `travel_travel_reserve_idx` (`travel_id`),
  KEY `traveL_buyer_id_idx` (`Id_Trabajador`),
  CONSTRAINT `travel_reserve_ibfk_1` FOREIGN KEY (`travel_id`) REFERENCES `travel` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='En esta tabla almacenamos los m3 que cada comprador tiene asignados, por travel.';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `travel_thermograph`
--

DROP TABLE IF EXISTS `travel_thermograph`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `travel_thermograph` (
  `thermograph_id` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `odbc_date` date NOT NULL,
  `warehouse_id` smallint(6) unsigned NOT NULL,
  `travel_id` int(10) unsigned DEFAULT NULL,
  `temperature` enum('COOL','WARM') COLLATE utf8_unicode_ci NOT NULL,
  `result` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `gestdoc_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`thermograph_id`,`odbc_date`),
  KEY `thermograph_fk_idx` (`thermograph_id`),
  KEY `gestdoc_fk_idx` (`gestdoc_id`),
  KEY `travel_id` (`travel_id`),
  KEY `warehouse_id` (`warehouse_id`),
  CONSTRAINT `gestdoc_fk` FOREIGN KEY (`gestdoc_id`) REFERENCES `gestdoc` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `thermograph_fk` FOREIGN KEY (`thermograph_id`) REFERENCES `thermograph` (`thermograph_id`) ON UPDATE CASCADE,
  CONSTRAINT `travel_fk` FOREIGN KEY (`travel_id`) REFERENCES `travel` (`id`),
  CONSTRAINT `travel_thermograph_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Registra cada termografo que se ha introducido en cada travel';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `trolley`
--

DROP TABLE IF EXISTS `trolley`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `trolley` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `fecha` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `ref` varchar(4) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=132 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `turn`
--

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

--
-- Table structure for table `unary`
--

DROP TABLE IF EXISTS `unary`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `unary` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `parent` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `idunary_UNIQUE` (`id`),
  KEY `unary_parent_idx` (`parent`),
  CONSTRAINT `unary_parent` FOREIGN KEY (`parent`) REFERENCES `unary` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=886 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `unaryScanFilter`
--

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

DROP TABLE IF EXISTS `unary_scan`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `unary_scan` (
  `unary_id` int(11) NOT NULL,
  `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `type` set('BUYS','EXPEDITIONS') COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`unary_id`),
  KEY `scan_unary_idx` (`unary_id`),
  CONSTRAINT `unary_scan` FOREIGN KEY (`unary_id`) REFERENCES `unary` (`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 `unary_scan_line`
--

DROP TABLE IF EXISTS `unary_scan_line`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `unary_scan_line` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `code` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `unary_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`),
  KEY `unary_line_idx` (`unary_id`),
  CONSTRAINT `unary_line` FOREIGN KEY (`unary_id`) REFERENCES `unary_scan` (`unary_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=8462 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `unary_scan_line_buy`
--

DROP TABLE IF EXISTS `unary_scan_line_buy`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `unary_scan_line_buy` (
  `scan_line_id` int(11) NOT NULL,
  `Id_Article` int(11) NOT NULL,
  PRIMARY KEY (`scan_line_id`),
  UNIQUE KEY `scan_line_id_UNIQUE` (`scan_line_id`),
  KEY `Id_Article_buy_idx` (`Id_Article`),
  CONSTRAINT `Id_Article_buy` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `scan_line_id_patriarcal` FOREIGN KEY (`scan_line_id`) REFERENCES `unary_scan_line` (`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 `unary_scan_line_expedition`
--

DROP TABLE IF EXISTS `unary_scan_line_expedition`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `unary_scan_line_expedition` (
  `scan_line_id` int(11) NOT NULL,
  `expedition_id` int(11) NOT NULL,
  PRIMARY KEY (`scan_line_id`),
  UNIQUE KEY `scan_line_id_UNIQUE` (`scan_line_id`),
  KEY `expedition_id_scan_idx` (`expedition_id`),
  CONSTRAINT `expedition_id_scan` FOREIGN KEY (`expedition_id`) REFERENCES `expeditions` (`expeditions_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 `unary_source`
--

DROP TABLE IF EXISTS `unary_source`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `unary_source` (
  `name` varchar(100) 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 */;

--
-- Temporary table structure for view `v_Agenda`
--

DROP TABLE IF EXISTS `v_Agenda`;
/*!50001 DROP VIEW IF EXISTS `v_Agenda`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_Agenda` AS SELECT 
 1 AS `Tipo`,
 1 AS `Id`,
 1 AS `Nombre`,
 1 AS `Telephone`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_Agenda2`
--

DROP TABLE IF EXISTS `v_Agenda2`;
/*!50001 DROP VIEW IF EXISTS `v_Agenda2`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_Agenda2` AS SELECT 
 1 AS `Tipo`,
 1 AS `Id`,
 1 AS `Nombre`,
 1 AS `Telefono`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_Articles_botanical`
--

DROP TABLE IF EXISTS `v_Articles_botanical`;
/*!50001 DROP VIEW IF EXISTS `v_Articles_botanical`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_Articles_botanical` AS SELECT 
 1 AS `Id_Article`,
 1 AS `edi_botanic`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_Movimientos_Volumen_shipping_charge`
--

DROP TABLE IF EXISTS `v_Movimientos_Volumen_shipping_charge`;
/*!50001 DROP VIEW IF EXISTS `v_Movimientos_Volumen_shipping_charge`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_Movimientos_Volumen_shipping_charge` AS SELECT 
 1 AS `Id_Ticket`,
 1 AS `Id_Ruta`,
 1 AS `Id_Movimiento`,
 1 AS `Fecha`,
 1 AS `price`,
 1 AS `freight`,
 1 AS `volume`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_Ordenes`
--

DROP TABLE IF EXISTS `v_Ordenes`;
/*!50001 DROP VIEW IF EXISTS `v_Ordenes`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_Ordenes` AS SELECT 
 1 AS `Id_ORDEN`,
 1 AS `ORDEN`,
 1 AS `datORDEN`,
 1 AS `datTICKET`,
 1 AS `CodVENDEDOR`,
 1 AS `CodCOMPRADOR`,
 1 AS `CANTIDAD`,
 1 AS `PRECIOMAX`,
 1 AS `PREU`,
 1 AS `Id_ARTICLE`,
 1 AS `Id_CLIENTE`,
 1 AS `COMENTARIO`,
 1 AS `OK`,
 1 AS `TOTAL`,
 1 AS `datCOMPRA`,
 1 AS `KO`,
 1 AS `Id_Movimiento`,
 1 AS `odbc_date`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_XDiario_ALL`
--

DROP TABLE IF EXISTS `v_XDiario_ALL`;
/*!50001 DROP VIEW IF EXISTS `v_XDiario_ALL`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_XDiario_ALL` AS SELECT 
 1 AS `empresa_id`,
 1 AS `SUBCTA`,
 1 AS `Eurodebe`,
 1 AS `Eurohaber`,
 1 AS `Fecha`,
 1 AS `FECHA_EX`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_accion`
--

DROP TABLE IF EXISTS `v_accion`;
/*!50001 DROP VIEW IF EXISTS `v_accion`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_accion` AS SELECT 
 1 AS `accion_id`,
 1 AS `accion`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_account`
--

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

--
-- Temporary table structure for view `v_analisis_ventas`
--

DROP TABLE IF EXISTS `v_analisis_ventas`;
/*!50001 DROP VIEW IF EXISTS `v_analisis_ventas`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_analisis_ventas` AS SELECT 
 1 AS `Familia`,
 1 AS `Reino`,
 1 AS `Comercial`,
 1 AS `Comprador`,
 1 AS `Provincia`,
 1 AS `almacen`,
 1 AS `Año`,
 1 AS `Mes`,
 1 AS `Semana`,
 1 AS `Vista`,
 1 AS `Importe`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_awb_volumen`
--

DROP TABLE IF EXISTS `v_awb_volumen`;
/*!50001 DROP VIEW IF EXISTS `v_awb_volumen`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_awb_volumen` AS SELECT 
 1 AS `awb_id`,
 1 AS `codigo`,
 1 AS `importe`,
 1 AS `Vol_Total`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_barcodes`
--

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

--
-- Temporary table structure for view `v_botanic_export`
--

DROP TABLE IF EXISTS `v_botanic_export`;
/*!50001 DROP VIEW IF EXISTS `v_botanic_export`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_botanic_export` AS SELECT 
 1 AS `Nom_botanic`,
 1 AS `Id_Paises`,
 1 AS `restriction`,
 1 AS `description`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_compres`
--

DROP TABLE IF EXISTS `v_compres`;
/*!50001 DROP VIEW IF EXISTS `v_compres`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_compres` AS SELECT 
 1 AS `Familia`,
 1 AS `reino_id`,
 1 AS `Id_Compra`,
 1 AS `Id_Entrada`,
 1 AS `Id_Article`,
 1 AS `Cantidad`,
 1 AS `Costefijo`,
 1 AS `Portefijo`,
 1 AS `Novincular`,
 1 AS `Etiquetas`,
 1 AS `Packing`,
 1 AS `grouping`,
 1 AS `Comisionfija`,
 1 AS `Embalajefijo`,
 1 AS `Nicho`,
 1 AS `Id_Cubo`,
 1 AS `Tarifa1`,
 1 AS `Tarifa2`,
 1 AS `Tarifa3`,
 1 AS `PVP`,
 1 AS `Vida`,
 1 AS `Id_Trabajador`,
 1 AS `punteo`,
 1 AS `odbc_date`,
 1 AS `Inventario`,
 1 AS `Id_Proveedor`,
 1 AS `Fecha`,
 1 AS `Confirmada`,
 1 AS `Redada`,
 1 AS `empresa_id`,
 1 AS `travel_id`,
 1 AS `Pedida`,
 1 AS `recibida_id`,
 1 AS `id`,
 1 AS `shipment`,
 1 AS `landing`,
 1 AS `warehouse_id`,
 1 AS `warehouse_id_out`,
 1 AS `agency_id`,
 1 AS `ref`,
 1 AS `delivered`,
 1 AS `received`,
 1 AS `Article`,
 1 AS `Medida`,
 1 AS `Tallos`,
 1 AS `caja`,
 1 AS `Categoria`,
 1 AS `id_origen`,
 1 AS `Tipo`,
 1 AS `tipo_id`,
 1 AS `Color`,
 1 AS `Min`,
 1 AS `Coste`,
 1 AS `fuente`,
 1 AS `iva_group_id`,
 1 AS `cm3`,
 1 AS `producer_id`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_departure_limit`
--

DROP TABLE IF EXISTS `v_departure_limit`;
/*!50001 DROP VIEW IF EXISTS `v_departure_limit`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_departure_limit` AS SELECT 
 1 AS `warehouse_id`,
 1 AS `fecha`,
 1 AS `hora`,
 1 AS `minSpeed`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_descuadre_bionic`
--

DROP TABLE IF EXISTS `v_descuadre_bionic`;
/*!50001 DROP VIEW IF EXISTS `v_descuadre_bionic`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_descuadre_bionic` AS SELECT 
 1 AS `Id_Ticket`,
 1 AS `Alias`,
 1 AS `Concepte`,
 1 AS `suma_componente`,
 1 AS `Preu`,
 1 AS `Descuento`,
 1 AS `diferencia`,
 1 AS `Fecha`,
 1 AS `benvenut`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_descuadre_porte2`
--

DROP TABLE IF EXISTS `v_descuadre_porte2`;
/*!50001 DROP VIEW IF EXISTS `v_descuadre_porte2`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_descuadre_porte2` AS SELECT 
 1 AS `Id_Ticket`,
 1 AS `suma_componente`,
 1 AS `Fecha`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_descuadre_portekk`
--

DROP TABLE IF EXISTS `v_descuadre_portekk`;
/*!50001 DROP VIEW IF EXISTS `v_descuadre_portekk`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_descuadre_portekk` AS SELECT 
 1 AS `Id_Ticket`,
 1 AS `suma_componente`,
 1 AS `teorico_agencia`,
 1 AS `diferencia`,
 1 AS `Fecha`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_empresa`
--

DROP TABLE IF EXISTS `v_empresa`;
/*!50001 DROP VIEW IF EXISTS `v_empresa`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_empresa` AS SELECT 
 1 AS `logo`,
 1 AS `id`,
 1 AS `registro`,
 1 AS `gerente_id`,
 1 AS `alta`,
 1 AS `Nombre`,
 1 AS `Apellidos`,
 1 AS `Proveedor`,
 1 AS `Domicilio`,
 1 AS `CP`,
 1 AS `Localidad`,
 1 AS `NIF`,
 1 AS `Telefono`,
 1 AS `Alias`,
 1 AS `abbreviation`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_encajado`
--

DROP TABLE IF EXISTS `v_encajado`;
/*!50001 DROP VIEW IF EXISTS `v_encajado`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_encajado` AS SELECT 
 1 AS `hora`,
 1 AS `minuto`,
 1 AS `cm3`,
 1 AS `warehouse_id`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_encajado_ultima_hora`
--

DROP TABLE IF EXISTS `v_encajado_ultima_hora`;
/*!50001 DROP VIEW IF EXISTS `v_encajado_ultima_hora`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_encajado_ultima_hora` AS SELECT 
 1 AS `m3`,
 1 AS `warehouse_id`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_expeditions_shipping_charge2`
--

DROP TABLE IF EXISTS `v_expeditions_shipping_charge2`;
/*!50001 DROP VIEW IF EXISTS `v_expeditions_shipping_charge2`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_expeditions_shipping_charge2` AS SELECT 
 1 AS `Id_Ticket`,
 1 AS `shipping_charge`,
 1 AS `Fecha`,
 1 AS `warehouse_id`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_expeditions_shipping_charge_by_container`
--

DROP TABLE IF EXISTS `v_expeditions_shipping_charge_by_container`;
/*!50001 DROP VIEW IF EXISTS `v_expeditions_shipping_charge_by_container`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_expeditions_shipping_charge_by_container` AS SELECT 
 1 AS `Id_Ticket`,
 1 AS `Fecha`,
 1 AS `Id_Article`,
 1 AS `price`,
 1 AS `Id_Ruta`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_expeditions_shipping_chargekk`
--

DROP TABLE IF EXISTS `v_expeditions_shipping_chargekk`;
/*!50001 DROP VIEW IF EXISTS `v_expeditions_shipping_chargekk`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_expeditions_shipping_chargekk` AS SELECT 
 1 AS `Id_Ticket`,
 1 AS `shipping_charge`,
 1 AS `Fecha`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_fallo`
--

DROP TABLE IF EXISTS `v_fallo`;
/*!50001 DROP VIEW IF EXISTS `v_fallo`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_fallo` AS SELECT 
 1 AS `queja_id`,
 1 AS `accion_id`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_inter`
--

DROP TABLE IF EXISTS `v_inter`;
/*!50001 DROP VIEW IF EXISTS `v_inter`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_inter` AS SELECT 
 1 AS `inter_id`,
 1 AS `state_id`,
 1 AS `nota`,
 1 AS `odbc_date`,
 1 AS `Id_Ticket`,
 1 AS `Id_Trabajador`,
 1 AS `Id_supervisor`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_jerarquia`
--

DROP TABLE IF EXISTS `v_jerarquia`;
/*!50001 DROP VIEW IF EXISTS `v_jerarquia`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_jerarquia` AS SELECT 
 1 AS `Id_Trabajador`,
 1 AS `boss_id`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_location`
--

DROP TABLE IF EXISTS `v_location`;
/*!50001 DROP VIEW IF EXISTS `v_location`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_location` AS SELECT 
 1 AS `longitude`,
 1 AS `latitude`,
 1 AS `Id_Consigna`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_mana_spellers`
--

DROP TABLE IF EXISTS `v_mana_spellers`;
/*!50001 DROP VIEW IF EXISTS `v_mana_spellers`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_mana_spellers` AS SELECT 
 1 AS `Id_Trabajador`,
 1 AS `size`,
 1 AS `used`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_miriam`
--

DROP TABLE IF EXISTS `v_miriam`;
/*!50001 DROP VIEW IF EXISTS `v_miriam`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_miriam` AS SELECT 
 1 AS `Id_Article`,
 1 AS `Concepte`,
 1 AS `Cantidad`,
 1 AS `Preu`,
 1 AS `Descuento`,
 1 AS `Fecha`,
 1 AS `Id_Cliente`,
 1 AS `Importe`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_movimientos_mark`
--

DROP TABLE IF EXISTS `v_movimientos_mark`;
/*!50001 DROP VIEW IF EXISTS `v_movimientos_mark`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_movimientos_mark` AS SELECT 
 1 AS `Id_Movimiento`,
 1 AS `Accion`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_pedidos_auto_preparadosKk`
--

DROP TABLE IF EXISTS `v_pedidos_auto_preparadosKk`;
/*!50001 DROP VIEW IF EXISTS `v_pedidos_auto_preparadosKk`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_pedidos_auto_preparadosKk` AS SELECT 
 1 AS `CodigoTrabajador`,
 1 AS `Id_Ticket`,
 1 AS `Momento`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_phonebook`
--

DROP TABLE IF EXISTS `v_phonebook`;
/*!50001 DROP VIEW IF EXISTS `v_phonebook`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_phonebook` AS SELECT 
 1 AS `Id_Cliente`,
 1 AS `Telefono`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_price_fixed`
--

DROP TABLE IF EXISTS `v_price_fixed`;
/*!50001 DROP VIEW IF EXISTS `v_price_fixed`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_price_fixed` AS SELECT 
 1 AS `warehouse_id`,
 1 AS `item_id`,
 1 AS `rate_0`,
 1 AS `rate_1`,
 1 AS `rate_2`,
 1 AS `rate_3`,
 1 AS `date_start`,
 1 AS `date_end`,
 1 AS `bonus`,
 1 AS `grouping`,
 1 AS `Packing`,
 1 AS `caja`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_price_fixed_group`
--

DROP TABLE IF EXISTS `v_price_fixed_group`;
/*!50001 DROP VIEW IF EXISTS `v_price_fixed_group`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_price_fixed_group` AS SELECT 
 1 AS `warehouse_id`,
 1 AS `item_id`,
 1 AS `rate_0`,
 1 AS `rate_1`,
 1 AS `rate_2`,
 1 AS `rate_3`,
 1 AS `date_start`,
 1 AS `date_end`,
 1 AS `bonus`,
 1 AS `grouping`,
 1 AS `Packing`,
 1 AS `caja`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_session`
--

DROP TABLE IF EXISTS `v_session`;
/*!50001 DROP VIEW IF EXISTS `v_session`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_session` AS SELECT 
 1 AS `id`,
 1 AS `CodigoTrabajador`,
 1 AS `Id_Trabajador`,
 1 AS `Id_Cliente`,
 1 AS `Cliente`,
 1 AS `Fecha`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_ticket_amount`
--

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

--
-- Temporary table structure for view `v_trabajadores`
--

DROP TABLE IF EXISTS `v_trabajadores`;
/*!50001 DROP VIEW IF EXISTS `v_trabajadores`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_trabajadores` AS SELECT 
 1 AS `CodigoTrabajador`,
 1 AS `Nombre`,
 1 AS `Fecha_Inicio`,
 1 AS `Password`,
 1 AS `user`,
 1 AS `Apellidos`,
 1 AS `Id_Trabajador`,
 1 AS `Foto`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_user`
--

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

--
-- Temporary table structure for view `v_ventes`
--

DROP TABLE IF EXISTS `v_ventes`;
/*!50001 DROP VIEW IF EXISTS `v_ventes`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_ventes` AS SELECT 
 1 AS `Agencia`,
 1 AS `Categoria`,
 1 AS `tipo_id`,
 1 AS `Medida`,
 1 AS `Article`,
 1 AS `Color`,
 1 AS `Id_Cliente`,
 1 AS `Tipo`,
 1 AS `Factura`,
 1 AS `warehouse_id`,
 1 AS `Id_Movimiento`,
 1 AS `Id_Article`,
 1 AS `Familia`,
 1 AS `Id_Ticket`,
 1 AS `Concepte`,
 1 AS `Cantidad`,
 1 AS `quantity`,
 1 AS `Preu`,
 1 AS `Descuento`,
 1 AS `CostFixat`,
 1 AS `Reservado`,
 1 AS `OK`,
 1 AS `PrecioFijado`,
 1 AS `odbc_date`,
 1 AS `Fecha`,
 1 AS `FechaCompleta`,
 1 AS `Alias`,
 1 AS `Id_Consigna`,
 1 AS `Importe`,
 1 AS `Origen`,
 1 AS `reino_id`,
 1 AS `invoice`,
 1 AS `producer_id`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_warehouse`
--

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

--
-- Temporary table structure for view `v_xsubclien`
--

DROP TABLE IF EXISTS `v_xsubclien`;
/*!50001 DROP VIEW IF EXISTS `v_xsubclien`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_xsubclien` AS SELECT 
 1 AS `Id_Cliente`,
 1 AS `empresa_id`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_xsubcuentas`
--

DROP TABLE IF EXISTS `v_xsubcuentas`;
/*!50001 DROP VIEW IF EXISTS `v_xsubcuentas`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_xsubcuentas` AS SELECT 
 1 AS `COD`,
 1 AS `TITULO`,
 1 AS `NIF`,
 1 AS `DOMICILIO`,
 1 AS `POBLACION`,
 1 AS `PROVINCIA`,
 1 AS `CODPOSTAL`,
 1 AS `country_code`,
 1 AS `empresa_id`,
 1 AS `EMAIL`,
 1 AS `IDNIF`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `v_xsubprov`
--

DROP TABLE IF EXISTS `v_xsubprov`;
/*!50001 DROP VIEW IF EXISTS `v_xsubprov`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_xsubprov` AS SELECT 
 1 AS `proveedor_id`,
 1 AS `empresa_id`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `versiones`
--

DROP TABLE IF EXISTS `versiones`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `versiones` (
  `programa` varchar(11) COLLATE utf8_unicode_ci NOT NULL,
  `version` int(11) NOT NULL,
  `critical` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`programa`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `viaxpress`
--

DROP TABLE IF EXISTS `viaxpress`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `viaxpress` (
  `codigo_postal` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
  `zona` tinyint(4) NOT NULL DEFAULT '2',
  `m_t` tinyint(4) NOT NULL DEFAULT '0',
  `POBLACION` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `PROVINCIA` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`codigo_postal`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `vnCreditClassification`
--

DROP TABLE IF EXISTS `vnCreditClassification`;
/*!50001 DROP VIEW IF EXISTS `vnCreditClassification`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `vnCreditClassification` AS SELECT 
 1 AS `id`,
 1 AS `client`,
 1 AS `dateStart`,
 1 AS `dateEnd`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `vnCreditInsurance`
--

DROP TABLE IF EXISTS `vnCreditInsurance`;
/*!50001 DROP VIEW IF EXISTS `vnCreditInsurance`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `vnCreditInsurance` AS SELECT 
 1 AS `id`,
 1 AS `creditClassification`,
 1 AS `credit`,
 1 AS `creationDate`,
 1 AS `grade`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `vnSolunionCAP`
--

DROP TABLE IF EXISTS `vnSolunionCAP`;
/*!50001 DROP VIEW IF EXISTS `vnSolunionCAP`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `vnSolunionCAP` AS SELECT 
 1 AS `creditInsurance`,
 1 AS `dateStart`,
 1 AS `dateEnd`,
 1 AS `dateLeaving`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `warehouse`
--

DROP TABLE IF EXISTS `warehouse`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `warehouse` (
  `id` smallint(6) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `fuente` tinyint(1) unsigned NOT NULL DEFAULT '0',
  `address_name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `delay` double NOT NULL DEFAULT '0.004',
  `reserve` tinyint(4) NOT NULL DEFAULT '0',
  `tpv` tinyint(2) unsigned zerofill NOT NULL DEFAULT '00',
  `Id_Paises` mediumint(8) unsigned NOT NULL DEFAULT '1',
  `zone_label` tinyint(4) NOT NULL DEFAULT '0',
  `comisionantes` tinyint(4) NOT NULL DEFAULT '0',
  `inventario` tinyint(2) NOT NULL DEFAULT '0',
  `is_comparative` tinyint(2) NOT NULL DEFAULT '0' COMMENT 'Si esta a true,en la comparativa muestra el stock de este almacen, cuando no se especifica almacen.',
  `valuatedInventory` tinyint(2) NOT NULL DEFAULT '0',
  `isManaged` tinyint(2) NOT NULL DEFAULT '0' COMMENT 'Se añaden los cubos de expedition a la tabla ticketPackaging',
  `hasConfectionTeam` tinyint(1) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `name_UNIQUE` (`name`),
  KEY `Id_Paises` (`Id_Paises`),
  CONSTRAINT `warehouse_ibfk_1` FOREIGN KEY (`Id_Paises`) REFERENCES `Paises` (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=58 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              = '' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `warehouse_ai` AFTER INSERT ON `warehouse` FOR EACH ROW
begin
	IF NEW.Fuente THEN
		INSERT INTO warehouse_alias (alias) VALUES(NEW.`name`);
		INSERT INTO warehouse_joined(warehouse_id,warehouse_alias_id) 
			VALUES(NEW.id,LAST_INSERT_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 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `warehouse_au` AFTER UPDATE ON `warehouse` FOR EACH ROW
begin
	IF NEW.fuente IS TRUE and OLD.fuente IS FALSE then
		INSERT INTO warehouse_alias (alias) VALUES(NEW.`name`);
		INSERT INTO warehouse_joined(warehouse_id,warehouse_alias_id) 
			VALUES(NEW.id,LAST_INSERT_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 */ ;

--
-- Table structure for table `warehouse_alias`
--

DROP TABLE IF EXISTS `warehouse_alias`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `warehouse_alias` (
  `warehouse_alias_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `alias` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`warehouse_alias_id`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `warehouse_filtro`
--

DROP TABLE IF EXISTS `warehouse_filtro`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `warehouse_filtro` (
  `warehouse_id` smallint(6) unsigned NOT NULL,
  `Id_Trabajador` int(11) NOT NULL,
  `ok` tinyint(3) unsigned DEFAULT '1',
  PRIMARY KEY (`Id_Trabajador`,`warehouse_id`),
  KEY `wh_worker_idx` (`Id_Trabajador`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla que permite filtrar los almacenes que muestra la comparativa, recordando la selección personal del usuario';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `warehouse_group`
--

DROP TABLE IF EXISTS `warehouse_group`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `warehouse_group` (
  `warehouse_alias_id` smallint(5) unsigned NOT NULL DEFAULT '22',
  `warehouse_id` smallint(5) unsigned NOT NULL,
  PRIMARY KEY (`warehouse_alias_id`,`warehouse_id`),
  KEY `warehosue_group_ware_idx` (`warehouse_id`),
  CONSTRAINT `warehosue_group_ware` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `warehouse_group_alias` FOREIGN KEY (`warehouse_alias_id`) REFERENCES `warehouse_alias` (`warehouse_alias_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Agrupa warehouses	';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `warehouse_joined`
--

DROP TABLE IF EXISTS `warehouse_joined`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `warehouse_joined` (
  `warehouse_id` smallint(5) unsigned NOT NULL,
  `warehouse_alias_id` smallint(5) unsigned NOT NULL,
  PRIMARY KEY (`warehouse_id`,`warehouse_alias_id`),
  CONSTRAINT `warehouse_joined_ibfk_3` FOREIGN KEY (`warehouse_id`) REFERENCES `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 `warehouse_lc`
--

DROP TABLE IF EXISTS `warehouse_lc`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `warehouse_lc` (
  `whin` smallint(6) unsigned NOT NULL,
  `whout` smallint(6) unsigned NOT NULL,
  `m3` double NOT NULL DEFAULT '15',
  `days` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`whin`,`whout`),
  KEY `whout_wh_idx` (`whout`),
  CONSTRAINT `whin_wh` FOREIGN KEY (`whin`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `whout_wh` FOREIGN KEY (`whout`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Warehouses cost for linking';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `warehouse_pickup`
--

DROP TABLE IF EXISTS `warehouse_pickup`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `warehouse_pickup` (
  `warehouse_id` smallint(5) unsigned NOT NULL,
  `agency_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`warehouse_id`),
  UNIQUE KEY `agency_id` (`agency_id`,`warehouse_id`),
  CONSTRAINT `warehouse_pickup_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `warehouse_pickup_ibfk_2` FOREIGN KEY (`agency_id`) REFERENCES `Agencias` (`Id_Agencia`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `wh_selection`
--

DROP TABLE IF EXISTS `wh_selection`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wh_selection` (
  `Id_Trabajador` int(11) NOT NULL,
  `warehouse_id` smallint(6) unsigned NOT NULL,
  PRIMARY KEY (`Id_Trabajador`,`warehouse_id`),
  KEY `Trabajadores` (`Id_Trabajador`),
  KEY `Warehouse` (`warehouse_id`),
  CONSTRAINT `Trabajadores` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE,
  CONSTRAINT `Warehouse` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Permite que los usuarios seleccionen los almacenes que van a';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `widget`
--

DROP TABLE IF EXISTS `widget`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `widget` (
  `widget_id` int(11) NOT NULL,
  `chr` int(11) NOT NULL,
  PRIMARY KEY (`widget_id`),
  UNIQUE KEY `chr_UNIQUE` (`chr`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `wks`
--

DROP TABLE IF EXISTS `wks`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wks` (
  `wk` int(10) unsigned NOT NULL,
  `yr` int(10) unsigned NOT NULL,
  `vwk` int(10) unsigned NOT NULL,
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `comments` text COLLATE utf8_unicode_ci,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=626 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workcenter_holiday`
--

DROP TABLE IF EXISTS `workcenter_holiday`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workcenter_holiday` (
  `workcenter_id` int(11) NOT NULL,
  `day` double NOT NULL,
  `year` smallint(6) NOT NULL,
  PRIMARY KEY (`workcenter_id`,`year`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `workerDocument`
--

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

--
-- Table structure for table `workerTeam`
--

DROP TABLE IF EXISTS `workerTeam`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerTeam` (
  `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=219 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `workerTeamCollegues`
--

DROP TABLE IF EXISTS `workerTeamCollegues`;
/*!50001 DROP VIEW IF EXISTS `workerTeamCollegues`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `workerTeamCollegues` AS SELECT 
 1 AS `workerId`,
 1 AS `collegueId`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `zelerisKk`
--

DROP TABLE IF EXISTS `zelerisKk`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zelerisKk` (
  `codigo_postal` mediumint(8) unsigned NOT NULL,
  `franja` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`codigo_postal`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `zoneNickname`
--

DROP TABLE IF EXISTS `zoneNickname`;
/*!50001 DROP VIEW IF EXISTS `zoneNickname`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `zoneNickname` AS SELECT 
 1 AS `warehouse_id`,
 1 AS `agency_id`,
 1 AS `zona`,
 1 AS `alias`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `zones`
--

DROP TABLE IF EXISTS `zones`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zones` (
  `zone_id` tinyint(4) NOT NULL,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `printingOrder` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`zone_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Zonas de reparto';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping events for database 'vn2008'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `cierre automatico` */;
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 `cierre automatico` ON SCHEDULE EVERY 1 DAY STARTS '2016-05-25 23:00:00' ON COMPLETION NOT PRESERVE DISABLE COMMENT 'Realiza el cierre de todos los Warehouse' DO INSERT INTO `vn2008`.`Colas` (`Id_Informe`,`Cola`) VALUES ('2',CURDATE()) */ ;;
/*!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 `closeTickets` */;;
DELIMITER ;;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
/*!50003 SET character_set_client  = utf8mb4 */ ;;
/*!50003 SET character_set_results = utf8mb4 */ ;;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone      = @@time_zone */ ;;
/*!50003 SET time_zone             = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `closeTickets` ON SCHEDULE EVERY 1 DAY STARTS '2017-06-23 07:20:00' ON COMPLETION NOT PRESERVE DISABLE COMMENT 'Vuelve a realizar el cierre del dia anterior por la mañana.' DO INSERT INTO `vn2008`.`Colas` (`Id_Informe`,`Cola`) VALUES ('2',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 */ ;;
/*!50106 DROP EVENT IF EXISTS `nightlyTaskChecker` */;;
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=`z-developer`@`%`*/ /*!50106 EVENT `nightlyTaskChecker` ON SCHEDULE EVERY 1 DAY STARTS '2018-09-26 04:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN 
DECLARE procedureIncorrect VARCHAR(50); 
SELECT CONCAT(`schema`,`procedure`) INTO procedureIncorrect FROM bs.nightTask WHERE date(finished) <> date(started); 
IF procedureIncorrect > '' THEN INSERT INTO vn2008.mail (`to`, subject, text) VALUES ('cau@verdnatura.es', 'error proceso nocturno', 
CONCAT('Ha fallado el procedimiento ', procedureIncorrect)); 

END IF; END */ ;;
/*!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 `raidUpdate` */;;
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 `raidUpdate` ON SCHEDULE EVERY 1 DAY STARTS '2017-12-29 00:05:00' ON COMPLETION PRESERVE ENABLE DO CALL raidUpdate */ ;;
/*!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 `__item_cache_cleaner` */;;
DELIMITER ;;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
/*!50003 SET character_set_client  = utf8mb4 */ ;;
/*!50003 SET character_set_results = utf8mb4 */ ;;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone      = @@time_zone */ ;;
/*!50003 SET time_zone             = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `__item_cache_cleaner` ON SCHEDULE EVERY 30 SECOND STARTS '2014-06-30 13:38:27' ON COMPLETION NOT PRESERVE DISABLE COMMENT 'Cleans the item cache' DO CALL item_cache_cleaner () */ ;;
/*!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 'vn2008'
--
/*!50003 DROP FUNCTION IF EXISTS `articod` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `articod`(intArt INT) RETURNS varchar(70) CHARSET utf8 COLLATE utf8_unicode_ci
BEGIN
	DECLARE strArt VARCHAR(70);
	SELECT CONCAT(Article,' ', Medida, ' ',Color) INTO strArt FROM Articles WHERE Id_Article = intArt;

	RETURN strArt;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `asiento` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `asiento`(
	v_asiento INT
	,v_date DATE
	,v_subaccount VARCHAR(12)
	,v_account VARCHAR(12)
	,v_concept VARCHAR(25)
	,v_debit DOUBLE
	,v_credit DOUBLE
	,v_euro DOUBLE
	,v_serial CHAR(1)
	,v_invoice VARCHAR(8)
	,v_vat DOUBLE
	,v_re DOUBLE
	,v_aux TINYINT
	,v_company INT
) RETURNS int(11)
BEGIN
	IF v_asiento IS NULL
	THEN
		SELECT MAX(ASIEN) + 1 INTO v_asiento FROM XDiario FOR UPDATE;
	END IF;

	INSERT INTO XDiario
	SET
		ASIEN = v_asiento
		,FECHA = v_date
		,SUBCTA = v_subaccount
		,CONTRA = v_account
		,CONCEPTO = v_concept
		,EURODEBE = v_debit
		,EUROHABER = v_credit
		,BASEEURO = v_euro
		,SERIE = v_serial
		,FACTURA = v_invoice
		,IVA = v_vat
		,RECEQUIV = v_re
		,AUXILIAR = IF(v_aux = FALSE, NULL, '*')
		,MONEDAUSO = 2
		,empresa_id = v_company;

	RETURN v_asiento;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `Averiguar_ComercialCliente` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `Averiguar_ComercialCliente`(v_customer INT, v_date DATE) RETURNS varchar(3) CHARSET utf8
    DETERMINISTIC
BEGIN
/**
 * Dado un id cliente y una fecha, devuelve su comercial.
 * Para más información ir a Averiguar_ComercialCliente_Id()
 *
 * @param v_customer El id del cliente
 * @param v_date Fecha a comprobar
 * @return El código del comercial para la fecha dada
 **/
    DECLARE v_employee CHAR(3);
    DECLARE v_salesperson INT;
    
    SET v_salesperson = Averiguar_ComercialCliente_Id(v_customer, v_date);

	SELECT CodigoTrabajador
		INTO v_employee
		FROM Trabajadores 
		WHERE Id_Trabajador = v_salesperson;

	RETURN IFNULL(v_employee, '---');
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `Averiguar_ComercialCliente_Id` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `Averiguar_ComercialCliente_Id`(v_customer INT, v_date DATE) RETURNS int(11)
    DETERMINISTIC
BEGIN
/**
 * Dado un id cliente y una fecha, devuelve su comercial para ese dia, teniendo 
 * en cuenta la jerarquía de las tablas: 1º la de sharingclient, 2º la de 
 * sharingcart y tercero la de clientes.
 *
 * @param v_customer El id del cliente
 * @param v_date Fecha a comprobar
 * @return El id del comercial para la fecha dada
 **/
	DECLARE v_salesperson INT DEFAULT NULL;
	DECLARE v_substitute INT DEFAULT NULL;
	DECLARE v_loop BOOLEAN;

	-- Obtiene el comercial original y el de sharingclient

	SELECT c.Id_Trabajador, s.Id_Trabajador
		INTO v_salesperson, v_substitute
		FROM Clientes c
			LEFT JOIN sharingclient s
				ON c.Id_Cliente = s.Id_Cliente
					AND v_date BETWEEN s.datSTART AND s.datEND
		WHERE c.Id_Cliente = v_customer
		ORDER BY s.id
        LIMIT 1;

	-- Si no hay ninguno en sharingclient busca en sharingcart

	IF v_substitute IS NOT NULL
	THEN
		SET v_salesperson = v_substitute;
	ELSEIF v_salesperson IS NOT NULL
	THEN
		DROP TEMPORARY TABLE IF EXISTS tmp.stack;
		CREATE TEMPORARY TABLE tmp.stack
			(INDEX (substitute))
			ENGINE = MEMORY
			SELECT v_salesperson substitute;

		l: LOOP
			SELECT Id_Suplente INTO v_substitute
				FROM sharingcart 
				WHERE v_date BETWEEN datSTART AND datEND
					AND Id_Trabajador = v_salesperson
				ORDER BY id
				LIMIT 1;
				
			IF v_substitute IS NULL THEN
				LEAVE l;
			END IF;
				
			SELECT COUNT(*) > 0 INTO v_loop
				FROM tmp.stack WHERE substitute = v_substitute;

			IF v_loop THEN
				LEAVE l;
			END IF;
			
			INSERT INTO tmp.stack SET
				substitute = v_substitute;
			
			SET v_salesperson = v_substitute;
		END LOOP;
		
		DROP TEMPORARY TABLE tmp.stack;
	END IF;

	RETURN v_salesperson;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `Averiguar_ComercialCliente_IdTicket` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `Averiguar_ComercialCliente_IdTicket`(v_ticket INT) RETURNS varchar(3) CHARSET utf8
    DETERMINISTIC
BEGIN
/**
 * Dado un id ticket, devuelve su comercial.
 * Para más información ir a Averiguar_ComercialCliente_Id()
 *
 * @param v_customer El id del cliente
 * @param v_date Fecha a comprobar
 * @return El código del comercial para la fecha dada
 **/
    DECLARE v_customer INT;
    DECLARE v_date DATE;
    
    SELECT id_cliente, fecha
		INTO v_customer, v_date
        FROM Tickets WHERE id_ticket = v_ticket;
        
	RETURN Averiguar_ComercialCliente(v_customer, v_date);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `Averiguar_ComercialCliente_IdTicket_Id` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `Averiguar_ComercialCliente_IdTicket_Id`(v_ticket INT) RETURNS int(11)
    DETERMINISTIC
BEGIN
/**
 * Dado un id ticket, devuelve su comercial.
 * Para más información ir a Averiguar_ComercialCliente_Id()
 *
 * @param v_customer El id del cliente
 * @param v_date Fecha a comprobar
 * @return El id del comercial para la fecha dada
 **/
    DECLARE v_customer INT;
    DECLARE v_date DATE;
    
    SELECT id_cliente, fecha
		INTO v_customer, v_date
        FROM Tickets WHERE id_ticket = v_ticket;
        
	RETURN Averiguar_ComercialCliente_Id(v_customer, v_date);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `Averiguar_Comprador` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `Averiguar_Comprador`(idARTICLE INT) RETURNS varchar(3) CHARSET utf8
BEGIN

-- Devuelve la abreviatura del comprador del articulo 

DECLARE buyer VARCHAR(3);

SELECT CodigoTrabajador INTO buyer 
FROM Trabajadores t
JOIN Tipos tp on tp.Id_Trabajador = t.Id_Trabajador
JOIN Articles a on a.tipo_id = tp.tipo_id
WHERE Id_Article = idARTICLE;


RETURN buyer;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `base_ticket` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `base_ticket`(Id_Ticket INT) RETURNS double
BEGIN

	DECLARE base DOUBLE;
	SELECT 
        red(SUM(Cantidad * Preu * (100 - Descuento) / 100)) into base
    FROm
        Movimientos m
		INNER JOIN Tickets t USING (Id_Ticket)
	WHERE t.Id_Ticket = Id_Ticket;

RETURN base;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `bionicCalcReverse` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `bionicCalcReverse`(vWarehouse INT,
    vMargin DECIMAL(10,3),
    vRetailedPrice DECIMAL(10,3),
    vM3 DECIMAL(10,3),
    vConsigna INT,
    vAgencia INT) RETURNS decimal(10,3)
BEGIN
	DECLARE COEFICIENTE_DE_INFLACION_GENERAL INT DEFAULT 1.3;
    DECLARE DENSIDAD_MINIMA_PESO_VOLUMETRICO INT DEFAULT 167;
    DECLARE VOLUMEN_CAJA_VERDNATURA BIGINT DEFAULT 138000;    
    DECLARE vCost DECIMAL(10,4) DEFAULT 0;
    DECLARE vCustomer INT;
    DECLARE vRecovery DECIMAL(10,4) DEFAULT 0;
	DECLARE vMana DECIMAL(10,4) DEFAULT 0;
    DECLARE vPort DECIMAL(10,4) DEFAULT 0;
    
    SELECT Id_Cliente INTO vCustomer FROM Consignatarios WHERE Id_Consigna = vConsigna;
      
   -- Recobro
	SELECT ROUND(LEAST(recobro,0.25), 3) INTO vRecovery
		FROM bi.claims_ratio
			WHERE Id_Cliente = vCustomer AND recobro > 0.009;
            
	-- Componente de maná automático, en función del maná acumulado por el comercial.
    SELECT ROUND(prices_modifier_rate, 3) INTO vMana
		FROM Clientes c 
		JOIN bs.mana_spellers ms ON c.Id_Trabajador = ms.Id_Trabajador 
		WHERE ms.prices_modifier_activated AND c.Id_Cliente = vCustomer;
 
	-- Reparto
	SELECT COEFICIENTE_DE_INFLACION_GENERAL
				* ROUND(
						vM3 
						* az.price 
						* az.inflacion 
						/ VOLUMEN_CAJA_VERDNATURA, 4
						) INTO vPort
    FROM vn2008.Agencias a 
        JOIN vn2008.Consignatarios c ON c.Id_Consigna = vConsigna AND a.Id_Agencia = vAgencia
		JOIN vn2008.Agencias_province ap ON ap.agency_id = a.agency_id AND ap.warehouse_id = vWarehouse AND ap.province_id = c.province_id
        JOIN vn2008.Agencias_zonas az ON az.Id_Agencia = vAgencia AND az.zona = ap.zona AND az.Id_Article = 71 AND az.warehouse_id = vWarehouse;
	
	-- Modificacion de precio por dia de preparacion del pedido
	-- No aplicada
    
    SET vCost = ((vRetailedPrice - vPort) / ( 1 + (vRecovery + vMana))) - vMargin;
    
    RETURN vCost;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `botanic_export_is_updatable` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `botanic_export_is_updatable`(v_edi_genus_id MEDIUMINT,v_edi_specie_id MEDIUMINT,v_id_Paises MEDIUMINT,v_restriction MEDIUMINT) RETURNS int(11)
BEGIN
	DECLARE is_updatable INTEGER;
	SELECT COUNT(*) INTO is_updatable FROM botanic_export 
		WHERE edi_genus_id = v_edi_genus_id 
			AND (v_edi_specie_id = edi_specie_id OR IFNULL(v_edi_specie_id,edi_specie_id) IS NULL)
            AND (v_id_Paises = Id_Paises OR IFNULL(v_id_Paises,Id_Paises) IS NULL)
            AND v_restriction = restriction;
RETURN is_updatable;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `buffer_name` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `buffer_name`(v_date DATE, v_wh INT) RETURNS varchar(11) CHARSET utf8
BEGIN
    RETURN CONCAT('b', YEAR(v_date), MONTH(v_date), DAY(v_date), IFNULL(v_wh, 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 `buyingAbsoluteCost` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `buyingAbsoluteCost`(vCompra BIGINT) RETURNS int(11)
BEGIN
/**
 * Devuelve el coste completo de una compra
 *
 * @param vCompra Id_Compra a calcular
 * @return Suma de los 4 componentes del coste
 */

DECLARE vCost DOUBLE;

SELECT IFNULL(Costefijo,0) + IFNULL(Portefijo,0) + IFNULL(Embalajefijo,0) + IFNULL(Comisionfija,0)
INTO vCost
FROM Compres
WHERE Id_Compra = vCompra;

RETURN vCost;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `cc_to_iban` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `cc_to_iban`(cc VARCHAR(20)) RETURNS varchar(4) CHARSET utf8
    DETERMINISTIC
BEGIN
	DECLARE iban VARCHAR(4);
	select
		CONCAT('ES',
			RIGHT(
				concat(0,
					98-
						mod(
							concat(
								mod(
									concat(
										mod(
											concat(
												mod(
													substring(cc,1,8),
													97),
												substring(cc,9,8)
											),
											97),
										substring(
											concat(
												cc,
												142800
											),
											17,
											8
										)
									),
								97),
								substring(
									concat(
										cc,
										142800
									),
									25,
									2
								)
							),
						97)
					)
			,2)
		)into iban;
RETURN iban;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `cm3` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = latin1 */ ;
/*!50003 SET character_set_results = latin1 */ ;
/*!50003 SET collation_connection  = latin1_swedish_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `cm3`(v_buy_id INT) RETURNS int(11)
BEGIN
  DECLARE id_CUB VARCHAR(10);
  DECLARE id_ART INT;
  SELECT Id_Cubo, Id_Article INTO id_CUB, id_ART
  FROM Compres c
  WHERE c.Id_compra = v_buy_id;

	RETURN cm3_2(id_CUB, id_ART);

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `cm3_2` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `cm3_2`(id_CUB VARCHAR(10), id_ART INT) RETURNS int(11)
BEGIN
	DECLARE v_cm3 INT;

	SELECT SUM(IF(b.Volumen > 0,
		b.Volumen,
		x * y * IF(z = 0, Medida + 10, z)
	)) INTO v_cm3
	  FROM Cubos b
		INNER JOIN Articles a ON Id_Article = id_ART
    WHERE Id_Cubo = id_CUB;
		
	RETURN v_cm3;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `cm3_unidad` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `cm3_unidad`(v_buy_id INT) RETURNS int(11)
BEGIN
  DECLARE id_CUB VARCHAR(10);
  DECLARE id_ART INT;
  DECLARE intPACK INT;
  
  SELECT Id_Cubo, Id_Article, Packing INTO id_CUB, id_ART, intPACK
  FROM Compres c
  WHERE c.Id_compra = v_buy_id;

	RETURN ifnull(round(cm3_2(id_CUB, id_ART)/intPACK),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 `code_to_id` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `code_to_id`(idART VARCHAR(22)) RETURNS int(11)
    DETERMINISTIC
BEGIN
	DECLARE idchecked INT;

	set idchecked = (SELECT Id_Article FROM barcodes WHERE code = idART);

	IF idchecked THEN
			RETURN idchecked;
	END IF;
	
	IF idART > 6000000 THEN
		SELECT Id_Article INTO idchecked
			FROM Compres WHERE Id_Compra = idART;
	ELSE
		SET idchecked = CAST(idART AS SIGNED);		
	END IF;

	RETURN idchecked;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `code_to_id2` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `code_to_id2`(idART VARCHAR(22)) RETURNS int(11)
BEGIN
	DECLARE idchecked INT;

	SELECT IFNULL(Id_Article,COUNT(*)) INTO idchecked 
		FROM barcodes 
		WHERE code = idART LIMIT 1;

	IF idchecked THEN
			RETURN idchecked;
	END IF;
	
	IF idART > 6000000 THEN
		/*SELECT Id_Article INTO idchecked
			FROM Compres WHERE Id_Compra = idART;*/
		SET idchecked = CAST(idART AS SIGNED);	
	ELSE
		SET idchecked = CAST(idART AS SIGNED);		
	END IF;

	RETURN idchecked;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `cub` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = latin1 */ ;
/*!50003 SET character_set_results = latin1 */ ;
/*!50003 SET collation_connection  = latin1_swedish_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `cub`(v_buy_id INT) RETURNS int(11)
BEGIN
	DECLARE v_cm3 INT;

	SELECT SUM(Etiquetas * IF(b.Volumen > 0,
		b.Volumen,
		IF(z = 0,
			x * y * (Medida + 10),
      x * y * z
		)
	)) INTO v_cm3
	FROM Compres c
		INNER JOIN Cubos b USING (Id_Cubo)
		INNER JOIN Articles a USING (Id_Article)
		WHERE c.Id_compra = v_buy_id;
		
	RETURN v_cm3;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `currate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `currate`() RETURNS double
BEGIN

DECLARE dblRATE DOUBLE;

SELECT rate INTO dblRATE FROM reference_rate ORDER BY date DESC LIMIT 1 ;

RETURN dblRATE;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `date_inv` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = latin1 */ ;
/*!50003 SET character_set_results = latin1 */ ;
/*!50003 SET collation_connection  = latin1_swedish_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `date_inv`() RETURNS datetime
    DETERMINISTIC
BEGIN
	RETURN (SELECT FechaInventario FROM tblContadores 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 FUNCTION IF EXISTS `DAYEND` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `DAYEND`(v_date DATE) RETURNS datetime
    DETERMINISTIC
BEGIN
  RETURN TIMESTAMP(v_date,'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 */ ;
/*!50003 DROP FUNCTION IF EXISTS `FIRSTDAYOFYEAR` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `FIRSTDAYOFYEAR`(datFEC DATE) RETURNS date
BEGIN

DECLARE datRETURNS DATE;

SELECT TIMESTAMPADD(DAY, -1 * DAYOFYEAR(datFEC) + 1, datFEC) INTO datRETURNS;

RETURN datRETURNS;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `f_periodo` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `f_periodo`(datFEC date) RETURNS int(7)
    DETERMINISTIC
BEGIN
DECLARE intPeriod INT;

SELECT Year(datFEC) * 100 + week(datFEC) into intPeriod;

RETURN intPeriod;




END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `getBouquetId` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `getBouquetId`(
	vName VARCHAR(50), 
	vType int, 
	vSize int, 
	vColour VARCHAR(5)
) RETURNS int(11)
BEGIN
/**
 * De vuelve el ID del ramo. Si no existe uno parecido, lo crea.
 *
 * @param vName Nombre del artículo
 * @param vType Tipo de flor/planta
 * @param vSize Tamaño del ramo
 * @param vColour Color del ramo
 * @return ID del ramo
 */
	DECLARE bouquetId INT(11);
    
	CALL vn2008.createBouquet(vName, vType, vSize, vColour, @vItem);
    
    SET bouquetId = (SELECT @vItem);
    
RETURN bouquetId;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `getInvoiceWeight` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `getInvoiceWeight`(vInvoice VARCHAR(15)) RETURNS decimal(10,2)
BEGIN
	DECLARE vTotalWeight DECIMAL(10,2);
    /*
	SELECT SUM(IFNULL(tallos,1) * Cantidad * a.density) sumTotal
		INTO vTotalWeight FROM Tickets t
				LEFT JOIN Movimientos m ON m.Id_Ticket = t.Id_Ticket
				LEFT JOIN Articles a ON a.Id_Article = m.Id_Article
                LEFT JOIN bi.rotacion r ON t.
				WHERE t.Factura = vInvoice AND Codintrastat;
                
     */
	SELECT SUM(IFNULL(i.stems,1) * s.quantity * i.density * r.cm3)  / 1000000
		INTO vTotalWeight
        FROM vn.ticket t
			JOIN vn.sale s ON s.ticketFk = t.id
            JOIN vn.item i ON i.id = s.itemFk
            JOIN bi.rotacion r ON r.Id_Article = i.id AND r.warehouse_id = t.warehouseFk
            WHERE t.refFk = vInvoice AND i.intrastatFk ;    
                
                
	RETURN vTotalWeight;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `getShippingFromTicket` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `getShippingFromTicket`(vTicket INTEGER) RETURNS decimal(10,2)
BEGIN
	DECLARE vValue DECIMAL(10,2);
	SELECT 
		SUM(Valor * m.Cantidad) INTO vValue
	FROM
		Movimientos_componentes mc
			JOIN
		Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento
			JOIN
		bi.tarifa_componentes tc ON mc.Id_Componente = tc.Id_Componente
		JOIN
		bi.tarifa_componentes_series tcs ON tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id 
				AND tcs.tarifa_componentes_series_id = 6
		
	WHERE m.Id_Ticket =  vTicket;
    
	RETURN vValue;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `get_special_price` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `get_special_price`(intArticle int(11),intCliente int(11)) RETURNS decimal(10,2)
BEGIN
	DECLARE price DECIMAL(10,2);

	SELECT rate_3 INTO price FROM price_fixed WHERE item_id = intArticle AND CURDATE() BETWEEN date_start AND date_end order by odbc_date DESC limit 1;
    
    SELECT precioespecial INTO price FROM PreciosEspeciales WHERE Id_Article =  intArticle and Id_Cliente = intCliente ;
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 `get_Trabajador` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `get_Trabajador`() RETURNS int(11)
    DETERMINISTIC
BEGIN
	RETURN IFNULL((SELECT Id_Trabajador FROM Trabajadores WHERE user_id = account.userGetId()),20);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `has_notify_passport` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `has_notify_passport`(vItemFk INT, vBuyFk INT) RETURNS tinyint(1)
    READS SQL DATA
BEGIN
	DECLARE vHasPassport BOOL;
	DECLARE vIsAlreadySent BOOL;

	SELECT COUNT(*) INTO vHasPassport
		FROM botanic_export be
            JOIN Articles_botanical ab
				ON be.edi_genus_id = ab.genus_id
					AND IFNULL(be.edi_specie_id, ab.specie_id) = ab.specie_id
					AND be.restriction = 'pasaporte fitosanitario'
			JOIN Articles a ON a.Id_Article = ab.Id_Article
			JOIN Tipos t ON t.tipo_id = a.tipo_id
		WHERE ab.Id_Article = vItemFk
			AND t.reino_id = 2;

	IF vHasPassport THEN
		SELECT COUNT(*) INTO vIsAlreadySent
			FROM mail m
				JOIN Compres c ON c.Id_Compra = vBuyFk
			WHERE m.`text` LIKE CONCAT('%', c.buy_edi_id, '%')
            LIMIT 1;
	END IF;

	RETURN vHasPassport AND NOT vIsAlreadySent;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `intrastat_neto` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `intrastat_neto`( intINSTRASTAT INTEGER,intUNIDADES INTEGER) RETURNS double
BEGIN

DECLARE n DOUBLE;

select ROUND(intUNIDADES / (sum(MEDIA) / count(media)),2) into n from (
select *, unidades / neto MEDIA FROM intrastat_data WHERE intrastat_id = intINSTRASTAT and neto and unidades > 0 ORDER BY odbc_date DESC limit 50) t;
-- JGF 01/06 per a evitar Kg en negatiu
RETURN n/2;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `is_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`@`%` FUNCTION `is_bionic`(intTicket INT) RETURNS tinyint(1)
BEGIN
	DECLARE bolIsBionic boolean;
	SELECT (COUNT(*) > 0) INTO bolIsBionic FROM order_Tickets ot
		WHERE ot.Id_Ticket = intTicket;
	RETURN bolIsBionic;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `lang` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `lang`() RETURNS char(2) CHARSET utf8
    DETERMINISTIC
BEGIN
	RETURN IFNULL(@lang, 'es');
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `next_venc` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `next_venc`( datFecha DATE,intDia INT,intPayDay INT) RETURNS date
BEGIN

DECLARE n DATE;
DECLARE datVenc DATE;
DECLARE intVenc INT;

    SELECT TIMESTAMPADD(DAY,intDia,datFecha) INTO datVenc;
    SELECT DAY(datVenc) INTO intVenc;
    
    SELECT MIN(TIMESTAMPADD(MONTH,(intVenc > intPayDay),DATE_FORMAT(datVenc,CONCAT('%y/%m/',intPayDay)))) INTO n;
RETURN n;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `next_venctesting` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `next_venctesting`( datFecha DATE,intDia INT,intPayDay INT) RETURNS date
BEGIN

DECLARE n DATE;
DECLARE datVenc DATE;
DECLARE intVenc INT;

    SELECT TIMESTAMPADD(DAY,intDia,datFecha) INTO datVenc;
    SELECT DAY(datVenc) INTO intVenc;
    
    SELECT IFNULL
			(
				TIMESTAMPADD
                (
					MONTH,
					(intVenc > intPayDay),
					DATE_FORMAT
                    (
						datVenc,
						CONCAT('%y/%m/',intPayDay)
					)
				),
				LAST_DAY(datVenc)
			) INTO n;
RETURN n;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `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
    DETERMINISTIC
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 FUNCTION IF EXISTS `paymentday` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `paymentday`(vDated DATE, vDayToPay INT) RETURNS date
BEGIN
/* OBSOLETO usar vn.getDueDate(vDated DATE, vDayToPay INT)*/
DECLARE vDued DATE;

SET vDued = vn.getDueDate(vDated, vDayToPay);

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 */ ;
/*!50003 DROP FUNCTION IF EXISTS `periodo` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `periodo`(datFEC DATETIME) RETURNS int(6)
    DETERMINISTIC
BEGIN

DECLARE intPERIODO INt;

SET intPERIODO = YEAR(datFEC) * 100 + MONTH(datFEC);

RETURN intPERIODO;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `periodo_day` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `periodo_day`(datFEC DATETIME) RETURNS int(8)
    DETERMINISTIC
BEGIN

DECLARE intPERIODO INt;

SET intPERIODO = YEAR(datFEC) * 10000 + MONTH(datFEC) * 100 + DAY(datFEC);

RETURN intPERIODO;

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

	
	DECLARE dblprice DOUBLE;
	SELECT 
       SUM(`az`.`price`) INTO dblprice
    FROM
        (((((`expeditions` `e`
        JOIN `Tickets` `t` ON ((`e`.`ticket_id` = `t`.`Id_Ticket`)))
        JOIN `Consignatarios` `c` ON ((`c`.`Id_Consigna` = `t`.`Id_Consigna`)))
        JOIN `Agencias` `a` ON ((`a`.`Id_Agencia` = `t`.`Id_Agencia`)))
        JOIN `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 `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` >= '2015-10-01')
            AND (`t`.`empresa_id` IN (442 , 791))) AND t.Id_Ticket = intId_Ticket
    GROUP BY `t`.`Id_Ticket`;
    
	RETURN dblprice;

/*
	DECLARE intId_Agencia INT;
	DECLARE int_agency_id SMALLINT;
	DECLARE int_province_id SMALLINT;
	DECLARE bolCOD71 TINYINT(1);
	DECLARE intPorte DOUBLE DEFAULT -1;
	DECLARE dayofweek TINYINT(1) default 0;
	DECLARE suplemento DOUBLE DEFAULT 9.41;
	DECLARE strCodPostal VARCHAR(5);
	DECLARE intWarehouse_id SMALLINT;
	DECLARE dbldescuento DOUBLE DEFAULT 0;
	DECLARE intVista TINYINT(1);
	DECLARE dblvolumen DOUBLE;

	SET @porte := 0;
	SELECT a.agency_id, t.Id_Agencia, cod71, Porte,c.CODPOSTAL,t.warehouse_id,c.province_id,cli.Descuento,IFNULL(ag.Vista,a.Vista), por_volumen
		INTO int_agency_id,intId_Agencia, bolCOD71,intPorte,strCodPostal,intWarehouse_id,int_province_id,dbldescuento,intVista,dblvolumen
		FROM Tickets t 
			JOIN  Consignatarios c USING(Id_Consigna)
			JOIN Agencias a ON t.Id_Agencia = a.Id_Agencia
			JOIN agency agn ON agn.agency_id = a.agency_id
			JOIN Clientes cli on c.Id_Cliente=cli.Id_Cliente
			LEFT JOIN agency_warehouse ag ON ag.agency_id = a.agency_id
	WHERE Id_Ticket = intId_Ticket limit 1;

	

		
			IF bolCOD71 THEN
				
					IF intId_Agencia = 47 THEN -- Si es viaxpress
						SELECT price INTO dblprice FROM Agencias_zonas az INNER JOIN viaxpress USING(zona) 
						WHERE Id_Agencia = 47 AND codigo_postal = strCodPostal AND az.warehouse_id = intWarehouse_id;
					ELSE
						SELECT price INTO dblprice FROM Agencias_zonas az
							WHERE Id_Agencia = intId_Agencia AND 71 = Id_Article AND az.warehouse_id = intWarehouse_id
								AND zona = (SELECT zona FROM Agencias_province
											WHERE warehouse_id = intWarehouse_id AND agency_id = int_agency_id and province_id = int_province_id);
					END IF;
				
			ELSE
				SELECT 0 INTO dblprice;
			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 FUNCTION IF EXISTS `red` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `red`( intCANTIDAD DOUBLE) RETURNS double
    DETERMINISTIC
BEGIN

	DECLARE n DOUBLE;

	SET n = SIGN(intCANTIDAD) * TRUNCATE(   (ABS(intCANTIDAD) * 100)   +  0.5001        ,0)           /100 ;

	RETURN n;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `semana` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `semana`(datFec DATETIME) RETURNS int(11)
    DETERMINISTIC
BEGIN
   /* DECLARE intWeek TINYINT DEFAULT WEEK(datFec, 1);
    DECLARE intYear SMALLINT DEFAULT YEAR(datFec);


-- La funcio week dona un error en els primers dies del any
-- Por convención, consideraremos que el año tiene siempre 52 semanas, y la 53 se incorpora a la 1 del año siguiente.
-- Mysql week function smells, so ...

    IF intWeek > 52 THEN

		SET intWeek = 1;

		IF MONTH(datFec) = 12 THEN 
         
			SET intYear = intYear + 1;
	
        SET intWeek = 1; 
    
		
		END IF;

	END IF;

    RETURN intYear * 100 + intWeek;
*/

   RETURN vnperiod(datFec);


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `shipmentDay` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `shipmentDay`(landingDay INT, intervalDays INT) RETURNS int(11)
BEGIN

/*  PAK 01/09/16
*
*   Devuelve el weekday resultante de restar al landingDay los dias de intervalDays
*
*/

DECLARE resultDay INT;

SET resultDay = (landingDay + 7 - (intervalDays mod 7)) mod 7;

RETURN resultDay;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `ticket_freight` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticket_freight`(idT INT) RETURNS decimal(10,3)
BEGIN

	DECLARE dblFreight DECIMAL(10,2);

	/*
	DECLARE intWh INTEGER;
	DECLARE datFecha DATE;
	
    
	SELECT warehouse_id, Fecha INTO intWh,datFecha FROM Tickets WHERE Id_Ticket = idT;
    
    
	CALL item_last_buy_(intWh,datFecha);

	SELECT SUM((`M`.`Cantidad` * (CM3(`b`.`buy_id`) / 1000000 /`C`.`Packing`) * `az`.`price` / 0.08)) INTO dblFreight
			FROM Movimientos M
				JOIN t_item_last_buy b on M.Id_Article = b.item_id
				JOIN Compres C ON C.Id_Compra = b.buy_id
				JOIN Tickets t on t.Id_Ticket = M.Id_Ticket
                JOIN `Consignatarios` `cn` ON (`cn`.`Id_Consigna` = `t`.`Id_Consigna`)
				JOIN `Agencias` `a` ON (`a`.`Id_Agencia` = `t`.`Id_Agencia`)
				JOIN `Agencias_province` `ap` ON (`t`.`warehouse_id` = `ap`.`warehouse_id`)
					AND (`ap`.`province_id` = `cn`.`province_id`)
					AND (`ap`.`agency_id` = `a`.`agency_id`)
				JOIN `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)
					WHERE M.Id_Ticket = idT;
    
	DROP TEMPORARY TABLE t_item_last_buy;
	*/
    
    SELECT sum(freight) 
			INTO dblFreight
		FROM v_Movimientos_Volumen_shipping_charge 
		WHERE Id_Ticket = idT;
    
    RETURN dblFreight;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `ticket_state` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `ticket_state`(
                                                         strFAC VARCHAR(15),
                                                         intIMP TINYINT(1),
                                                         intETI TINYINT(1),
                                                         intBLO TINYINT(1)

                                                  ) RETURNS varchar(15) CHARSET utf8
BEGIN
CASE

    WHEN strFAC IS NOT NULL AND strFAC != '' THEN RETURN 'FACTURADO';

    WHEN intETI <> 0 THEN RETURN 'ALBARAN';

    WHEN intIMP <> 0 THEN RETURN 'PREPARACION';

    WHEN intBLO <> 0 THEN RETURN 'BLOQUEADO';

    ELSE RETURN 'LIBRE';

END CASE;





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

                                                  ) RETURNS varchar(15) CHARSET utf8
BEGIN

DECLARE strVAR VARCHAR(15);


SELECT ticket_state(Factura, PedidoImpreso, Etiquetasemitidas, Blocked)
INTO strVAR
FROM Tickets
WHERE Id_Ticket = idTICKET;



RETURN strVAR;



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

                                                  ) RETURNS varchar(15) CHARSET utf8
BEGIN

DECLARE strVAR VARCHAR(15);
DECLARE strNAM VARCHAR(15);
DECLARE fltID FLOAT DEFAULT 0;
DECLARE strfac VARCHAR(15);
DECLARE inteti tinyint;
DECLARE intimp tinyint;
DECLARE intblk tinyint;

SELECT s.`name`,id INTO strNAM,fltID
	FROM Tickets t INNER JOIN vncontrol.inter i USING(Id_Ticket)
		INNER JOIN state s ON s.id = i.state_id 
	WHERE Id_Ticket = idTICKET ORDER BY i.odbc_date DESC,i.state_id DESC LIMIT 1;

SELECT Factura, PedidoImpreso, Etiquetasemitidas, Blocked
		INTO strfac,intimp,inteti,intblk
	FROM Tickets
	WHERE Id_Ticket = idTICKET;

CASE


    WHEN strfac <> '' AND fltID < 11 THEN RETURN 'FACTURADO';

	WHEN inteti <> 0 AND fltID < 11 THEN RETURN 'ALBARAN' ;

    WHEN intimp <> 0 AND fltID <= 5 THEN RETURN 'EN PREPARACION';

    WHEN fltID > 0 THEN RETURN strNAM;

	ELSE RETURN 'LIBRE';

END CASE;


RETURN strVAR;



END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `ticket_volumen` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticket_volumen`(idT INT) RETURNS decimal(10,3)
    READS SQL DATA
BEGIN
	-- OBSOLETA USAR vn.ticketTotalVolumen JGF 2018-05-22
	-- DECLARE intWh INTEGER;
	-- DECLARE datFecha DATE;
	DECLARE dblVolume DECIMAL(10,3);
    
    /*
	SELECT warehouse_id, Fecha
    INTO intWh,datFecha
    FROM Tickets 
    WHERE Id_Ticket = idT;
    
    SELECT IFNULL(SUM(m.Cantidad * cm3)/1000000,0) INTO dblVolume
    FROM Movimientos m
    JOIN bi.rotacion r on r.Id_Article = m.Id_Article AND r.warehouse_id = intWh
    WHERE m.Id_Ticket = idT;
    */
    
    SELECT sum(volume) INTO dblVolume
		FROM vn2008.v_Movimientos_Volumen_shipping_charge
        WHERE Id_Ticket = idT;
        
    RETURN dblVolume;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `ticket_volumen_encajado` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticket_volumen_encajado`(idT INT) RETURNS decimal(10,1)
    READS SQL DATA
BEGIN

/* Devuelve el volumen estimado de un pedido, en cajas
*
*	idT Numero de ticket
*	
*/


	DECLARE vVolumenCajaM3 DOUBLE;
    DECLARE vTicketVolumenEnCajas DECIMAL(10,1);
    DECLARE CAJA VARCHAR(10) DEFAULT '94';
    
    SELECT Volumen/1000000 INTO vVolumenCajaM3 FROM Cubos WHERE Id_Cubo = CAJA;
    
    SELECT SUM(volume)/vVolumenCajaM3 INTO vTicketVolumenEnCajas
		FROM vn2008.v_Movimientos_Volumen_shipping_charge
			WHERE Id_Ticket = idT;
    
    -- SET vTicketVolumenEnCajas = ticket_volumen(idT) / vVolumenCajaM3;
    
    RETURN vTicketVolumenEnCajas;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `till_entry` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `till_entry`(
	 v_customer INT
	,v_bank INT
	,v_amount DOUBLE
	,v_concept VARCHAR(25)
	,v_date DATE
	,v_serial CHAR(1)
	,v_batch TINYINT
	,v_number INT
	,v_company SMALLINT
	,v_employee INT
) RETURNS int(11)
BEGIN
	DECLARE v_account VARCHAR(12);
	DECLARE v_subaccount VARCHAR(12);
	DECLARE v_asiento INT DEFAULT NULL;

	-- Inserta el registro en cajas

	INSERT INTO Cajas
	SET
		Id_Trabajador = v_employee
		,Id_Banco = v_bank
		,Entrada = v_amount
		,Concepto = v_concept
		,Cajafecha = v_date
		,Serie = v_serial
		,Partida = v_batch
		,Numero = v_number
		,empresa_id = v_company;

	-- Inserta los asientos contables

	SELECT Cuenta INTO v_account
		FROM Bancos WHERE Id_Banco = v_bank;

	SELECT Cuenta INTO v_subaccount
		FROM Clientes WHERE Id_Cliente = v_customer;

	SET v_asiento = asiento
	(
		v_asiento
		,v_date
		,v_account
		,v_subaccount
		,v_concept
		,v_amount
		,0
		,0
		,NULL -- Serie
		,NULL -- Factura
		,NULL -- IVA
		,NULL -- Recargo
		,FALSE -- Auxiliar
		,v_company
	);
	DO asiento
	(
		v_asiento
		,v_date
		,v_subaccount
		,v_account
		,v_concept
		,0
		,v_amount
		,0
		,NULL -- Serie
		,NULL -- Factura
		,NULL -- IVA
		,NULL -- Recargo
		,FALSE -- Auxiliar
		,v_company
	);

	RETURN 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 FUNCTION IF EXISTS `to_weeks` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `to_weeks`(v_date DATE) RETURNS int(11)
    DETERMINISTIC
BEGIN
    RETURN FLOOR((TO_DAYS(v_date) - 366) / 7);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `ubicator_cabecaja` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `ubicator_cabecaja`(x SMALLINT,y SMALLINT,z SMALLINT,w SMALLINT,d SMALLINT,h SMALLINT) RETURNS tinyint(1)
BEGIN

IF ((y>d) OR (x>w) OR (z>h)) THEN -- si no cabe alguna de las medidas en la balda.
        RETURN FALSE;
END IF;
RETURN 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 FUNCTION IF EXISTS `vnday` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `vnday`(datfec DATE) RETURNS int(11)
    DETERMINISTIC
BEGIN

DECLARE intper INT;

SELECT day INTO intper FROM time WHERE date = datfec;

RETURN intper;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `vndayname` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `vndayname`(datfec DATE) RETURNS varchar(10) CHARSET utf8 COLLATE utf8_unicode_ci
    DETERMINISTIC
BEGIN

DECLARE vDayName VARCHAR(10);

CASE weekday(datfec)

	WHEN 6 then
		SET vDayName = 'Domingo';

	WHEN 0  then
		SET vDayName = 'Lunes';

	WHEN 1 then
		SET vDayName = 'Martes';

	WHEN 2 then
		SET vDayName = 'Miercoles';

	WHEN 3 then
		SET vDayName = 'Jueves';

	WHEN 4  then
		SET vDayName = 'Viernes';

	WHEN 5 then
		SET vDayName = 'Sabado';

END CASE;

RETURN vDayName;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `vnmonth` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `vnmonth`(datfec DATE) RETURNS int(11)
    DETERMINISTIC
BEGIN

DECLARE intper INT;

SELECT month INTO intper FROM time WHERE date = datfec;

RETURN intper;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `vnperiod` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `vnperiod`(datfec DATE) RETURNS int(6)
    DETERMINISTIC
BEGIN

DECLARE intper INT;

SELECT period INTO intper FROM time WHERE date = datfec;

RETURN intper;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `vntrimestre` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `vntrimestre`(datfec DATE) RETURNS int(11)
    DETERMINISTIC
BEGIN

	CASE 
		WHEN MONTH(datfec)<=3 THEN RETURN 1;
		WHEN MONTH(datfec)<=6 THEN RETURN 2;
		WHEN MONTH(datfec)<=9 THEN RETURN 3;
		ELSE return 4;
	END CASE;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `vnweek` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `vnweek`(datfec DATE) RETURNS int(11)
    DETERMINISTIC
BEGIN

DECLARE intper INT;

SELECT week INTO intper FROM time WHERE date = datfec;

RETURN intper;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `vnyear` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `vnyear`(datfec DATE) RETURNS int(11)
    DETERMINISTIC
BEGIN

DECLARE intper INT;

SELECT year INTO intper FROM time WHERE date = datfec;

RETURN intper;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `__AltaEmpleado` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `__AltaEmpleado`(strCodTrabajador varchar(3),strNombre varchar(50),strApellidos varchar(50),strDni varchar(9),
							    strDomicilio longtext,strCodPostal varchar(5),strPoblacion varchar(25),provinceId smallint(5), intempresa_id smallint(5),strMovil varchar(11)) RETURNS varchar(50) CHARSET utf8
BEGIN

DECLARE RETORNO varchar(50) DEFAULT 'Empleado creado CORRECTAMENTE';
DECLARE tmpUserId INT(11) DEFAULT 0;
DECLARE intId_Cliente int(11) DEFAULT 0;
DECLARE Cod_Trabajador VARCHAR(8) DEFAULT strCodTrabajador;
DECLARE strPassword VARCHAR(50);
DECLARE strSambaNombre VARCHAR(30);

samba:BEGIN
	
proc:BEGIN 
	-- IF (boolCrearSamba) THEN
	-- SELECT Id_Cliente_Interno INTO intId_Cliente FROM Trabajadores WHERE Nombre=strNombre and Apellidos=strApellidos;
	-- SELECT CONCAT(IF(INSTR(StrApellidos,' ')=0,StrApellidos,LEFT(strApellidos,INSTR(StrApellidos,' ')-1)),'.',intId_Cliente) INTO strPassword; 
	-- LEAVE proc;
	-- END IF;
-- Tabla Clientes
SELECT COUNT(*) INTO intId_Cliente FROM Clientes WHERE `IF`=strDni;
IF (intId_Cliente=0) THEN
	-- SELECT IFNULL(province_id,1) INTO intprovince_id FROM province WHERE `name`=strProvincia;
	SELECT MAX(Id_Cliente)+1 INTO intId_Cliente FROM Clientes WHERE Id_Cliente<999999;

	INSERT INTO Clientes (Id_Cliente,Cliente,Domicilio,`IF`,Telefono,province_id,Poblacion,CodPostal,RazonSocial,Contacto,Oficial,Descuento)
	SELECT intId_Cliente,Concat('TR ',strNombre,' ',StrApellidos),strDomicilio,strDni,strMovil,provinceId,strPoblacion,strCodPostal,
		   CONCAT(strApellidos,' ',strNombre),strNombre,1,3;
ELSE
	SELECT  id_cliente INTO intId_Cliente FROM Clientes WHERE `IF`=strDni;
END IF;

SELECT CONCAT(IF(INSTR(StrApellidos,' ')=0,StrApellidos,LEFT(strApellidos,INSTR(StrApellidos,' ')-1)),'.',intId_Cliente) INTO strPassword; 

-- Tabla Trabajadores
IF (SELECT COUNT(*) FROM Trabajadores WHERE Nombre=strNombre AND Apellidos=strApellidos)=0 THEN
	
    IF strCodTrabajador IS NULL THEN
		SET Cod_Trabajador = CONCAT(LEFT(strNombre, 1), LEFT(strApellidos, 1), MID(strApellidos, (LOCATE(' ',  strApellidos) + 1), 1));
    END IF;
    
	IF (SELECT COUNT(*) FROM Trabajadores WHERE CodigoTrabajador=Cod_Trabajador) > 0 THEN
		SET Cod_Trabajador = CONCAT(Cod_Trabajador, (FLOOR(RAND() * 100)));
	END IF;

	SELECT CONCAT(IF(INSTR(StrApellidos,' ')=0,StrApellidos,LEFT(strApellidos,INSTR(StrApellidos,' ')-1)),'.',intId_Cliente) INTO strPassword; 

	INSERT INTO Trabajadores (CodigoTrabajador,Nombre,Apellidos,`Password`,dni,empresa_id,id_Cliente_Interno) 
	SELECT Cod_Trabajador,strNombre,strApellidos,LCASE(strPassword),strDni,intempresa_id,intId_Cliente;
ELSE
	SET RETORNO="CodigoTrabajador Existente";
END IF;
	-- LEAVE SAMBA;
END; -- PROC

-- Tabla Account, lo crea como usuario y en samba
-- Obtengo el nombre sin espacios 
SET strSambaNombre = REPLACE(strNombre,' ','');
IF (SELECT COUNT(*) FROM account.user WHERE `name`=convert(strNombre USING utf8) COLLATE utf8_general_ci)>0 THEN -- Si existe cojo la inicial del nombre+1º apellido
	SELECT CONCAT(LEFT(strNombre,1),CONCAT(IF(INSTR(StrApellidos,' ')=0,StrApellidos,LEFT(strApellidos,INSTR(StrApellidos,' ')-1)),intId_Cliente))
	INTO strSambaNombre;
END IF;

	IF (SELECT COUNT(*) FROM account.user where id=intId_Cliente)=0 THEN
		INSERT INTO account.user (id,role,`name`,`password`,active) VALUES (intId_Cliente,1,lcase(strSambaNombre),MD5(LCASE(strPassword)),1);
        INSERT INTO account.account (id,lastchange,`expire`,user_id) values  (intId_Cliente,CURRENT_DATE(),CURRENT_DATE(),intId_Cliente);
        UPDATE Trabajadores SET user_id=intId_Cliente WHERE Id_Cliente_Interno=intId_Cliente;
	ELSE
	    INSERT INTO account.user (role,`name`,`password`,active) VALUES (1,lcase(strSambaNombre),MD5(LCASE(strPassword)),1);
        SET tmpUserId = LAST_INSERT_ID();
        INSERT INTO account.account (id,lastchange,`expire`,user_id) values  (tmpUserId,CURRENT_DATE(),CURRENT_DATE(),tmpUserId);
		UPDATE Trabajadores SET user_id=tmpUserId WHERE Id_Cliente_Interno=intId_Cliente;
	END IF;

    REPLACE INTO account.mailAliasAccount(mailAlias, account) VALUES (48,intId_Cliente);
	
END; -- samba

RETURN RETORNO;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `__getComision` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `__getComision`(vEntry INT, vMoneda INT) RETURNS int(11)
    READS SQL DATA
BEGIN
	DECLARE vComision INT;

	SELECT IFNULL(ROUND(-100 * (1 - (1 / rm.rate))), 0) INTO vComision
		FROM Entradas e
			JOIN travel tr ON tr.id = e.travel_id
			LEFT JOIN reference_min rm
				ON rm.moneda_id = vMoneda AND tr.shipment >= rm.`date`
		WHERE e.Id_Entrada = vEntry
		ORDER BY rm.date DESC
		LIMIT 1;

	RETURN IFNULL(vComision, 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 `account_conciliacion_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 `account_conciliacion_add`()
BEGIN
	DECLARE vIsEuroBank BOOLEAN DEFAULT 1;
    
	UPDATE account_conciliacion ac
		JOIN
		(
			SELECT idaccount_conciliacion, @c:= if(@id = id_calculated, @c + 1, 1) contador, 
					@id:= id_calculated as id_calculated, concat(id_calculated,'(',@c,')') as new_id   
			   FROM account_conciliacion
			JOIN
				(
				select id_calculated, count(*) rep, @c:= 0, @id:= concat('-',id_calculated) from account_conciliacion
				group by id_calculated
				having rep > 1
				) sub using(id_calculated)
		) sub2 using(idaccount_conciliacion)
	SET ac.id_calculated = sub2.new_id;

	SELECT currencyFk = 1 INTO vIsEuroBank 
		FROM vn.bank b 
			JOIN Proveedores_account pa ON pa.Id_Banco = b.id
			JOIN vn2008.account_conciliacion a ON a.Id_Proveedores_account = pa.Id_Proveedores_account
		LIMIT 1;
            
	INSERT INTO Cajas(Cajafecha, Partida, Serie, Concepto, Entrada, 
					Salida, Id_Banco,empresa_id, warehouse_id,
                    Proveedores_account_id, id_calculated, InForeignValue, OutForeignValue)
		SELECT Fechaoperacion, TRUE, 'MB', ac.Concepto, IF(DebeHaber = 2 AND vIsEuroBank, importe,null), 
				IF(DebeHaber = 1 AND vIsEuroBank, importe, null), pa.Id_Banco, pa.Id_Proveedor, 1,
                ac.Id_Proveedores_account, ac.id_calculated, IF(DebeHaber = 2 AND NOT vIsEuroBank, importe, null),
                IF(DebeHaber = 1 AND NOT vIsEuroBank, importe, null)
			FROM account_conciliacion ac
				JOIN Proveedores_account pa on pa.Id_Proveedores_account = ac.Id_Proveedores_account
				LEFT JOIN Cajas c on c.id_calculated = ac.id_calculated
			WHERE c.Id_Caja 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 `accumulatorsReadingDateUpdate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `accumulatorsReadingDateUpdate`()
BEGIN

/*	Actualiza los valores de la tabla en función de la cotización del EUR/USD
*
*/

UPDATE accumulatorsReadingDate a
	JOIN
		(
		SELECT 
				d.id,
				CASE 
					WHEN rr.rate between p.lowerBarrier and p.rate THEN p.strike
					WHEN rr.rate between p.rate and p.upperBarrier AND p.financialProductTypefk = 'AC' THEN p.strike
					WHEN rr.rate >= p.upperBarrier THEN p.strike * 2
					ELSE 0
				END AS Acumulado
			FROM vn2008.reference_rate rr
				JOIN accumulatorsReadingDate d ON d.readingDate = rr.date
				JOIN pago_sdc p ON p.pago_sdc_id = d.pagoSdcfk
			WHERE IFNULL(amount,0) = 0
            AND rr.date < CURDATE()
			AND rr.rate >= p.lowerBarrier) sub ON sub.id = a.id
            
		SET a.amount = sub.Acumulado
		WHERE a.amount 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 `add_awb_component` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `add_awb_component`(IN v_awb SMALLINT)
BEGIN

	DECLARE vShipment DATE;
	SELECT tr.shipped INTO vShipment 
		FROM vn.travel tr
			JOIN vn.entry e ON e.travelFk = tr.id
			JOIN vn.duaEntry de ON de.entryFk = e.id
            JOIN vn.dua d ON d.id = de.duaFk
		WHERE awbFk = v_awb limit 1;
                    
	INSERT IGNORE INTO awb_component (awb_id,Id_Proveedor,awb_component_type_id,awb_role_id,awb_unit_id,value,Id_Moneda) 
		SELECT id,Id_Proveedor,awb_component_type_id,awb_role_id,awb_unit_id,LEAST(GREATEST(value1,IFNULL(min_value,value1)),IFNULL(max_value,value1)),Id_Moneda
        FROM (
			SELECT a.id,IFNULL(act.carguera_id,CASE awb_role_id WHEN 1 THEN a.carguera_id WHEN 2 THEN a.transitario_id WHEN 3 THEN f.airline_id END) Id_Proveedor, 
			act.awb_component_type_id,act.awb_role_id,act.awb_unit_id, value *
			CASE awb_unit_id
				WHEN '1000Tj-20' THEN ((CAST(stems AS SIGNED) - 20000)/1000) + (min_value / value)
                WHEN '1000Tj-10' THEN ((CAST(stems AS SIGNED) - 10000)/1000) + (min_value / value)
				WHEN '100GW' THEN peso/100 
				WHEN 'AWB' THEN 1 -- No action
				WHEN 'FB' THEN hb/2
				WHEN 'GW' THEN peso
				WHEN 'TW' THEN GREATEST(peso,volume_weight)
			END value1
			 , value,
			 act.Id_Moneda, act.min_value, act.max_value
			 FROM awb a JOIN flight f ON f.flight_id = a.flight_id 
			 LEFT JOIN awb_component_template act ON ((IFNULL(act.carguera_id, a.carguera_id) = a.carguera_id AND awb_role_id = 1) 
			 OR (IFNULL(act.carguera_id, a.transitario_id) = a.transitario_id AND awb_role_id = 2)) 
			 AND IFNULL(act.airport_out, f.airport_out) = f.airport_out AND IFNULL(act.airport_in, f.airport_in) = f.airport_in 
			 AND IFNULL(act.airline_id, f.airline_id) = f.airline_id AND INSTR(IFNULL(act.days, WEEKDAY(vShipment) + 1),WEEKDAY(vShipment) + 1)
			 WHERE a.id = v_awb AND Fecha <= vShipment ORDER BY Fecha DESC, act.days DESC) t;
			 
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `adelantarTickets` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `adelantarTickets`(datCurrent DATE,datAttempted DATE)
BEGIN
	DECLARE vWarehouse INTEGER;
    DECLARE vFechedTicket INTEGER;
	DECLARE done INT DEFAULT 0;
    DECLARE vFetchCounter INT DEFAULT 0;
    DECLARE cur1 CURSOR FOR 
		SELECT ticketId
        FROM tmpTicketList;
	DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;
    
    OPEN cur1;
    
	SELECT warehouse_id INTO vWarehouse FROM tmpTicketList ttl JOIN Tickets t ON t.Id_Ticket = ttl.ticketId LIMIT 1;
	CALL item_stock(vWarehouse,CURDATE(),NULL);
    
	DROP TEMPORARY TABLE IF EXISTS tmpAdelantarTickets;
	CREATE TEMPORARY TABLE tmpAdelantarTickets(
		Id_Ticket INT,
		count INT,
		media DOUBLE) 
        ENGINE = MEMORY;
    
	REPEAT
		FETCH cur1 INTO vFechedTicket;
        
	INSERT INTO tmpAdelantarTickets
		SELECT 
			vFechedTicket,
			COUNT(Cantidad),
            AVG(Cantidad <= IFNULL(Saldo, 0)) AS `AVG`
		FROM Movimientos m
			LEFT JOIN
			(SELECT 
				*
			FROM
				(SELECT 
				Id_Article, Saldo
			FROM
				(SELECT 
				Dia, Id_Article, SUM(Entradas - Salidas) AS Saldo
			FROM
				(
                SELECT CURDATE() AS Dia,
					item_id Id_Article,
					stock AS Entradas,
					0 AS Salidas
				FROM tmp_item ti
					JOIN Movimientos m ON m.Id_Article = ti.item_id AND m.Id_Ticket = vFechedTicket
				UNION ALL 
                SELECT DATE(t.Fecha) AS Dia,
					mt.Id_Article,
					0 AS Entradas,
					- m.Cantidad AS Salidas
					FROM Tickets t
						JOIN Movimientos m ON m.Id_Ticket = t.Id_Ticket AND t.warehouse_id = vWarehouse
						JOIN Movimientos mt ON mt.Id_Article = m.Id_Article
					WHERE mt.Id_Ticket = vFechedTicket AND
						t.Fecha BETWEEN curdate() AND datCurrent
				UNION ALL 
						SELECT tr.landing, c.Id_Article, c.Cantidad, 0
					FROM
						Compres c 
						JOIN Movimientos mt ON mt.Id_Article = c.Id_Article
						JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
						JOIN travel tr ON tr.id = travel_id and tr.warehouse_id = vWarehouse
					WHERE mt.Id_Ticket = vFechedTicket AND
						tr.landing BETWEEN curdate() AND datCurrent
				UNION ALL 
					SELECT tr.shipment, c.Id_Article, - c.Cantidad, 0
					FROM
						Compres c
					JOIN Movimientos mt ON mt.Id_Article = c.Id_Article
					JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
					JOIN travel tr ON tr.id = travel_id and tr.warehouse_id_out = vWarehouse
					WHERE mt.Id_Ticket = vFechedTicket AND tr.shipment BETWEEN curdate() AND datCurrent
				) sub GROUP BY Dia , Id_Article) sub2
			ORDER BY Saldo) sub3
			GROUP BY Id_Article) sub4 USING (Id_Article)
		WHERE m.Id_Ticket = vFechedTicket;

    UNTIL done END REPEAT;

	select * from tmpAdelantarTickets;
  CLOSE cur1;
  DROP TEMPORARY TABLE IF EXISTS tmpAdelantarTickets;  
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `agencia_descuadre` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `agencia_descuadre`(datSince DATE, datTo DATE, intAgency INT, intWarehouseAlias INT)
BEGIN

		DECLARE isFile boolean;
    DECLARE datTo2359 DATETIME;
    
    SET datTo2359 = util.dayEnd(datTo);
	     
		SELECT t.Id_Ticket,0 AS Total_Agencia,t.Id_Consigna,t.empresa_id,t.warehouse_id,
			v.suma_componente AS VN, v.suma_componente - shipping_charge AS Difer,
			e.shipping_charge AS teorico,t.Id_Agencia, t.Bultos,t.Id_Cliente, ap.zona
        
        FROM  Tickets t LEFT JOIN 
			(SELECT Id_Ticket, SUM(suma_componente) suma_componente,Fecha 
				FROM v_descuadre_porte2
				WHERE Fecha BETWEEN datSince AND datTo2359
                        GROUP BY Id_Ticket) v ON t.Id_Ticket = v.Id_Ticket
        LEFT JOIN (SELECT  Id_Ticket, SUM(shipping_charge) shipping_charge, Fecha 
						FROM v_expeditions_shipping_charge2 
                        WHERE Fecha BETWEEN datSince AND datTo2359
                        GROUP BY Id_Ticket
				) e ON t.Id_Ticket = e.Id_Ticket
		JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia
        JOIN Consignatarios c ON t.Id_Consigna = c.Id_Consigna
        JOIN Agencias_province ap ON ap.agency_id = a.agency_id AND ap.warehouse_id = t.warehouse_id AND ap.province_id = c.province_id
        JOIN warehouse_group wg ON wg.warehouse_id =t.warehouse_id
        WHERE DATE(t.Fecha) BETWEEN datSince AND datTo2359 AND a.agency_id = intAgency and wg.warehouse_alias_id = intWarehouseAlias;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `agencia_volume` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `agencia_volume`()
BEGIN
    DECLARE v_start DATETIME DEFAULT TIMESTAMP(CURDATE());
    DECLARE v_end DATETIME DEFAULT TIMESTAMP(CURDATE(), '23:59:59');


	SET v_start = IF(WEEKDAY(CURDATE()), CURDATE(),TIMESTAMPADD(DAY,-1,CURDATE()));
	SET v_start = IF(CURDATE() = '2014-05-02', '2014-05-01',v_start);
    DROP TEMPORARY TABLE IF EXISTS agenVOL;
    CREATE TEMPORARY TABLE agenVOL
    (
         Id_Ticket INT PRIMARY KEY
        ,Id_Agencia INT
        ,Agencia VARCHAR(30)
        ,Bultos INT DEFAULT 0
        ,Faltan INT DEFAULT 0
        /*,Prioridad VARCHAR(15) DEFAULT ''*/
    )
    ENGINE=MEMORY;
    
    -- Insertamos los tickets que ya tienen la linea de portes
          
    INSERT INTO agenVOL(Id_Agencia, Agencia, Id_Ticket, Bultos)
    SELECT a.Id_Agencia, name , Id_Ticket, sum(Cantidad) Bultos
        FROM Tickets t
        JOIN Agencias a USING(Id_Agencia)
        JOIN Movimientos m USING(Id_Ticket)
        JOIN agency ag USING(agency_id)
		JOIN warehouse_joined wj ON wj.warehouse_id = t.warehouse_id
            WHERE Concepte LIKE '%porte%'
            AND wj.warehouse_alias_id = 1 -- El 1 equivale a Silla (SillaFV-SillaPCA)
            AND Fecha BETWEEN v_start AND v_end
            AND Vista = 1
            GROUP BY Id_Ticket;
            
    -- Insertamos los tickets que ya tienen expediciones, que fallaran si se repite la clave primaria.
          
    INSERT INTO agenVOL(Id_Agencia, Agencia, Id_Ticket, Bultos)
    SELECT a.Id_Agencia, name, ticket_id, COUNT(ticket_id) 
        FROM expeditions e
			JOIN Tickets t ON t.Id_Ticket =  e.ticket_id
			JOIN Agencias a ON a.Id_Agencia  = e.agency_id
			JOIN agency ag ON ag.agency_id = a.agency_id
			JOIN warehouse_joined wj ON wj.warehouse_id = t.warehouse_id
				WHERE t.Fecha BETWEEN v_start AND v_end
				AND wj.warehouse_alias_id = 1 -- El 1 equivale a Silla (SillaFV-SillaPCA)
				AND Vista = 1
				GROUP BY ticket_id 
				ON DUPLICATE KEY UPDATE Bultos = Bultos;

    -- Adivinamos el futuro
          INSERT INTO agenVOL(Id_Agencia, Agencia, Id_Ticket, Faltan)
    SELECT a.Id_Agencia, name, Id_Ticket, 1 as Faltan
        FROM Tickets t
        JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia
        JOIN agency ag ON ag.agency_id = a.agency_id
        LEFT JOIN expeditions e ON e.ticket_id = t.Id_Ticket
		JOIN warehouse_joined wj ON wj.warehouse_id = t.warehouse_id
            WHERE Fecha BETWEEN v_start AND v_end
            AND Bultos = 0 AND expeditions_id IS NULL AND EtiquetasEmitidas = 0
            AND wj.warehouse_alias_id = 1 -- JGF 18/12/14 El 1 equivale a Silla (SillaFV-SillaPCA) 
            AND Vista = 1 
            GROUP BY Id_Ticket            
            ON DUPLICATE KEY UPDATE Faltan = Faltan + 1;
            
   
    -- Matizamos la urgencia para ZELERIS
       /*  
    UPDATE agenVOL a
        JOIN Tickets t USING(Id_Ticket)
        JOIN Clientes c USING(Id_Cliente)
        JOIN Agencias agen ON agen.Id_Agencia = t.Id_Agencia
        JOIN agency ag ON ag.agency_id = agen.agency_id
        JOIN Agencias_province ap ON ag.agency_id = ap.province_id
        JOIN province p ON p.province_id = ap.province_id
            SET a.Prioridad = IF(p.name IN ('VALENCIA','MURCIA','MADRID','BARCELONA','GIRONA','ALICANTE','CASTELLON'), 'LENTA','RAPIDA')
            WHERE ag.name LIKE 'zeleris';*/
        
    SELECT agen.agency_id, name Agencia, COUNT(Id_Ticket) expediciones, SUM(Bultos) Bultos, SUM(Faltan) Faltan/*, Prioridad*/
        FROM agenVOL a
        JOIN Agencias agen USING(Id_Agencia)
        JOIN agency ag USING(agency_id)
            GROUP BY ag.agency_id/*, Prioridad*/ ;
        
    DROP TEMPORARY TABLE IF EXISTS agenVOL;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `alfa_invoices` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `alfa_invoices`(IN datFEC DATE)
BEGIN

DECLARE datSTART DATETIME;
DECLARE vTotal DECIMAL(10,2) DEFAULT 0.00;

SET @myId = -10000000;
SET @myRef = 'factura';
SET @myTotal = vTotal;

SET datSTART = TIMESTAMPADD(DAY, -1 * DAYOFMONTH(datFEC) + 1, datfec);

IF datFEC < '2017-07-01' THEN

	SELECT 	Id_Factura `Invoice no`,
			date(Fecha) as `Invoice date`,
            Id_Cliente `Debtor no`,
            `IF` `Vat nr`,
            Razonsocial `Name`,
            BI7 `Amount excl Vat 6%`,
			BI16 `Amount excl Vat 19%`,
            IVA7 `Vat 6%`,
            IVA16 `Vat 19%`,
            Importe `Total inc Vat`
		from Facturas 
			INNER JOIN Clientes USING(Id_Cliente)
		where empresa_id = 567
			and Fecha BETWEEN datSTART AND datFEC
		order by `Invoice date`, factura_id;

ELSE

SELECT * FROM
	(
	SELECT 	io.ref `Invoice no`,
			io.issued `Invoice date`,
			IF(@myId = io.id, '', clientFk) `Debtor no`,
			IF(@myId = io.id, '', c.fi) `Vat nr`,
			IF(@myId = io.id, '', c.socialName) `Name`,
			taxableBase `Taxable Amount excl VAT`,
			CONCAT(CAST(pgc.rate AS DECIMAL(2,0)) ,' %') `VAT Rate`,
			CAST(vat AS DECIMAL(10,2)) `VAT Quote`,
			CAST(@myTotal + taxableBase + vat AS DECIMAL(10,2)) `Total plus Vat`,
            IF(@myId := io.id, NULL, NULL) as ControlField
		FROM vn.invoiceOut io
			JOIN vn.client c ON c.id = io.clientFk
			JOIN vn.invoiceOutTax iot ON iot.invoiceOutFk = io.id
			JOIN vn.pgc ON pgc.code = iot.pgcFk
		WHERE io.companyFk = 567
			AND io.issued BETWEEN datSTART AND datFEC
		ORDER BY io.id, iot.id
	) t1
    ORDER BY `Invoice date` DESC, `Invoice no`;

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 `article` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `article`()
BEGIN
	DROP TEMPORARY TABLE IF EXISTS `article_inventory`;
	CREATE TEMPORARY TABLE `article_inventory`
	(
		`article_id` INT(11) NOT NULL PRIMARY KEY,
		`future` DATETIME
	)
	ENGINE = MEMORY;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `article_available_single` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `article_available_single`(IN v_wh TINYINT, IN v_date DATETIME, IN id_single INT)
BEGIN

	CALL bionic_available_single (v_wh, v_date,id_single,0);
	
	
	SELECT available AS minimo FROM tmp_item
 WHERE item_id = id_single;
-- ixen totes les linies en lloc d'una sola
    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 `article_inventory_warehouses` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `article_inventory_warehouses`(vDate DATE)
proc: BEGIN
/**
 * Recalcula los inventarios de todos los almacenes.
 *
 * @param vDate Fecha de los nuevos inventarios
 */
	DECLARE vWh INT;
	DECLARE vDone BOOL;
	DECLARE vEntryId INT;
	DECLARE vTravelId INT;
	DECLARE vDateTime DATETIME DEFAULT TIMESTAMP(vDate, '00:00:00');
	DECLARE vDeleteDate DATE DEFAULT TIMESTAMPADD(DAY, -2, vDate);

	DECLARE cWarehouses CURSOR FOR
		SELECT id FROM warehouse WHERE inventario;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	OPEN cWarehouses;

	l: LOOP

		SET vDone = FALSE;
		FETCH cWarehouses INTO vWh;

		IF vDone THEN
			LEAVE l;
		END IF;

		INSERT INTO travel SET
			warehouse_id_out = 13,
			warehouse_id = vWh,
			shipment = vDateTime,
			landing = vDateTime,
			agency_id = 53,
			ref = 'inventario',
			delivered = TRUE,
			received = TRUE;

		SELECT LAST_INSERT_ID() INTO vTravelId; 

		INSERT INTO Entradas SET
			Id_Proveedor = 4,
			Fecha = vDateTime,
			Confirmada = TRUE,
			Pedida = TRUE,
			travel_id = vTravelId;

		SELECT LAST_INSERT_ID() INTO vEntryId;

		-- Inserta el visible

		CALL inventario_multiple_inventarios (vWh, vDateTime);

		-- Inserta Last_buy_id

		ALTER TABLE article_inventory
			ADD buy_id INT;

		UPDATE article_inventory ai 
			JOIN 
			(
				SELECT * FROM (
					SELECT Id_Article, Id_Compra,warehouse_id
						FROM Compres c
							JOIN Entradas e USING (Id_Entrada)
							JOIN travel tr ON tr.id = e.travel_id
						WHERE Novincular = FALSE
							AND costefijo > 0 AND tarifa2 > 0
							AND NOT Redada
							AND landing BETWEEN date_inv() AND vDate 
						ORDER BY (vWh = warehouse_id) DESC, landing DESC
				) t1
				GROUP BY Id_Article
			) t
			ON ai.article_id = t.Id_Article
				SET ai.buy_id = t.Id_Compra; 

		INSERT INTO Compres (
				 Id_Entrada
				,Id_Article
				,Cantidad
				,Costefijo
				,Packing
				,Id_Cubo
				,Tarifa2
				,Tarifa3
				,Productor
			)
			SELECT
				 vEntryId
				,AI.article_id
				,IF(AI.visible < 0,0,AI.visible)
				,ifnull(C.Costefijo,0) + ifnull(C.Portefijo,0) + ifnull(C.Comisionfija,0) + ifnull(C.Embalajefijo,0)
				,C.Packing
				,C.Id_Cubo
				,C.Tarifa2
				,C.Tarifa3
				,C.Productor
				FROM article_inventory AI
					LEFT JOIN Compres C ON C.Id_Compra = AI.buy_id;

		DROP TEMPORARY TABLE article_inventory;
	END LOOP;

	CLOSE cWarehouses;

	UPDATE tblContadores SET FechaInventario = vDate;

	DELETE e, t
		FROM travel t
			JOIN Entradas e ON e.travel_id = t.id 
		WHERE Id_Proveedor = 4
			AND shipment <= vDeleteDate
			AND (DAY(shipment) <> 1 OR shipment < TIMESTAMPADD(MONTH, -12, 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 `article_inventory_warehouses_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 `article_inventory_warehouses_kk`(vDate DATE)
proc: BEGIN
/**
 * Recalcula los inventarios de todos los almacenes.
 *
 * @param vDate Fecha de los nuevos inventarios
 */
	DECLARE vWh INT;
	DECLARE vDone BOOL;
	DECLARE vEntryId INT;
	DECLARE vTravelId INT;
	DECLARE vDateTime DATETIME DEFAULT TIMESTAMP(vDate, '00:00:00');
	DECLARE vDeleteDate DATE DEFAULT TIMESTAMPADD(DAY, -2, vDate);

	DECLARE cWarehouses CURSOR FOR
		SELECT id FROM warehouse WHERE inventario;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	OPEN cWarehouses;

	l: LOOP

		SET vDone = FALSE;
		FETCH cWarehouses INTO vWh;

		IF vDone THEN
			LEAVE l;
		END IF;

		INSERT INTO travel SET
			warehouse_id_out = 13,
			warehouse_id = vWh,
			shipment = vDateTime,
			landing = vDateTime,
			agency_id = 53,
			ref = 'inventario',
			delivered = TRUE,
			received = TRUE;

		SELECT LAST_INSERT_ID() INTO vTravelId; 

		INSERT INTO Entradas SET
			Id_Proveedor = 4,
			Fecha = vDateTime,
			Confirmada = TRUE,
			Pedida = TRUE,
			travel_id = vTravelId;

		SELECT LAST_INSERT_ID() INTO vEntryId;

		-- Inserta el visible

		CALL inventario_multiple_inventarios (vWh, vDateTime);

		-- Inserta Last_buy_id

		ALTER TABLE article_inventory
			ADD buy_id INT;

		UPDATE article_inventory ai 
			JOIN 
			(
				SELECT * FROM (
					SELECT Id_Article, Id_Compra,warehouse_id
						FROM Compres c
							JOIN Entradas e USING (Id_Entrada)
							JOIN travel tr ON tr.id = e.travel_id
						WHERE Novincular = FALSE
							AND costefijo > 0 AND tarifa2 > 0
							AND NOT Redada
							AND landing BETWEEN date_inv() AND vDate 
						ORDER BY (vWh = warehouse_id) DESC, landing DESC
				) t1
				GROUP BY Id_Article
			) t
			ON ai.article_id = t.Id_Article
				SET ai.buy_id = t.Id_Compra; 

		INSERT INTO Compres (
				 Id_Entrada
				,Id_Article
				,Cantidad
				,Costefijo
				,Packing
				,Id_Cubo
				,Tarifa2
				,Tarifa3
				,Productor
			)
			SELECT
				 vEntryId
				,AI.article_id
				,IF(AI.visible < 0,0,AI.visible)
				,ifnull(C.Costefijo,0) + ifnull(C.Portefijo,0) + ifnull(C.Comisionfija,0) + ifnull(C.Embalajefijo,0)
				,C.Packing
				,C.Id_Cubo
				,C.Tarifa2
				,C.Tarifa3
				,C.Productor
				FROM article_inventory AI
					LEFT JOIN Compres C ON C.Id_Compra = AI.buy_id;

		DROP TEMPORARY TABLE article_inventory;
	END LOOP;

	CLOSE cWarehouses;

	UPDATE tblContadores SET FechaInventario = vDate;

	DELETE e, t
		FROM travel t
			JOIN Entradas e ON e.travel_id = t.id 
		WHERE Id_Proveedor = 4
			AND shipment <= vDeleteDate
			AND (DAY(shipment) <> 1 OR shipment < TIMESTAMPADD(MONTH, -12, 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 `article_minacum` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `article_minacum`(IN v_wh TINYINT, IN v_date_ini DATETIME, IN v_range INT)
BEGIN
	-- CÃ¡lculo del mÃ­nimo acumulado

	DECLARE v_date DATE DEFAULT v_date_ini;
	DECLARE v_date_end DATETIME;

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

	-- CALL item_travel (v_wh, v_date_ini);

	DROP TEMPORARY TABLE IF EXISTS article_minacum;
	CREATE TEMPORARY TABLE article_minacum
    ENGINE = MEMORY
	SELECT t.article_id, t.warehouse_id, minacum(dat, amount, v_date) AS amount FROM (
		SELECT article_id, DATE(Fecha) AS dat, SUM(amount) AS amount, warehouse_id FROM (
			SELECT Id_Article article_id, Fecha, -Cantidad AS amount, warehouse_id
				FROM Movimientos m INNER JOIN Tickets t USING (Id_Ticket)
					WHERE Fecha BETWEEN v_date_ini AND v_date_end
					AND Cantidad != 0
					AND (@aid IS NULL OR Id_Article = @aid)
                    AND (v_wh IS NULL OR t.warehouse_id = v_wh)
			UNION ALL
			SELECT Id_Article, t.landing, Cantidad, warehouse_id
				FROM Compres c INNER JOIN Entradas e USING (Id_Entrada)
				LEFT JOIN travel t ON e.travel_id = t.id
					WHERE t.landing BETWEEN v_date_ini AND v_date_end
					AND (v_wh IS NULL OR t.warehouse_id = v_wh)
					AND e.Inventario = FALSE
					AND Cantidad != 0
					AND (@aid IS NULL OR Id_Article = @aid)
			UNION ALL
			SELECT Id_Article, t.shipment, -Cantidad, warehouse_id_out
				FROM Compres c INNER JOIN Entradas e USING (Id_Entrada)
				LEFT JOIN travel t ON e.travel_id = t.id
					WHERE t.shipment BETWEEN v_date_ini AND v_date_end
					AND (v_wh IS NULL OR t.warehouse_id_out = v_wh)
					AND e.Inventario = FALSE
					AND Cantidad != 0
					AND (@aid IS NULL OR Id_Article = @aid)
		) t1
		GROUP BY t1.article_id, dat, warehouse_id
	) t
	
  	GROUP BY t.article_id, warehouse_id HAVING amount != 0;
    SET @aid = 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 `article_multiple_buy` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `article_multiple_buy`(v_date DATETIME, wh INT)
BEGIN

    ALTER TABLE article_inventory
        ADD buy_id INT;

    DROP TEMPORARY TABLE IF EXISTS tmp;
	
	call vn.buyUltimate(wh, v_date);
	
    CREATE TEMPORARY TABLE tmp
		(KEY (itemFk))
		ENGINE = MEMORY
		SELECT * FROM
		(
			SELECT itemFk, buyFk 
				FROM tmp.buyUltimate
				ORDER BY (wh = warehouseFk) DESC 
		) t
		GROUP BY itemFk;

    UPDATE article_inventory ai 
		JOIN tmp t ON ai.article_id = t.itemFk
        SET ai.buy_id = t.buyFk; 

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `article_multiple_buy_date` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `article_multiple_buy_date`(IN date_ DATETIME, IN wh TINYINT(3))
BEGIN

  DECLARE datINV DATE;
  SELECT FechaInventario INTO datINV FROM tblContadores;

	ALTER TABLE `article_inventory`
		ADD `buy_date` datetime NOT NULL;

	UPDATE article_inventory INNER JOIN
	(

  SELECT * FROM
   (
		SELECT travel.landing AS bdate, Compres.Id_Article AS article_id
    FROM Compres
    JOIN Entradas USING(Id_Entrada)
    JOIN travel ON travel.id = Entradas.travel_id
    
    JOIN warehouse W ON W.id = travel.warehouse_id
    WHERE travel.landing BETWEEN datINV AND date_
    AND IF(wh = 0, W.comisionantes, wh = travel.warehouse_id)
    /*AND Compres.Novincular = FALSE
    AND Entradas.Id_Proveedor <> 4
    AND Entradas.Inventario = FALSE*/
    -- jgf 2017/03/06 en la comparativa no trau el dia de caducitat
    AND Entradas.Redada = FALSE
    ORDER BY article_id, bdate DESC

    ) AS temp
      GROUP BY article_id
	)
	AS buy ON article_inventory.article_id = buy.article_id
	SET article_inventory.buy_date = buy.bdate;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `article_multiple_buy_last` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = latin1 */ ;
/*!50003 SET character_set_results = latin1 */ ;
/*!50003 SET collation_connection  = latin1_swedish_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `article_multiple_buy_last`(IN wh TINYINT, IN date_end DATETIME)
BEGIN
	DECLARE v_date DATETIME;

	DROP TEMPORARY TABLE IF EXISTS article_buy_last;
	CREATE TEMPORARY TABLE article_buy_last
	SELECT * FROM (
		SELECT c.Id_Article AS article_id, c.Id_Compra AS id
			FROM Compres c INNER JOIN Entradas e USING(Id_Entrada)
      			INNER JOIN travel t ON t.id = e.travel_id
				WHERE t.landing BETWEEN date_inv() AND date_end
				AND c.Novincular = FALSE
        AND c.tarifa2 > 0
				ORDER BY t.landing DESC,(wh IN (0,t.warehouse_id)) DESC, (Id_Cubo IS NULL) ,article_id,  (e.Id_proveedor = 4)
	) t
	GROUP BY article_id;
	ALTER TABLE article_buy_last ADD INDEX (article_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 `article_visible_single` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `article_visible_single`(IN v_wh TINYINT,IN v_article INT)
BEGIN
DECLARE bisible FLOAT;
CALL article_visible_single2(v_wh,v_article,@suma2);

SET bisible = @suma2;
SELECT bisible AS suma, A.Id_Article, A.Article, A.Medida, A.Tallos, A.Nicho, O.Abreviatura as origen, A.Color, A.Tipo, A.Nicho,
    A.Categoria
  		FROM v_compres A INNER JOIN Origen O ON O.id = A.id_origen WHERE A.Id_Article =v_article AND A.warehouse_id = v_wh ORDER BY landing DESC 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 `article_visible_single2` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `article_visible_single2`(IN v_wh TINYINT,IN v_article INT,OUT int_amount INT)
BEGIN

	call item_stock(v_wh,CURDATE(),v_article);
	call article_visible(v_wh);

		SELECT  SUM(stock) INTO int_amount FROM tmp_item WHERE item_id = v_article ;
		SELECT  IFNULL(SUM(amount),0) + IFNULL(int_amount,0) INTO int_amount 
			FROM article_visible 
			WHERE article_id = v_article;

	DROP TEMPORARY TABLE tmp_item;
	DROP TEMPORARY TABLE article_visible;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `availableTraslate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `availableTraslate`(vWarehouseLanding INT, v_date DATE,vWarehouseShipment INT)
proc: BEGIN
	DECLARE v_date_ini DATE;
	DECLARE v_date_end DATETIME;
	DECLARE v_reserve_date DATETIME;
    DECLARE v_date_inv DATE;

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

	CALL vn2008.item_stock (vWarehouseLanding, v_date, 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.Id_Article item_id, MAX(landing) date_end
		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 = vWarehouseLanding
			AND NOT e.Inventario
			AND NOT e.Redada
		GROUP BY Id_Article;
        
    -- Tabla con el ultimo dia de last_buy para cada producto que hace un replace de la anterior
         
	CALL item_last_buy_(vWarehouseShipment,curdate());
    
	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;

	INSERT INTO item_range
		SELECT t.item_id, tr.landing 
			FROM t_item_last_buy t
				JOIN Compres c ON c.Id_Compra = t.buy_id
				JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
				JOIN travel tr ON tr.id = e.travel_id
				LEFT JOIN item_range_copy i ON t.item_id = i.item_id
			WHERE t.warehouse_id = vWarehouseShipment
	ON DUPLICATE KEY UPDATE item_range.date_end = GREATEST(item_range.date_end,landing);

    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 c.item_id, TIMESTAMP(TIMESTAMPADD(DAY, t.life, c.date_end), '23:59:59') date_end FROM item_range 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;
		
	DROP TEMPORARY TABLE IF EXISTS item_range_copy2;
	CREATE TEMPORARY TABLE item_range_copy2 LIKE  item_range_copy1;
	INSERT INTO item_range_copy2 
		SELECT * FROM item_range_copy1;
		
	DROP TEMPORARY TABLE IF EXISTS item_range_copy3;
	CREATE TEMPORARY TABLE item_range_copy3 LIKE  item_range_copy1;
	INSERT INTO item_range_copy3 
		SELECT * FROM item_range_copy1;
		
	DROP TEMPORARY TABLE IF EXISTS item_range_copy4;
	CREATE TEMPORARY TABLE item_range_copy4 LIKE  item_range_copy1;
	INSERT INTO item_range_copy4 
		SELECT * FROM item_range_copy1;
		
	DROP TEMPORARY TABLE IF EXISTS item_range_copy5;
	CREATE TEMPORARY TABLE item_range_copy5 LIKE  item_range_copy1;
	INSERT INTO item_range_copy5 
		SELECT * FROM item_range_copy1;

    -- Calcula el ATP

	DROP TEMPORARY TABLE IF EXISTS availableTraslate;
	CREATE TEMPORARY TABLE availableTraslate
		(PRIMARY KEY (item_id))
		ENGINE = MEMORY
	SELECT t.item_id, SUM(stock) available 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 = vWarehouseLanding
				UNION ALL
				SELECT m.Id_Article item_id, t.landing dat, m.Cantidad amount
					FROM Compres m
								JOIN Entradas e ON m.Id_Entrada = e.Id_Entrada
								JOIN travel t ON e.travel_id = t.id
                                JOIN item_range_copy2 ir ON ir.item_id = m.Id_Article
							WHERE
								e.Inventario = 0
								AND m.Cantidad <> 0
								AND e.redada = 0
								AND t.warehouse_id = vWarehouseLanding
								AND t.landing >= v_date_ini
								AND (ir.date_end IS NULL OR t.landing <= ir.date_end)
						
				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 = vWarehouseLanding
				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 = vWarehouseLanding
						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 available != 0;

	DROP TEMPORARY TABLE
		 vn2008.tmp_item
		,item_range
		,item_range_copy1
		,item_range_copy2
		,item_range_copy3
		,item_range_copy4
        ,item_range_copy5;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `availableTraslateTesting` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `availableTraslateTesting`(vWarehouseLanding INT, v_date DATE,vWarehouseShipment INT)
proc: BEGIN
	DECLARE v_date_ini DATE;
	DECLARE v_date_end DATETIME;
	DECLARE v_reserve_date DATETIME;
    DECLARE v_date_inv DATE;

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

	CALL vn2008.item_stock (vWarehouseLanding, v_date, 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.Id_Article item_id, MAX(landing) date_end
		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 = vWarehouseLanding
			AND NOT e.Inventario
			AND NOT e.Redada
		GROUP BY Id_Article;
        
    -- Tabla con el ultimo dia de last_buy para cada producto que hace un replace de la anterior
		
    SELECT vWarehouseShipment;
        
	CALL item_last_buy_(vWarehouseShipment,v_date);
    
    SELECT *,'last_buy' FROM t_item_last_buy t ; -- WHERE t.item_id = 41576;
    SELECT * FROM item_range t WHERE t.item_id = 41576;
    
	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;

		SELECT 'update' , t.item_id, tr.landing 
			FROM t_item_last_buy t
				JOIN Compres c ON c.Id_Compra = t.buy_id
				JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
				JOIN travel tr ON tr.id = e.travel_id
				LEFT JOIN item_range_copy i ON t.item_id = i.item_id
			WHERE t.warehouse_id = vWarehouseShipment AND t.item_id = 41576;
            
	INSERT INTO item_range
		SELECT t.item_id, tr.landing 
			FROM t_item_last_buy t
				JOIN Compres c ON c.Id_Compra = t.buy_id
				JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
				JOIN travel tr ON tr.id = e.travel_id
				LEFT JOIN item_range_copy i ON t.item_id = i.item_id
			WHERE t.warehouse_id = vWarehouseShipment
	ON DUPLICATE KEY UPDATE item_range.date_end = GREATEST(item_range.date_end,landing);

    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 c.item_id, TIMESTAMP(TIMESTAMPADD(DAY, t.life, c.date_end), '23:59:59') date_end FROM item_range 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;
        
       select * from  item_range_copy1 where item_id = 41576;
		
	DROP TEMPORARY TABLE IF EXISTS item_range_copy2;
	CREATE TEMPORARY TABLE item_range_copy2 LIKE  item_range_copy1;
	INSERT INTO item_range_copy2 
		SELECT * FROM item_range_copy1;
		
	DROP TEMPORARY TABLE IF EXISTS item_range_copy3;
	CREATE TEMPORARY TABLE item_range_copy3 LIKE  item_range_copy1;
	INSERT INTO item_range_copy3 
		SELECT * FROM item_range_copy1;
		
	DROP TEMPORARY TABLE IF EXISTS item_range_copy4;
	CREATE TEMPORARY TABLE item_range_copy4 LIKE  item_range_copy1;
	INSERT INTO item_range_copy4 
		SELECT * FROM item_range_copy1;
		
	DROP TEMPORARY TABLE IF EXISTS item_range_copy5;
	CREATE TEMPORARY TABLE item_range_copy5 LIKE  item_range_copy1;
	INSERT INTO item_range_copy5 
		SELECT * FROM item_range_copy1;

    -- Calcula el ATP
	SELECT ti.item_id, stock
			FROM vn2008.tmp_item ti
				JOIN item_range ir ON ir.item_id = ti.item_id ;
                
		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 = vWarehouseLanding;
                        
		SELECT m.Id_Article item_id, t.landing dat, m.Cantidad amount
					FROM Compres m
								JOIN Entradas e ON m.Id_Entrada = e.Id_Entrada
								JOIN travel t ON e.travel_id = t.id
                                JOIN item_range_copy2 ir ON ir.item_id = m.Id_Article
							WHERE
								e.Inventario = 0
								AND m.Cantidad <> 0
								AND e.redada = 0
								AND t.warehouse_id = vWarehouseLanding
								AND t.landing >= v_date_ini
								AND (ir.date_end IS NULL OR t.landing <= ir.date_end);
                                
                   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 = vWarehouseLanding;
             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 = vWarehouseLanding
						AND r.created >= v_reserve_date
						AND NOT o.confirmed;
                        
	DROP TEMPORARY TABLE IF EXISTS availableTraslate;
	CREATE TEMPORARY TABLE availableTraslate
		(PRIMARY KEY (item_id))
		ENGINE = MEMORY
	SELECT t.item_id, SUM(stock) available 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 = vWarehouseLanding
				UNION ALL
				SELECT m.Id_Article item_id, t.landing dat, m.Cantidad amount
					FROM Compres m
								JOIN Entradas e ON m.Id_Entrada = e.Id_Entrada
								JOIN travel t ON e.travel_id = t.id
                                JOIN item_range_copy2 ir ON ir.item_id = m.Id_Article
							WHERE
								e.Inventario = 0
								AND m.Cantidad <> 0
								AND e.redada = 0
								AND t.warehouse_id = vWarehouseLanding
								AND t.landing >= v_date_ini
								AND (ir.date_end IS NULL OR t.landing <= ir.date_end)
						
				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 = vWarehouseLanding
				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 = vWarehouseLanding
						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 available != 0;

	select * from availableTraslate where item_id = 41576;

	DROP TEMPORARY TABLE
		 vn2008.tmp_item
		,item_range
		,item_range_copy1
		,item_range_copy2
		,item_range_copy3
		,item_range_copy4
        ,item_range_copy5;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `balance_create` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `balance_create`(IN vStartingMonth INT
                                                   , IN vEndingMonth INT
                                                   , IN vCompany INT
                                                   , IN vConsolidate BOOLEAN
                                                   , IN vInterGroupSalesIncluded BOOLEAN)
BEGIN

DECLARE v_sql TEXT;
DECLARE strTABLE VARCHAR(20) DEFAULT "balance_nest_tree";
DECLARE intGAP INTEGER DEFAULT 7;
DECLARE intYEARS INTEGER DEFAULT 3;
DECLARE vConsolidatedGroup INTEGER;
DECLARE vStartingDate DATE DEFAULT '2016-01-01';
DECLARE vStartingYear INT DEFAULT 2016;


-- Solicitamos la tabla tmp.nest, como base para el balance
CALL nest_tree(strTABLE,intGAP, FALSE);

DROP TEMPORARY TABLE IF EXISTS tmp.balance;

CREATE TEMPORARY TABLE tmp.balance
SELECT * FROM tmp.nest;

DROP TEMPORARY TABLE IF EXISTS tmp.empresas_receptoras;
DROP TEMPORARY TABLE IF EXISTS tmp.empresas_emisoras;

IF vConsolidate THEN
	SELECT empresa_grupo INTO vConsolidatedGroup FROM empresa WHERE id = vCompany;
END IF;

CREATE TEMPORARY TABLE tmp.empresas_receptoras
	SELECT id as empresa_id
	FROM vn2008.empresa
	WHERE id = vCompany
	OR empresa_grupo = vConsolidatedGroup;

																	
CREATE TEMPORARY TABLE tmp.empresas_emisoras
	SELECT Id_Proveedor as empresa_id
	FROM vn2008.Proveedores p;
																		
IF NOT vInterGroupSalesIncluded THEN

	DELETE ee.* 
		FROM tmp.empresas_emisoras ee
		JOIN vn2008.empresa e on e.id = ee.empresa_id
		WHERE e.empresa_grupo = vConsolidatedGroup;

	END IF;
																		
-- Se calculan las facturas que intervienen, para luego poder servir el desglose desde aqui

DROP TEMPORARY TABLE IF EXISTS tmp.balance_desglose;
CREATE TEMPORARY TABLE tmp.balance_desglose
	SELECT er.empresa_id as receptora_id
		 , ee.empresa_id as emisora_id
         , year(IFNULL(r.bookEntried,IFNULL(r.dateBooking, r.Fecha))) as `year`
         , month(IFNULL(r.bookEntried,IFNULL(r.dateBooking, r.Fecha))) as `month`
         , gastos_id as Id_Gasto
         , sum(bi) as importe
		FROM recibida r 
		JOIN recibida_iva ri on ri.recibida_id = r.id 
        JOIN tmp.empresas_receptoras er on er.empresa_id = r.empresa_id
        JOIN tmp.empresas_emisoras ee ON ee.empresa_id = r.proveedor_id
		WHERE IFNULL(r.bookEntried,IFNULL(r.dateBooking, r.Fecha)) >= vStartingDate 
        AND r.contabilizada
		GROUP BY Id_Gasto, year, month, emisora_id, receptora_id;

INSERT INTO tmp.balance_desglose(receptora_id
							   , emisora_id
                               , year
                               , month
                               , Id_Gasto
                               , importe)
	SELECT gr.empresa_id
		 , gr.empresa_id
         , year
         , month
         , Id_Gasto
         , sum(importe)
		FROM gastos_resumen gr
		JOIN tmp.empresas_receptoras er on gr.empresa_id = er.empresa_id
		WHERE year >= vStartingYear
        AND month BETWEEN vStartingMonth AND vEndingMonth
		GROUP BY Id_Gasto, year, month, gr.empresa_id;
  
		
DELETE FROM tmp.balance_desglose
	WHERE month < vStartingMonth
	OR month > vEndingMonth;

																						

-- Ahora el balance
SET v_sql = sql_printf (
                '
                ALTER TABLE tmp.balance
                ADD COLUMN %t INT(10) NULL ,
                ADD COLUMN %t INT(10) NULL ,
                ADD COLUMN %t INT(10) NULL ,
                ADD COLUMN Id_Gasto VARCHAR(10) NULL,
                ADD COLUMN Gasto VARCHAR(45) NULL;
                ',
                YEAR(CURDATE())-2,
				YEAR(CURDATE())-1,
				YEAR(CURDATE())
			);
            
CALL util.exec (v_sql);


-- Añadimos los gastos, para facilitar el formulario

UPDATE tmp.balance b
JOIN vn2008.balance_nest_tree bnt on bnt.id = b.id
JOIN (SELECT Id_Gasto, Gasto
	  FROM vn2008.Gastos
      GROUP BY Id_Gasto) g ON g.Id_Gasto = bnt.Id_Gasto
SET b.Id_Gasto = g.Id_Gasto
    , b.Gasto = g.Gasto;

-- Rellenamos los valores de primer nivel, los que corresponden a los gastos simples

WHILE intYEARS > 0 DO

	SET intYEARS = intYEARS - 1;
    
	SET v_sql = sql_printf (
					'
					UPDATE tmp.balance b
					JOIN 
					(
                    	SELECT Id_Gasto, sum(Importe) as Importe
                        FROM tmp.balance_desglose
                        WHERE year = %v
                        GROUP BY Id_Gasto
					) sub on sub.Id_Gasto = b.Id_Gasto
                  	SET %t =  - Importe;
					',
					YEAR(CURDATE()) - intYEARS,
					YEAR(CURDATE()) - intYEARS
				);
                
	CALL util.exec (v_sql);

END WHILE;

-- Añadimos las ventas

   
	SET v_sql = sql_printf (
					'
                    UPDATE tmp.balance b
                    JOIN (  
							SELECT   sum(IF(year = %v, venta, 0)) as y2
                                   , sum(IF(year = %v, venta, 0)) as y1
                                   , sum(IF(year = %v, venta, 0)) as y0
                                   , c.Gasto

							FROM bs.ventas_contables c
                            join tmp.empresas_receptoras er on er.empresa_id = c.empresa_id
							WHERE  month BETWEEN %v AND %v
                            GROUP BY c.Gasto
                            
                          ) sub ON sub.Gasto = b.Id_Gasto
                    SET  %t = IFNULL(%t,0) + sub.y2 
                       , %t = IFNULL(%t,0) + sub.y1
					   , %t = IFNULL(%t,0) + sub.y0
                    ;
                    
					',
                    YEAR(CURDATE()) - 2,
					YEAR(CURDATE()) - 1,  
                    YEAR(CURDATE()),  
					vStartingMonth,
					vEndingMonth,
                    YEAR(CURDATE()) - 2,  YEAR(CURDATE()) - 2,   
					YEAR(CURDATE()) - 1,  YEAR(CURDATE()) - 1,   
                    YEAR(CURDATE()),  YEAR(CURDATE()) 
                    
				);
                
	CALL util.exec (v_sql);

-- Ventas intra grupo
IF NOT vInterGroupSalesIncluded THEN

	SELECT lft, rgt 
		INTO @grupoLft, @grupoRgt 
		FROM tmp.balance b
		WHERE TRIM(b.`name`) = 'Grupo';
    
	DELETE 
		FROM tmp.balance
		WHERE lft BETWEEN @grupoLft AND @grupoRgt;

END IF;
																					

-- Rellenamos el valor de los padres con la suma de los hijos
DROP TEMPORARY TABLE IF EXISTS tmp.balance_aux;
CREATE TEMPORARY TABLE tmp.balance_aux SELECT * FROM tmp.balance;

UPDATE tmp.balance b
JOIN
(
select b1.id, b1.name, sum(b2.`2017`) as `2017`, sum(b2.`2018`) as `2018`, sum(b2.`2019`) as `2019`
from tmp.nest b1
join tmp.balance_aux b2 on b2.lft between b1.lft and b1.rgt
group by b1.id) sub on sub.id = b.id
SET b.`2017` = sub.`2017`, b.`2018` = sub.`2018`, b.`2019` = sub.`2019`
;



SELECT *, concat('',ifnull(Id_Gasto,'')) as newgasto FROM tmp.balance;
    

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `base_ticket` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `base_ticket`(IN Id_Ticket INT)
BEGIN
	SELECT 
        red(SUM(Cantidad * Preu * (100 - Descuento) / 100)) AS base
    FROm
        Movimientos m
		INNER JOIN Tickets t USING (Id_Ticket)
	WHERE t.Id_Ticket = Id_Ticket;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_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              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `bionic_available_`(
	vDate DATE,
    vAddress INT,
    vAgency INT)
BEGIN
/**
 * Calcula el disponible para un conjunto de almacenes y fechas
 * devueltos por el procedimiento agencyHourGetShipped()
 *
 * @table t_bionic_available Tabla con los ids de cache
 **/
	DECLARE vAvailableCalc INT;
	DECLARE vShipment DATE;
	DECLARE vAgencyId INT;
    DECLARE vWh INT;
	DECLARE vDone BOOL;
	DECLARE cTravelTree CURSOR FOR
		SELECT warehouseFk, shipped FROM tmp.agencyHourGetShipped;
			
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
    
	-- Establecemos los almacenes y las fechas que van a entrar al disponible

	SELECT agency_id INTO vAgencyId
		FROM Agencias WHERE Id_Agencia = vAgency;

	CALL vn.agencyHourGetShipped (vDate, vAddress, vAgencyId);
	
	DROP TEMPORARY TABLE IF EXISTS t_bionic_available;
	CREATE TEMPORARY TABLE t_bionic_available(	
		calc_id INT UNSIGNED,
        PRIMARY KEY (calc_id)
	)
	ENGINE = MEMORY;

	OPEN cTravelTree;
	l: LOOP
		SET vDone = FALSE;
		FETCH cTravelTree INTO vWh, vShipment;
        
        IF vDone THEN
			LEAVE l;
		END IF;

		CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWh, vShipment);

		INSERT IGNORE INTO t_bionic_available
			SET calc_id = vAvailableCalc;
    END LOOP;

	CLOSE cTravelTree;    
  	DROP TEMPORARY TABLE tmp.agencyHourGetShipped;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_available_articlelist` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_available_articlelist`(IN strART VARCHAR(50)
                                                                 , IN minMED DOUBLE
                                                                 , IN maxMED DOUBLE
                                                                 , IN minPVP DOUBLE
                                                                 , IN maxPVP DOUBLE)
BEGIN

DECLARE intSPACE_POS INT;
DECLARE strSUBTR VARCHAR(50);
DECLARE strFILTER VARCHAR(500);
DECLARE v_sql TEXT;

DROP TEMPORARY TABLE IF EXISTS articlelist;

CREATE TEMPORARY table articlelist
(Id_Article INT(11) PRIMARY KEY)
ENGINE = INNODB;



-- Arreglos

SET minMED = IFNULL(minMED,0);
SET minMED = IF(minMED = 0,0.01, minMED);
SET maxMED = IFNULL(maxMED,9990);
SET maxMED = IF(maxMED = 0,9990, maxMED);
SET minPVP = IFNULL(minPVP,0);
SET minPVP = IF(minPVP = 0, 0.01, minPVP);
SET maxPVP = IFNULL(maxPVP,9990);
SET maxPVP = IF(maxPVP = 0, 9990, maxPVP);

-- ARTICLE

SET strART = TRIM(strART);

IF ASCII(strART) BETWEEN 48 AND 57 THEN

INSERT INTO articlelist(Id_Article) VALUES(CAST(strART AS UNSIGNED));

ELSE

SET strFILTER = 'TRUE ';

WHILE LENGTH(strART) > 0 DO

SET intSPACE_POS = POSITION(' ' IN strART) ;
IF intSPACE_POS = 0 THEN 
 SET strFILTER = CONCAT(strFILTER, ' AND CONCAT(a.Id_Article,Article,t.Tipo) LIKE "%',strART,'%"');
 SET strART = '';
 
ELSE
 SET strFILTER = CONCAT(strFILTER, ' AND CONCAT(a.Id_Article,Article,t.Tipo) LIKE "%',LEFT(strART,intSPACE_POS - 1),'%"');
 SET strART = TRIM(SUBSTRING(strART, intSPACE_POS));
 
END IF;

 
END WHILE;
    
   
    IF minMED <> 0.01 OR  maxMED <>9990 THEN    
SET strFILTER = CONCAT(strFILTER, ' AND Medida BETWEEN ',minMED,' AND ', maxMED);
    END IF;    
    
   

if minpvp = 0.01 and maxpvp = 9990 then

SET v_sql = sql_printf (
'
REPLACE vn2008.articlelist 
SELECT a.Id_Article
FROM vn2008.Articles a
LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id
WHERE %s ;',strFILTER);
 else
 
  SET v_sql = sql_printf (
'
REPLACE vn2008.articlelist 
SELECT a.Id_Article
FROM vn2008.Articles a
LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id
JOIN (
SELECT DISTINCT Id_Article 
FROM vn2008.Movimientos m 
JOIN vn2008.Tickets t using(Id_Ticket) 
JOIN vn2008.Clientes c using(Id_Cliente)
WHERE Fecha > CURDATE() - INTERVAL 4 DAY
AND Preu BETWEEN  %v   AND   %v
AND c.invoice <> 0
) v on v.Id_Article = a.Id_Article
WHERE %s ;',minPVP,maxPVP,strFILTER);        
end if;
CALL util.exec (v_sql); 
               
END IF;
-- SELECT Id_Article, Article, Medida FROM Articles join articlelist using(Id_Article);

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_available_items_` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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_available_items_`(v_date DATE, --  fecha de recepcion de mercancia
    v_consigna INT,
    v_agencia INT)
BEGIN
/**
 * Crea una tabla con los identificadores de los articulos disponibles. 
 *
 * @table t_bionic_available_items
 **/        
	CALL bionic_available_ (v_date, v_consigna, v_agencia);

	DROP TEMPORARY TABLE IF EXISTS t_bionic_available_items;
	CREATE TEMPORARY TABLE t_bionic_available_items
		(INDEX (Id_Article))
        ENGINE = MEMORY
		SELECT a.Id_Article, a.Article
		FROM `cache`.available c 
			JOIN Articles a ON c.item_id = a.Id_Article
			JOIN t_bionic_available ba ON c.calc_id = ba.calc_id
		WHERE c.available GROUP BY a.Article;

	 DROP TEMPORARY TABLE 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 `bionic_available_single` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_available_single`(IN v_wh TINYINT, IN v_date DATETIME, IN id_single INT, IN refresh TINYINT)
BEGIN
	DECLARE intcalc_id INT;
	call cache.available_refresh(intcalc_id,refresh, v_wh,v_date);	
	
	SELECT available AS minimo FROM cache.available WHERE calc_id = intcalc_id AND item_id = id_single ;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_available_types_` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_available_types_`(
	v_date DATE, --  fecha de recepcion de mercancia
    v_consigna INT,
    v_agencia INT)
BEGIN
/**
 * Calcula los tipos disponibles para un conjunto de almacenes
 * y fechas devueltos por el procedimiento agencyHourGetShipped()
 *
 * @table t_bionic_available_types Tabla con los tipos disponibles
 **/
        
	CALL bionic_available_(v_date, v_consigna, v_agencia);

	DROP TEMPORARY TABLE IF EXISTS t_bionic_available_types;
	CREATE TEMPORARY TABLE t_bionic_available_types
    (INDEX (tipo_id))
    ENGINE = MEMORY
	SELECT a.tipo_id, t.Tipo
		FROM `cache`.available c 
		JOIN Articles a ON c.item_id = a.Id_Article
		JOIN Tipos t ON t.tipo_id = a.tipo_id
		JOIN t_bionic_available ba ON c.calc_id = ba.calc_id
			WHERE c.available > 0 -- JGF 2016-03-23 en el bionic no apareixen negatius, els tipos que no continguen disponible, tampoc els volem mostrar
            AND t.Orden != 0
            GROUP BY t.tipo_id;

	DROP TEMPORARY TABLE 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 `bionic_available_types_filter` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_available_types_filter`(
	v_date DATE,
    v_consigna INT,
    v_agencia INT,
    v_filter TEXT)
BEGIN
/**
 * Este procedimiento devuelve una tabla t_bionic_available_types
 * que debe de ser borrar por quien la llame, y se conecta con la tabla articlelist
 * que tambien hay que eliminar.
 *
 * @param vDatefecha de recepcion de mercancia
 * @table t_bionic_available_types
 */

	DECLARE v_sql TEXT;
	DECLARE v_list TEXT;
	SET v_list = '';

	SET v_filter = IFNULL(v_filter,' TRUE');

	CALL bionic_available_(v_date, v_consigna, v_agencia);
	-- Inroducimos los valores en una tabla temporal
	DROP TEMPORARY TABLE IF EXISTS t_bionic_available_types;

	CALL check_table_existence('articlelist');

	IF @table_exists THEN

	SET v_list = 'JOIN vn2008.articlelist AL ON AL.Id_Article = a.Id_Article ';

	END IF;

	SET v_sql = sql_printf (
		'
	CREATE TEMPORARY TABLE t_bionic_available_types
	SELECT a.tipo_id, Tipo, reino, count(*) as item_count
		FROM `cache`.available c 
			JOIN vn2008.Articles a ON c.item_id = a.Id_Article
			JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id
			JOIN vn2008.reinos r ON r.id = t.reino_id
			JOIN vn2008.t_bionic_available ba ON c.calc_id = ba.calc_id
		%s
	WHERE c.available > 0
	AND %s 
	GROUP BY a.tipo_id;
		'
		, v_list
		, v_filter);

	CALL sql_query (v_sql); 

	 DROP TEMPORARY TABLE 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 `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`(
    vDate DATE, -- Fecha de recepcion de mercancia
    vAddress INT,
    vAgency INT)
proc: BEGIN
-- @DEPRECATED use vn.ticketCalculate
	DECLARE vAvailableCalc INT;
	DECLARE vShipment DATE;
	DECLARE vAgencyId INT;
	DECLARE vCustomer INT;
	DECLARE vWh SMALLINT;
	DECLARE vDone BOOL;
	DECLARE cTravelTree CURSOR FOR
		SELECT warehouseFk, shipped FROM tmp.agencyHourGetShipped;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
	
	DROP TEMPORARY TABLE IF EXISTS
		tmp.bionic_item,
        tmp.bionic_component,
        tmp.bionic_lot,
        tmp.bionic_price;
    
	-- Establece los almacenes y las fechas que van a entrar al disponible

	SELECT agency_id INTO vAgencyId FROM Agencias WHERE Id_Agencia = vAgency;
	SELECT Id_Cliente INTO vCustomer FROM Consignatarios WHERE Id_Consigna = vAddress;

	CALL vn.agencyHourGetShipped(vDate, vAddress, vAgencyId);

	-- Crea la tabla temporal que almacenará los lotes

    CREATE TEMPORARY TABLE tmp.bionic_lot LIKE
		template_bionic_lot;
        
	OPEN cTravelTree;

	l: LOOP
		SET vDone = FALSE;
		FETCH cTravelTree INTO  vWh, vShipment;

		IF vDone THEN 
			LEAVE l;
		END IF;

		CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWh, vShipment);
		CALL item_last_buy_ (vWh, vShipment);

		INSERT INTO tmp.bionic_lot (warehouse_id, item_id, available, buy_id)
		SELECT
			vWh,
			i.item_id,
			IFNULL(i.available, 0),
			ilb.buy_id
				FROM `cache`.available i
					JOIN tmp.bionic_calc br ON br.item_id = i.item_id
					LEFT JOIN Articles a ON a.Id_Article = i.item_id
					LEFT JOIN t_item_last_buy ilb ON ilb.item_id = i.item_id
				WHERE i.calc_id = vAvailableCalc
					AND a.Id_Article != 100	
					AND i.available > 0;
		
		DROP TEMPORARY TABLE t_item_last_buy;
    END LOOP;

	CLOSE cTravelTree;

	CALL bionic_calc_component(vAddress, vAgency);
    
	CREATE TEMPORARY TABLE tmp.bionic_item
	ENGINE = MEMORY
	SELECT b.item_id, SUM(b.available) available, p.name producer,
			a.Article item, a.Medida size, a.Tallos stems, a.Categoria category,
            a.Color, a.Foto image, o.Abreviatura origin, bl.min_price price
		FROM tmp.bionic_lot b
			JOIN Articles a ON b.item_id = a.Id_Article
			LEFT JOIN producer p ON p.producer_id = a.producer_id AND p.visible
			JOIN Origen o ON o.id = a.id_origen
			JOIN (
				SELECT MIN(price) min_price, item_id
					FROM tmp.bionic_price
                    GROUP BY item_id
			) bl ON bl.item_id = b.item_id
		GROUP BY b.item_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 `bionic_calc_clon` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_clon`(IN v_ticket BIGINT)
BEGIN

/*
* DEPRECATED vn.ticketCalculateClon
*
Este procedimiento "rebioniza" una linea, eliminando los componentes existentes e insertandolos de nuevo
*/
	DECLARE v_shipment DATE;
	DECLARE v_customer INT;
	DECLARE v_wh SMALLINT;
    DECLARE v_agencia INT;
    DECLARE v_consigna INT;
	DECLARE v_landing DATE;
    DECLARE v_agency INT;
	
    REPLACE order_Tickets(order_id,Id_Ticket) VALUES(48, v_ticket);
    	
	SELECT t.Id_Cliente , t.warehouse_id, date(t.Fecha), t.Id_Consigna, t.Id_Agencia, t.landing, a.agency_id
    INTO v_customer, v_wh, v_shipment, v_consigna, v_agencia, v_landing, v_agency
    FROM vn2008.Agencias a 
    JOIN vn2008.Tickets t ON t.Id_Agencia = a.Id_Agencia
    WHERE t.Id_Ticket = v_ticket;
    
	DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetShipped;
	CREATE TEMPORARY TABLE tmp.agencyHourGetShipped ENGINE = MEMORY
	SELECT v_wh warehouseFk, v_shipment shipped, v_landing landed;
    
    CALL item_last_buy_ (v_wh, v_shipment);  -- rellena la tabla t_item_last_buy con la ultima compra
    
    DROP TEMPORARY TABLE IF EXISTS tmp.bionic_lot;
    CREATE TEMPORARY TABLE tmp.bionic_lot 
	SELECT v_wh warehouse_id,NULL available,
		m.Id_Article item_id,ilb.buy_id
			FROM Movimientos m
			LEFT JOIN t_item_last_buy ilb ON ilb.item_id = m.Id_Article
				WHERE m.Id_Ticket = v_ticket GROUP BY m.Id_Article;
                
	CALL bionic_calc_component(v_consigna,v_agencia);
    
    -- Bionizamos lineas con Preu = 0
    DROP TEMPORARY TABLE IF EXISTS tmp.movement;
	CREATE TEMPORARY TABLE tmp.movement
				(PRIMARY KEY (Id_Movimiento)) ENGINE = MEMORY
			SELECT Id_Movimiento, v_wh warehouse_id FROM Movimientos m
				JOIN Tickets t on t.Id_Ticket = m.Id_Ticket WHERE m.Id_Ticket =  v_ticket AND Preu = 0;
                
	CALL bionic_movement_update(1);
    
    -- Bionizamos lineas con Preu > 0
	DROP TEMPORARY TABLE IF EXISTS tmp.movement;
	CREATE TEMPORARY TABLE tmp.movement
				(PRIMARY KEY (Id_Movimiento)) ENGINE = MEMORY
			SELECT Id_Movimiento, v_wh warehouse_id FROM Movimientos m 
				JOIN Tickets t on t.Id_Ticket = m.Id_Ticket WHERE m.Id_Ticket =  v_ticket AND Preu > 0;
	CALL bionic_movement_update(6);

	IF v_landing IS NULL THEN
		CALL travel_tree_shipment(v_shipment, v_consigna, v_agency,v_wh);
        UPDATE Tickets t
				JOIN travel_tree_shipment tts ON t.warehouse_id = tts.warehouse_id 
			SET t.landing = tts.landing 
			WHERE Id_Ticket = v_ticket;
    END IF;
	
	-- Log
    call Ditacio(v_ticket
            ,'Bioniza Ticket'
            ,'T' 
            , 20
            , 'proc bionic_calc_clon'
            , NULL);
            
	-- Limpieza
	DROP TEMPORARY TABLE t_item_last_buy;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_component` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `bionic_calc_component`(IN `v_consigna` INT, IN `v_agencia` INT)
proc: BEGIN

	DECLARE v_customer INT;
    DECLARE COEFICIENTE_DE_INFLACION_GENERAL INT DEFAULT 1.0;
    DECLARE DENSIDAD_MINIMA_PESO_VOLUMETRICO INT DEFAULT 167;
    DECLARE VOLUMEN_CAJA_VERDNATURA BIGINT; -- DEFAULT 138000;
    -- DECLARE vValorEmbolsado DOUBLE DEFAULT 0.04;
    
    SELECT Volumen INTO VOLUMEN_CAJA_VERDNATURA
		FROM Cubos
        WHERE Id_Cubo = '94';
        
    SELECT Id_Cliente INTO v_customer FROM Consignatarios WHERE Id_Consigna = v_consigna;
    SET @rate2 := 0;
    SET @rate3 := 0;

	DROP TEMPORARY TABLE IF EXISTS t_bionic_temp;
	CREATE TEMPORARY TABLE t_bionic_temp
	(PRIMARY KEY (item_id,warehouse_id))
	ENGINE = MEMORY
		SELECT 
			b.item_id, b.warehouse_id,available,
			IF((@rate2 := IFNULL(pf.rate_2,c.Tarifa2)) < a.PVP AND a.`Min`, a.PVP, @rate2) * 1.0 rate_2,
			IF((@rate3 := IFNULL(pf.rate_3,c.Tarifa3)) < a.PVP AND a.`Min`, a.PVP, @rate3) * 1.0 rate_3,
            ifnull(pf.rate_3,0) AS min_price,
			IFNULL(pf.Packing,c.Packing) packing,
			IFNULL(pf.`grouping`,c.`grouping`) `grouping`,
			ABS(IFNULL(pf.caja,c.caja)) box,
            b.buy_id, a.tipo_id
        FROM tmp.bionic_lot b 
		JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra
		JOIN vn2008.Articles a ON b.item_id = a.Id_Article
        JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id
        LEFT JOIN vn2008.reinos r ON r.id = t.reino_id
		LEFT JOIN vn2008.PreciosEspeciales p ON a.Id_Article = p.Id_Article AND p.Id_Cliente = v_customer
		LEFT JOIN (
			SELECT * FROM (
				SELECT p.item_id, p.`grouping`, p.Packing,p.caja, p.rate_2, p.rate_3, ah.warehouseFk AS warehouse_id
					FROM vn2008.price_fixed p
					JOIN tmp.agencyHourGetShipped ah ON ah.warehouseFk = p.warehouse_id OR p.warehouse_id = 0 
						WHERE ah.shipped BETWEEN p.date_start AND p.date_end ORDER BY p.item_id, p.warehouse_id DESC
			) t
			GROUP BY item_id, warehouse_id
		) pf ON pf.item_id = b.item_id AND pf.warehouse_id = b.warehouse_id
        -- descartamos articulos con coste menor de 0.01
        WHERE Costefijo + Portefijo + Embalajefijo + Comisionfija > 0.01 AND r.display <> 0;
        
    -- Creamos la tabla tmp.bionic_component
    DROP TEMPORARY TABLE IF EXISTS tmp.bionic_component;
    CREATE TEMPORARY TABLE tmp.bionic_component LIKE
		template_bionic_component;
        
	-- Componentes del precio, valores absolutos
	INSERT INTO tmp.bionic_component ( warehouse_id, item_id, component_id, cost)
	SELECT  b.warehouse_id, b.item_id, 29, rate_3 - Costefijo - Portefijo - Embalajefijo - Comisionfija
		FROM t_bionic_temp b 
        JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra;
	
    INSERT INTO tmp.bionic_component ( warehouse_id, item_id, component_id, cost)
	SELECT  b.warehouse_id, b.item_id, 28, Costefijo + Portefijo + Embalajefijo + Comisionfija
		FROM t_bionic_temp b
        JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra; 

	-- Ahora los valores en funcion de la base

	DROP TEMPORARY TABLE IF EXISTS t_components_base;

	CREATE TEMPORARY TABLE t_components_base
	SELECT bc.item_id, ROUND(SUM(cost), 4) AS base, bc.warehouse_id
		FROM tmp.bionic_component bc
			GROUP BY bc.item_id,warehouse_id;

	-- La ratio se calcula teniendo en cuenta el valor de las reclamaciones y el saldo de greuge
	
	INSERT INTO tmp.bionic_component
	SELECT cb.warehouse_id, item_id, 17, ROUND(base * LEAST(recobro,0.25), 3)
		FROM t_components_base cb
		JOIN bi.claims_ratio ON Id_Cliente = v_customer
			WHERE recobro > 0.009;
            
	-- PAK 2016-08-31  Componente de maná automático, en función del maná acumulado por el comercial.
   
    INSERT INTO tmp.bionic_component
	SELECT cb.warehouse_id, item_id, 39, ROUND(base * (0.01 + prices_modifier_rate), 3) as manaAuto
		FROM t_components_base cb
        JOIN Clientes c on c.Id_Cliente = v_customer
		JOIN bs.mana_spellers ms ON c.Id_Trabajador = ms.Id_Trabajador 
		WHERE ms.prices_modifier_activated
        AND c.Id_Trabajador != 196 -- Ruben Espinosa
        HAVING manaAuto <> 0 ;
      
         
/*      
	-- Vendedor variable
	INSERT INTO tmp.bionic_component
	SELECT  cb.warehouse_id, item_id, Id_Componente, IFNULL(ROUND(base * tax,4), 0)
		FROM t_components_base cb
		JOIN bi.tarifa_componentes
			WHERE tarifa_componentes_series_id = 2 and IFNULL(tax, 0) > 0;
 */  
 
 
-- ******* Inicio Bloque para componentes con tarifa_class diferente de NULL
	-- Descuento por ultimas unidades
	INSERT INTO tmp.bionic_component
	SELECT  cb.warehouse_id, b.item_id, Id_Componente, GREATEST(IFNULL(ROUND(base * tax,4), 0), b.min_price - b.rate_3)
		FROM t_components_base cb
			JOIN bi.tarifa_componentes
			JOIN t_bionic_temp b ON  b.item_id = cb.item_id AND b.warehouse_id = cb.warehouse_id 
			LEFT JOIN PreciosEspeciales pe ON pe.Id_Cliente = v_customer AND pe.Id_Article = b.item_id
		WHERE Id_Componente = 32 AND tax <> 0 AND b.min_price < b.rate_3 AND PrecioEspecial IS NULL;
            
	-- Incremento por paquete suelto
	INSERT INTO tmp.bionic_component
	SELECT b.warehouse_id, b.item_id, 22, rate_2 - rate_3 
		FROM t_bionic_temp b
        JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra
        LEFT JOIN PreciosEspeciales pe ON pe.Id_Cliente = v_customer AND pe.Id_Article = b.item_id
	WHERE PrecioEspecial IS NULL;
 
-- ******* Fin Bloque para componentes con tarifa_class diferente de NULL

	-- Reparto
	INSERT INTO tmp.bionic_component
    SELECT b.warehouse_id
			, b.item_id
            , 15
            , COEFICIENTE_DE_INFLACION_GENERAL
				* ROUND(
						r.cm3  
                        * art.compression
						* IF(a.Vista = 1, (GREATEST(art.density,DENSIDAD_MINIMA_PESO_VOLUMETRICO) / DENSIDAD_MINIMA_PESO_VOLUMETRICO ) , 1)
						* IFNULL(az.price
						* az.inflacion ,50)
						/ VOLUMEN_CAJA_VERDNATURA, 4
						) cost
    FROM t_bionic_temp b
		JOIN vn2008.Articles art ON art.Id_Article = b.item_id
		JOIN vn2008.Agencias a ON a.Id_Agencia = v_agencia
        JOIN vn2008.Consignatarios c ON c.Id_Consigna = v_consigna
		JOIN vn2008.Agencias_province ap ON ap.agency_id = a.agency_id AND ap.warehouse_id = b.warehouse_id AND ap.province_id = c.province_id
        JOIN vn2008.Agencias_zonas az ON az.Id_Agencia = v_agencia AND az.zona = ap.zona AND az.Id_Article = 71 AND az.warehouse_id = b.warehouse_id
		LEFT JOIN bi.rotacion r ON r.warehouse_id = b.warehouse_id AND r.Id_Article = b.item_id
		HAVING cost <> 0;
	
-- Reparto bonificado
	INSERT INTO tmp.bionic_component
    SELECT b.warehouse_id
			, b.item_id
            , 41
            , COEFICIENTE_DE_INFLACION_GENERAL
				* ROUND(
						r.cm3 
                        * art.compression
						* IF(a.Vista = 1, (GREATEST(art.density,DENSIDAD_MINIMA_PESO_VOLUMETRICO) / DENSIDAD_MINIMA_PESO_VOLUMETRICO ) , 1)
						* awb.bonus 
						* az.inflacion 
						/ VOLUMEN_CAJA_VERDNATURA, 4
						) cost
    FROM t_bionic_temp b
		JOIN vn2008.Articles art ON art.Id_Article = b.item_id
		JOIN vn2008.Agencias a ON a.Id_Agencia = v_agencia
        JOIN vn2008.Consignatarios c ON c.Id_Consigna = v_consigna
		JOIN vn2008.Agencias_province ap ON ap.agency_id = a.agency_id AND ap.warehouse_id = b.warehouse_id AND ap.province_id = c.province_id
        JOIN vn2008.Agencias_zonas az ON az.Id_Agencia = v_agencia AND az.zona = ap.zona AND az.Id_Article = 71 AND az.warehouse_id = b.warehouse_id
		JOIN vn2008.agency_weekday_bonus awb ON awb.warehouse_id = az.warehouse_id AND awb.zona = az.zona AND a.agency_id = awb.agency_id
        LEFT JOIN bi.rotacion r ON r.warehouse_id = b.warehouse_id AND r.Id_Article = b.item_id
        JOIN tmp.agencyHourGetShipped ah ON ah.warehouseFk = awb.warehouse_id AND weekday(ah.landed) = awb.weekDay
		HAVING cost <> 0
        LIMIT 1;
      
-- PAK 12-05-2015
    -- EMBOLSADO 
    IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = v_consigna) THEN
    
    -- IF v_consigna IN (13690, 3402, 5661, 4233) THEN
   
		INSERT INTO tmp.bionic_component
			SELECT b.warehouse_id, b.item_id, 38, ap.packagingValue cost
				FROM t_bionic_temp b
					JOIN vn.addressForPackaging ap
				WHERE ap.addressFk = v_consigna;
        
    END IF;
    
	-- JGF 14-08-2015 
	-- Modificacion de precio por dia de preparacion del pedido
	INSERT INTO tmp.bionic_component
	SELECT cb.warehouse_id, cb.item_id, 14, cb.base * (IFNULL(pe.percentage,pp.percentage)/100)
		FROM t_components_base cb
		JOIN tmp.agencyHourGetShipped ah ON ah.warehouseFk = cb.warehouse_id
        LEFT JOIN vn2008.preparation_percentage pp ON pp.week_day = weekday(ah.shipped) AND cb.warehouse_id = IFNULL(pp.warehouse_id,cb.warehouse_id)
        LEFT JOIN vn2008.preparation_exception pe ON pe.exception_day = ah.shipped AND cb.warehouse_id = IFNULL(pe.warehouse_id,cb.warehouse_id)
	WHERE IFNULL(pe.percentage,pp.percentage);

	-- Creamos la tabla tmp.bionic_component_copy por que mysql no puede reabrir una tabla temporal
    DROP TEMPORARY TABLE IF EXISTS tmp.bionic_component_copy;
    CREATE TEMPORARY TABLE tmp.bionic_component_copy
		SELECT * FROM tmp.bionic_component;
        
	-- JGF 19-01-2016 
	-- Precios especiales
	INSERT INTO tmp.bionic_component
	SELECT b.warehouse_id, b.item_id, 10, pe.PrecioEspecial - SUM(cost) sum_cost
			FROM tmp.bionic_component_copy b
				JOIN bi.tarifa_componentes t ON b.component_id = t.Id_Componente
				JOIN PreciosEspeciales pe ON pe.Id_Cliente = v_customer AND pe.Id_Article = b.item_id
			WHERE t.tarifa_class IS NULL
			GROUP BY b.item_id, b.warehouse_id
			HAVING ABS(sum_cost) > 0.001;

	-- Lotes
	DROP TEMPORARY TABLE IF EXISTS t_component_sum;
	CREATE TEMPORARY TABLE t_component_sum
	(INDEX (item_id, warehouse_id))
	ENGINE = MEMORY
	SELECT SUM(cost) sum_cost, b.item_id, b.warehouse_id, t.tarifa_class
			FROM tmp.bionic_component b
			JOIN bi.tarifa_componentes t ON b.component_id = t.Id_Componente
				GROUP BY b.item_id, b.warehouse_id, t.tarifa_class;
  
  -- ***** Inicia Modifica t_bionic_rate las diferentes tarifas
	-- Tarifa por unidad minima
	DROP TEMPORARY TABLE IF EXISTS t_bionic_rate;
	CREATE TEMPORARY TABLE t_bionic_rate
    ENGINE = MEMORY
		SELECT b.warehouse_id,  item_id, 1 rate,
		IF(box = 1, `grouping`, 1) `grouping`, SUM(sum_cost) price
			FROM t_bionic_temp b
				JOIN t_component_sum cs USING(item_id, warehouse_id)
			WHERE IFNULL(cs.tarifa_class,1) = 1 AND box < 2 AND (packing > `grouping` or box = 0)
			GROUP BY warehouse_id, item_id;

	-- Tarifa por caja
	INSERT INTO t_bionic_rate (warehouse_id, item_id, rate, `grouping`, price)
        SELECT b.warehouse_id, item_id, 2 rate, packing `grouping`,
				SUM(sum_cost) price
			FROM t_bionic_temp b
				JOIN t_component_sum cs USING(item_id, warehouse_id)
			WHERE available IS NULL OR (IFNULL(cs.tarifa_class,2) = 2 AND packing > 0 AND available >= packing)
			GROUP BY warehouse_id, item_id;

	-- Tarifa para toda la cantidad disponible
	INSERT INTO t_bionic_rate (warehouse_id, item_id, rate, `grouping`, price)
		 SELECT b.warehouse_id, item_id, 3 rate, available `grouping`,
				SUM(sum_cost) price
			FROM t_bionic_temp b
				JOIN t_component_sum cs USING(item_id, warehouse_id)
			WHERE IFNULL(cs.tarifa_class,3) = 3 
			GROUP BY warehouse_id, item_id;
            
  -- ***** Fin Modifica t_bionic_rate las diferentes tarifas    
        
	DROP TEMPORARY TABLE IF EXISTS tmp.bionic_price;
	CREATE TEMPORARY TABLE tmp.bionic_price 
		LIKE template_bionic_price;

	INSERT INTO tmp.bionic_price (warehouse_id, item_id, rate, `grouping`, price)
		SELECT * FROM (
			SELECT * FROM t_bionic_rate ORDER BY price
		) t
		GROUP BY item_id, warehouse_id, `grouping`;


	DROP TEMPORARY TABLE IF EXISTS tmp.travel_tree;
	CREATE TEMPORARY TABLE tmp.travel_tree
    ENGINE = MEMORY
		SELECT * FROM tmp.agencyHourGetShipped;
    
	-- Limpieza

	DROP TEMPORARY TABLE tmp.agencyHourGetShipped;
    DROP TEMPORARY TABLE t_bionic_temp;
    DROP TEMPORARY TABLE t_component_sum;
    DROP TEMPORARY TABLE t_components_base;
    DROP TEMPORARY TABLE t_bionic_rate;
    DROP TEMPORARY TABLE tmp.bionic_component_copy;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_componentTest` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `bionic_calc_componentTest`(IN `v_consigna` INT, IN `v_agencia` INT)
proc: BEGIN

	DECLARE v_customer INT;
    DECLARE COEFICIENTE_DE_INFLACION_GENERAL INT DEFAULT 1.3;
    DECLARE DENSIDAD_MINIMA_PESO_VOLUMETRICO INT DEFAULT 167;
    DECLARE VOLUMEN_CAJA_VERDNATURA BIGINT DEFAULT 138000;
    -- DECLARE vValorEmbolsado DOUBLE DEFAULT 0.04;
    
    SELECT Id_Cliente INTO v_customer FROM Consignatarios WHERE Id_Consigna = v_consigna;
    SET @rate2 := 0;
    SET @rate3 := 0;

	DROP TEMPORARY TABLE IF EXISTS t_bionic_temp;
	CREATE TEMPORARY TABLE t_bionic_temp
	(PRIMARY KEY (item_id,warehouse_id))
	ENGINE = MEMORY
		SELECT 
			b.item_id, b.warehouse_id,available,
			IF((@rate2 := IFNULL(pf.rate_2,c.Tarifa2)) < a.PVP AND a.`Min`, a.PVP, @rate2) * 1.0 rate_2,
			IF((@rate3 := IFNULL(pf.rate_3,c.Tarifa3)) < a.PVP AND a.`Min`, a.PVP, @rate3) * 1.0 rate_3,
            ifnull(pf.rate_3,0) AS min_price,
			IFNULL(pf.Packing,c.Packing) packing,
			IFNULL(pf.`grouping`,c.`grouping`) `grouping`,
			ABS(IFNULL(pf.caja,c.caja)) box,
            b.buy_id, a.tipo_id
        FROM tmp.bionic_lot b 
		JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra
		JOIN vn2008.Articles a ON b.item_id = a.Id_Article
        JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id
        LEFT JOIN vn2008.reinos r ON r.id = t.reino_id
		LEFT JOIN vn2008.PreciosEspeciales p ON a.Id_Article = p.Id_Article AND p.Id_Cliente = v_customer
		LEFT JOIN (
			SELECT * FROM (
				SELECT p.item_id, p.`grouping`, p.Packing,p.caja, p.rate_2, p.rate_3, ah.warehouseFk AS warehouse_id
					FROM vn2008.price_fixed p
					JOIN tmp.agencyHourGetShipped ah ON ah.warehouseFk = p.warehouse_id OR p.warehouse_id = 0 
						WHERE ah.shipped BETWEEN p.date_start AND p.date_end ORDER BY p.item_id, p.warehouse_id DESC
			) t
			GROUP BY item_id, warehouse_id
		) pf ON pf.item_id = b.item_id AND pf.warehouse_id = b.warehouse_id
        -- descartamos articulos con coste menor de 0.01
        WHERE Costefijo + Portefijo + Embalajefijo + Comisionfija > 0.01 AND r.display <> 0;
        
    -- Creamos la tabla tmp.bionic_component
    DROP TEMPORARY TABLE IF EXISTS tmp.bionic_component;
    CREATE TEMPORARY TABLE tmp.bionic_component LIKE
		template_bionic_component;
        
	-- Componentes del precio, valores absolutos
	INSERT INTO tmp.bionic_component ( warehouse_id, item_id, component_id, cost)
	SELECT  b.warehouse_id, b.item_id, 29, rate_3 - Costefijo - Portefijo - Embalajefijo - Comisionfija
		FROM t_bionic_temp b 
        JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra;
	
    INSERT INTO tmp.bionic_component ( warehouse_id, item_id, component_id, cost)
	SELECT  b.warehouse_id, b.item_id, 28, Costefijo + Portefijo + Embalajefijo + Comisionfija
		FROM t_bionic_temp b
        JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra; 

	-- Ahora los valores en funcion de la base

	DROP TEMPORARY TABLE IF EXISTS t_components_base;

	CREATE TEMPORARY TABLE t_components_base
	SELECT bc.item_id, ROUND(SUM(cost), 4) AS base, bc.warehouse_id
		FROM tmp.bionic_component bc
			GROUP BY bc.item_id,warehouse_id;

	-- La ratio se calcula teniendo en cuenta el valor de las reclamaciones y el saldo de greuge
	
	INSERT INTO tmp.bionic_component
	SELECT cb.warehouse_id, item_id, 17, ROUND(base * LEAST(recobro,0.25), 3)
		FROM t_components_base cb
		JOIN bi.claims_ratio ON Id_Cliente = v_customer
			WHERE recobro > 0.009;
            
	-- PAK 2016-08-31  Componente de maná automático, en función del maná acumulado por el comercial.
   
    INSERT INTO tmp.bionic_component
	SELECT cb.warehouse_id, item_id, 39, ROUND(base * (0.01 + prices_modifier_rate), 3) as manaAuto
		FROM t_components_base cb
        JOIN Clientes c on c.Id_Cliente = v_customer
		JOIN bs.mana_spellers ms ON c.Id_Trabajador = ms.Id_Trabajador 
		WHERE ms.prices_modifier_activated
        AND c.Id_Trabajador != 196 -- Ruben Espinosa
        HAVING manaAuto <> 0 ;
      
         
/*      
	-- Vendedor variable
	INSERT INTO tmp.bionic_component
	SELECT  cb.warehouse_id, item_id, Id_Componente, IFNULL(ROUND(base * tax,4), 0)
		FROM t_components_base cb
		JOIN bi.tarifa_componentes
			WHERE tarifa_componentes_series_id = 2 and IFNULL(tax, 0) > 0;
 */  
 
 
-- ******* Inicio Bloque para componentes con tarifa_class diferente de NULL
	-- Descuento por ultimas unidades
	INSERT INTO tmp.bionic_component
	SELECT  cb.warehouse_id, b.item_id, Id_Componente, GREATEST(IFNULL(ROUND(base * tax,4), 0), b.min_price - b.rate_3)
		FROM t_components_base cb
			JOIN bi.tarifa_componentes
			JOIN t_bionic_temp b ON  b.item_id = cb.item_id AND b.warehouse_id = cb.warehouse_id 
			LEFT JOIN PreciosEspeciales pe ON pe.Id_Cliente = v_customer AND pe.Id_Article = b.item_id
		WHERE Id_Componente = 32 AND tax <> 0 AND b.min_price < b.rate_3 AND PrecioEspecial IS NULL;
            
	-- Incremento por paquete suelto
	INSERT INTO tmp.bionic_component
	SELECT b.warehouse_id, b.item_id, 22, rate_2 - rate_3 
		FROM t_bionic_temp b
        JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra
        LEFT JOIN PreciosEspeciales pe ON pe.Id_Cliente = v_customer AND pe.Id_Article = b.item_id
	WHERE PrecioEspecial IS NULL;
 
-- ******* Fin Bloque para componentes con tarifa_class diferente de NULL

	-- Reparto
	INSERT INTO tmp.bionic_component
    SELECT b.warehouse_id
			, b.item_id
            , 15
            , COEFICIENTE_DE_INFLACION_GENERAL
				* ROUND(
						r.cm3  
                        * art.compression
						* IF(a.Vista = 1, (GREATEST(art.density,DENSIDAD_MINIMA_PESO_VOLUMETRICO) / DENSIDAD_MINIMA_PESO_VOLUMETRICO ) , 1)
						* IFNULL(az.price
						* az.inflacion ,50)
						/ VOLUMEN_CAJA_VERDNATURA, 4
						) cost
    FROM t_bionic_temp b
		JOIN vn2008.Articles art ON art.Id_Article = b.item_id
		JOIN vn2008.Agencias a ON a.Id_Agencia = v_agencia
        JOIN vn2008.Consignatarios c ON c.Id_Consigna = v_consigna
		JOIN vn2008.Agencias_province ap ON ap.agency_id = a.agency_id AND ap.warehouse_id = b.warehouse_id AND ap.province_id = c.province_id
        JOIN vn2008.Agencias_zonas az ON az.Id_Agencia = v_agencia AND az.zona = ap.zona AND az.Id_Article = 71 AND az.warehouse_id = b.warehouse_id
		LEFT JOIN bi.rotacion r ON r.warehouse_id = b.warehouse_id AND r.Id_Article = b.item_id
		HAVING cost <> 0;
	
-- Reparto bonificado
	INSERT INTO tmp.bionic_component
    SELECT b.warehouse_id
			, b.item_id
            , 41
            , COEFICIENTE_DE_INFLACION_GENERAL
				* ROUND(
						r.cm3 
                        * art.compression
						* IF(a.Vista = 1, (GREATEST(art.density,DENSIDAD_MINIMA_PESO_VOLUMETRICO) / DENSIDAD_MINIMA_PESO_VOLUMETRICO ) , 1)
						* awb.bonus 
						* az.inflacion 
						/ VOLUMEN_CAJA_VERDNATURA, 4
						) cost
    FROM t_bionic_temp b
		JOIN vn2008.Articles art ON art.Id_Article = b.item_id
		JOIN vn2008.Agencias a ON a.Id_Agencia = v_agencia
        JOIN vn2008.Consignatarios c ON c.Id_Consigna = v_consigna
		JOIN vn2008.Agencias_province ap ON ap.agency_id = a.agency_id AND ap.warehouse_id = b.warehouse_id AND ap.province_id = c.province_id
        JOIN vn2008.Agencias_zonas az ON az.Id_Agencia = v_agencia AND az.zona = ap.zona AND az.Id_Article = 71 AND az.warehouse_id = b.warehouse_id
		JOIN vn2008.agency_weekday_bonus awb ON awb.warehouse_id = az.warehouse_id AND awb.zona = az.zona AND a.agency_id = awb.agency_id
        LEFT JOIN bi.rotacion r ON r.warehouse_id = b.warehouse_id AND r.Id_Article = b.item_id
        JOIN tmp.agencyHourGetShipped ah ON ah.warehouseFk = awb.warehouse_id AND weekday(ah.landed) = awb.weekDay
		HAVING cost <> 0
        LIMIT 1;
      
-- PAK 12-05-2015
    -- EMBOLSADO 
    IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = v_consigna) THEN
    
    -- IF v_consigna IN (13690, 3402, 5661, 4233) THEN
   
		INSERT INTO tmp.bionic_component
			SELECT b.warehouse_id, b.item_id, 38, ap.packagingValue cost
				FROM t_bionic_temp b
					JOIN vn.addressForPackaging ap
				WHERE ap.addressFk = v_consigna;
        
    END IF;
    
	-- JGF 14-08-2015 
	-- Modificacion de precio por dia de preparacion del pedido
	INSERT INTO tmp.bionic_component
	SELECT cb.warehouse_id, cb.item_id, 14, cb.base * (IFNULL(pe.percentage,pp.percentage)/100)
		FROM t_components_base cb
		JOIN tmp.agencyHourGetShipped ah ON ah.warehouseFk = cb.warehouse_id
        LEFT JOIN vn2008.preparation_percentage pp ON pp.week_day = weekday(ah.shipped) AND cb.warehouse_id = IFNULL(pp.warehouse_id,cb.warehouse_id)
        LEFT JOIN vn2008.preparation_exception pe ON pe.exception_day = ah.shipped AND cb.warehouse_id = IFNULL(pe.warehouse_id,cb.warehouse_id)
	WHERE IFNULL(pe.percentage,pp.percentage);

	-- Creamos la tabla tmp.bionic_component_copy por que mysql no puede reabrir una tabla temporal
    DROP TEMPORARY TABLE IF EXISTS tmp.bionic_component_copy;
    CREATE TEMPORARY TABLE tmp.bionic_component_copy
		SELECT * FROM tmp.bionic_component;
        
	-- JGF 19-01-2016 
	-- Precios especiales
	INSERT INTO tmp.bionic_component
	SELECT b.warehouse_id, b.item_id, 10, pe.PrecioEspecial - SUM(cost) sum_cost
			FROM tmp.bionic_component_copy b
				JOIN bi.tarifa_componentes t ON b.component_id = t.Id_Componente
				JOIN PreciosEspeciales pe ON pe.Id_Cliente = v_customer AND pe.Id_Article = b.item_id
			WHERE t.tarifa_class IS NULL
			GROUP BY b.item_id, b.warehouse_id
			HAVING ABS(sum_cost) > 0.001;

	-- Lotes
	DROP TEMPORARY TABLE IF EXISTS t_component_sum;
	CREATE TEMPORARY TABLE t_component_sum
	(INDEX (item_id, warehouse_id))
	ENGINE = MEMORY
	SELECT SUM(cost) sum_cost, b.item_id, b.warehouse_id, t.tarifa_class
			FROM tmp.bionic_component b
			JOIN bi.tarifa_componentes t ON b.component_id = t.Id_Componente
				GROUP BY b.item_id, b.warehouse_id, t.tarifa_class;
  
  -- ***** Inicia Modifica t_bionic_rate las diferentes tarifas
	-- Tarifa por unidad minima
	DROP TEMPORARY TABLE IF EXISTS t_bionic_rate;
	CREATE TEMPORARY TABLE t_bionic_rate
    ENGINE = MEMORY
		SELECT b.warehouse_id,  item_id, 1 rate,
		IF(box = 1, `grouping`, 1) `grouping`, SUM(sum_cost) price
			FROM t_bionic_temp b
				JOIN t_component_sum cs USING(item_id, warehouse_id)
			WHERE IFNULL(cs.tarifa_class,1) = 1 AND box < 2 AND (packing > `grouping` or box = 0)
			GROUP BY warehouse_id, item_id;

	-- Tarifa por caja
	INSERT INTO t_bionic_rate (warehouse_id, item_id, rate, `grouping`, price)
        SELECT b.warehouse_id, item_id, 2 rate, packing `grouping`,
				SUM(sum_cost) price
			FROM t_bionic_temp b
				JOIN t_component_sum cs USING(item_id, warehouse_id)
			WHERE available IS NULL OR (IFNULL(cs.tarifa_class,2) = 2 AND packing > 0 AND available >= packing)
			GROUP BY warehouse_id, item_id;

	-- Tarifa para toda la cantidad disponible
	INSERT INTO t_bionic_rate (warehouse_id, item_id, rate, `grouping`, price)
		 SELECT b.warehouse_id, item_id, 3 rate, available `grouping`,
				SUM(sum_cost) price
			FROM t_bionic_temp b
				JOIN t_component_sum cs USING(item_id, warehouse_id)
			WHERE IFNULL(cs.tarifa_class,3) = 3 
			GROUP BY warehouse_id, item_id;
            
  -- ***** Fin Modifica t_bionic_rate las diferentes tarifas    
        
	DROP TEMPORARY TABLE IF EXISTS tmp.bionic_price;
	CREATE TEMPORARY TABLE tmp.bionic_price 
		LIKE template_bionic_price;

	INSERT INTO tmp.bionic_price (warehouse_id, item_id, rate, `grouping`, price)
		SELECT * FROM (
			SELECT * FROM t_bionic_rate ORDER BY price
		) t
		GROUP BY item_id, warehouse_id, `grouping`;


	DROP TEMPORARY TABLE IF EXISTS tmp.travel_tree;
	CREATE TEMPORARY TABLE tmp.travel_tree
    ENGINE = MEMORY
		SELECT * FROM tmp.agencyHourGetShipped;
    
	-- Limpieza

	DROP TEMPORARY TABLE tmp.agencyHourGetShipped;
    DROP TEMPORARY TABLE t_bionic_temp;
    DROP TEMPORARY TABLE t_component_sum;
    DROP TEMPORARY TABLE t_components_base;
    DROP TEMPORARY TABLE t_bionic_rate;
    DROP TEMPORARY TABLE tmp.bionic_component_copy;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_component_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `bionic_calc_component_beta`(IN `v_consigna` INT, IN `v_agencia` INT)
proc: BEGIN

	DECLARE v_customer INT;
    DECLARE COEFICIENTE_DE_INFLACION_GENERAL INT DEFAULT 1.3;
    DECLARE DENSIDAD_MINIMA_PESO_VOLUMETRICO INT DEFAULT 167;
    DECLARE VOLUMEN_CAJA_VERDNATURA BIGINT;
    -- DECLARE vValorEmbolsado DOUBLE DEFAULT 0.04;
    
    
    SELECT Volumen INTO VOLUMEN_CAJA_VERDNATURA
		FROM Cubos
        WHERE Id_Cubo = 94;
        
    SELECT Id_Cliente INTO v_customer FROM Consignatarios WHERE Id_Consigna = v_consigna;
    SET @rate2 := 0;
    SET @rate3 := 0;

	DROP TEMPORARY TABLE IF EXISTS t_bionic_temp;
	CREATE TEMPORARY TABLE t_bionic_temp
	(PRIMARY KEY (item_id,warehouse_id))
	ENGINE = MEMORY
		SELECT 
			b.item_id, b.warehouse_id,available,
			IF((@rate2 := IFNULL(pf.rate_2,c.Tarifa2)) < a.PVP AND a.`Min`, a.PVP, @rate2) * 1.0 rate_2,
			IF((@rate3 := IFNULL(pf.rate_3,c.Tarifa3)) < a.PVP AND a.`Min`, a.PVP, @rate3) * 1.0 rate_3,
            ifnull(pf.rate_3,0) AS min_price,
			IFNULL(pf.Packing,c.Packing) packing,
			IFNULL(pf.`grouping`,c.`grouping`) `grouping`,
			ABS(IFNULL(pf.caja,c.caja)) box,
            b.buy_id, a.tipo_id
        FROM tmp.bionic_lot b 
		JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra
		JOIN vn2008.Articles a ON b.item_id = a.Id_Article
        JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id
        LEFT JOIN vn2008.reinos r ON r.id = t.reino_id
		LEFT JOIN vn2008.PreciosEspeciales p ON a.Id_Article = p.Id_Article AND p.Id_Cliente = v_customer
		LEFT JOIN (
			SELECT * FROM (
				SELECT p.item_id, p.`grouping`, p.Packing,p.caja, p.rate_2, p.rate_3, ah.warehouseFk AS warehouse_id
					FROM vn2008.price_fixed p
					JOIN tmp.agencyHourGetShipped ah ON ah.warehouseFk = p.warehouse_id OR p.warehouse_id = 0 
						WHERE ah.shipped BETWEEN p.date_start AND p.date_end ORDER BY p.item_id, p.warehouse_id DESC
			) t
			GROUP BY item_id, warehouse_id
		) pf ON pf.item_id = b.item_id AND pf.warehouse_id = b.warehouse_id
        -- descartamos articulos con coste menor de 0.01
        WHERE Costefijo + Portefijo + Embalajefijo + Comisionfija > 0.01 AND r.display <> 0;
        
    -- Creamos la tabla tmp.bionic_component
    DROP TEMPORARY TABLE IF EXISTS tmp.bionic_component;
    CREATE TEMPORARY TABLE tmp.bionic_component LIKE
		template_bionic_component;
        
	-- Componentes del precio, valores absolutos
	INSERT INTO tmp.bionic_component ( warehouse_id, item_id, component_id, cost)
	SELECT  b.warehouse_id, b.item_id, 29, rate_3 - Costefijo - Portefijo - Embalajefijo - Comisionfija
		FROM t_bionic_temp b 
        JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra;
	
    INSERT INTO tmp.bionic_component ( warehouse_id, item_id, component_id, cost)
	SELECT  b.warehouse_id, b.item_id, 28, Costefijo + Portefijo + Embalajefijo + Comisionfija
		FROM t_bionic_temp b
        JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra; 

	-- Ahora los valores en funcion de la base

	DROP TEMPORARY TABLE IF EXISTS t_components_base;

	CREATE TEMPORARY TABLE t_components_base
	SELECT bc.item_id, ROUND(SUM(cost), 4) AS base, bc.warehouse_id
		FROM tmp.bionic_component bc
			GROUP BY bc.item_id,warehouse_id;

	-- La ratio se calcula teniendo en cuenta el valor de las reclamaciones y el saldo de greuge
	
	INSERT INTO tmp.bionic_component
	SELECT cb.warehouse_id, item_id, 17, ROUND(base * LEAST(recobro,0.25), 3)
		FROM t_components_base cb
		JOIN bi.claims_ratio ON Id_Cliente = v_customer
			WHERE recobro > 0.009;
            
	-- PAK 2016-08-31  Componente de maná automático, en función del maná acumulado por el comercial.
   
    INSERT INTO tmp.bionic_component
	SELECT cb.warehouse_id, item_id, 39, ROUND(base * (0.01 + prices_modifier_rate), 3) as manaAuto
		FROM t_components_base cb
        JOIN Clientes c on c.Id_Cliente = v_customer
		JOIN bs.mana_spellers ms ON c.Id_Trabajador = ms.Id_Trabajador 
		WHERE ms.prices_modifier_activated
        AND c.Id_Trabajador != 196 -- Ruben Espinosa
        HAVING manaAuto <> 0 ;
      
         
/*      
	-- Vendedor variable
	INSERT INTO tmp.bionic_component
	SELECT  cb.warehouse_id, item_id, Id_Componente, IFNULL(ROUND(base * tax,4), 0)
		FROM t_components_base cb
		JOIN bi.tarifa_componentes
			WHERE tarifa_componentes_series_id = 2 and IFNULL(tax, 0) > 0;
 */  
 
 
-- ******* Inicio Bloque para componentes con tarifa_class diferente de NULL
	-- Descuento por ultimas unidades
	INSERT INTO tmp.bionic_component
	SELECT  cb.warehouse_id, b.item_id, Id_Componente, GREATEST(IFNULL(ROUND(base * tax,4), 0), b.min_price - b.rate_3)
		FROM t_components_base cb
			JOIN bi.tarifa_componentes
			JOIN t_bionic_temp b ON  b.item_id = cb.item_id AND b.warehouse_id = cb.warehouse_id 
			LEFT JOIN PreciosEspeciales pe ON pe.Id_Cliente = v_customer AND pe.Id_Article = b.item_id
		WHERE Id_Componente = 32 AND tax <> 0 AND b.min_price < b.rate_3 AND PrecioEspecial IS NULL;
            
	-- Incremento por paquete suelto
	INSERT INTO tmp.bionic_component
	SELECT b.warehouse_id, b.item_id, 22, rate_2 - rate_3 
		FROM t_bionic_temp b
        JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra
        LEFT JOIN PreciosEspeciales pe ON pe.Id_Cliente = v_customer AND pe.Id_Article = b.item_id
	WHERE PrecioEspecial IS NULL;
 
-- ******* Fin Bloque para componentes con tarifa_class diferente de NULL

	-- Reparto
	INSERT INTO tmp.bionic_component
    SELECT b.warehouse_id
			, b.item_id
            , 15
            , COEFICIENTE_DE_INFLACION_GENERAL
				* ROUND(
						r.cm3  
                        * art.compression
						* IF(a.Vista = 1, (GREATEST(art.density,DENSIDAD_MINIMA_PESO_VOLUMETRICO) / DENSIDAD_MINIMA_PESO_VOLUMETRICO ) , 1)
						* IFNULL(az.price
						* az.inflacion ,50)
						/ VOLUMEN_CAJA_VERDNATURA, 4
						) cost
    FROM t_bionic_temp b
		JOIN vn2008.Articles art ON art.Id_Article = b.item_id
		JOIN vn2008.Agencias a ON a.Id_Agencia = v_agencia
        JOIN vn2008.Consignatarios c ON c.Id_Consigna = v_consigna
		JOIN vn2008.Agencias_province ap ON ap.agency_id = a.agency_id AND ap.warehouse_id = b.warehouse_id AND ap.province_id = c.province_id
        JOIN vn2008.Agencias_zonas az ON az.Id_Agencia = v_agencia AND az.zona = ap.zona AND az.Id_Article = 71 AND az.warehouse_id = b.warehouse_id
		LEFT JOIN bi.rotacion r ON r.warehouse_id = b.warehouse_id AND r.Id_Article = b.item_id
		HAVING cost <> 0;
	
-- Reparto bonificado
	INSERT INTO tmp.bionic_component
    SELECT b.warehouse_id
			, b.item_id
            , 41
            , COEFICIENTE_DE_INFLACION_GENERAL
				* ROUND(
						r.cm3 
                        * art.compression
						* IF(a.Vista = 1, (GREATEST(art.density,DENSIDAD_MINIMA_PESO_VOLUMETRICO) / DENSIDAD_MINIMA_PESO_VOLUMETRICO ) , 1)
						* awb.bonus 
						* az.inflacion 
						/ VOLUMEN_CAJA_VERDNATURA, 4
						) cost
    FROM t_bionic_temp b
		JOIN vn2008.Articles art ON art.Id_Article = b.item_id
		JOIN vn2008.Agencias a ON a.Id_Agencia = v_agencia
        JOIN vn2008.Consignatarios c ON c.Id_Consigna = v_consigna
		JOIN vn2008.Agencias_province ap ON ap.agency_id = a.agency_id AND ap.warehouse_id = b.warehouse_id AND ap.province_id = c.province_id
        JOIN vn2008.Agencias_zonas az ON az.Id_Agencia = v_agencia AND az.zona = ap.zona AND az.Id_Article = 71 AND az.warehouse_id = b.warehouse_id
		JOIN vn2008.agency_weekday_bonus awb ON awb.warehouse_id = az.warehouse_id AND awb.zona = az.zona AND a.agency_id = awb.agency_id
        LEFT JOIN bi.rotacion r ON r.warehouse_id = b.warehouse_id AND r.Id_Article = b.item_id
        JOIN tmp.agencyHourGetShipped ah ON ah.warehouseFk = awb.warehouse_id AND weekday(ah.landed) = awb.weekDay
		HAVING cost <> 0
        LIMIT 1;
      
-- PAK 12-05-2015
    -- EMBOLSADO 
    IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = v_consigna) THEN
    
    -- IF v_consigna IN (13690, 3402, 5661, 4233) THEN
   
		INSERT INTO tmp.bionic_component
			SELECT b.warehouse_id, b.item_id, 38, ap.packagingValue cost
				FROM t_bionic_temp b
					JOIN vn.addressForPackaging ap
				WHERE ap.addressFk = v_consigna;
        
    END IF;
    
	-- JGF 14-08-2015 
	-- Modificacion de precio por dia de preparacion del pedido
	INSERT INTO tmp.bionic_component
	SELECT cb.warehouse_id, cb.item_id, 14, cb.base * (IFNULL(pe.percentage,pp.percentage)/100)
		FROM t_components_base cb
		JOIN tmp.agencyHourGetShipped ah ON ah.warehouseFk = cb.warehouse_id
        LEFT JOIN vn2008.preparation_percentage pp ON pp.week_day = weekday(ah.shipped) AND cb.warehouse_id = IFNULL(pp.warehouse_id,cb.warehouse_id)
        LEFT JOIN vn2008.preparation_exception pe ON pe.exception_day = ah.shipped AND cb.warehouse_id = IFNULL(pe.warehouse_id,cb.warehouse_id)
	WHERE IFNULL(pe.percentage,pp.percentage);

	-- Creamos la tabla tmp.bionic_component_copy por que mysql no puede reabrir una tabla temporal
    DROP TEMPORARY TABLE IF EXISTS tmp.bionic_component_copy;
    CREATE TEMPORARY TABLE tmp.bionic_component_copy
		SELECT * FROM tmp.bionic_component;
        
	-- JGF 19-01-2016 
	-- Precios especiales
	INSERT INTO tmp.bionic_component
	SELECT b.warehouse_id, b.item_id, 10, pe.PrecioEspecial - SUM(cost) sum_cost
			FROM tmp.bionic_component_copy b
				JOIN bi.tarifa_componentes t ON b.component_id = t.Id_Componente
				JOIN PreciosEspeciales pe ON pe.Id_Cliente = v_customer AND pe.Id_Article = b.item_id
			WHERE t.tarifa_class IS NULL
			GROUP BY b.item_id, b.warehouse_id
			HAVING ABS(sum_cost) > 0.001;

	-- Lotes
	DROP TEMPORARY TABLE IF EXISTS t_component_sum;
	CREATE TEMPORARY TABLE t_component_sum
	(INDEX (item_id, warehouse_id))
	ENGINE = MEMORY
	SELECT SUM(cost) sum_cost, b.item_id, b.warehouse_id, t.tarifa_class
			FROM tmp.bionic_component b
			JOIN bi.tarifa_componentes t ON b.component_id = t.Id_Componente
				GROUP BY b.item_id, b.warehouse_id, t.tarifa_class;
  
  -- ***** Inicia Modifica t_bionic_rate las diferentes tarifas
	-- Tarifa por unidad minima
	DROP TEMPORARY TABLE IF EXISTS t_bionic_rate;
	CREATE TEMPORARY TABLE t_bionic_rate
    ENGINE = MEMORY
		SELECT b.warehouse_id,  item_id, 1 rate,
		IF(box = 1, `grouping`, 1) `grouping`, SUM(sum_cost) price
			FROM t_bionic_temp b
				JOIN t_component_sum cs USING(item_id, warehouse_id)
			WHERE IFNULL(cs.tarifa_class,1) = 1 AND box < 2 AND (packing > `grouping` or box = 0)
			GROUP BY warehouse_id, item_id;

	-- Tarifa por caja
	INSERT INTO t_bionic_rate (warehouse_id, item_id, rate, `grouping`, price)
        SELECT b.warehouse_id, item_id, 2 rate, packing `grouping`,
				SUM(sum_cost) price
			FROM t_bionic_temp b
				JOIN t_component_sum cs USING(item_id, warehouse_id)
			WHERE available IS NULL OR (IFNULL(cs.tarifa_class,2) = 2 AND packing > 0 AND available >= packing)
			GROUP BY warehouse_id, item_id;

	-- Tarifa para toda la cantidad disponible
	INSERT INTO t_bionic_rate (warehouse_id, item_id, rate, `grouping`, price)
		 SELECT b.warehouse_id, item_id, 3 rate, available `grouping`,
				SUM(sum_cost) price
			FROM t_bionic_temp b
				JOIN t_component_sum cs USING(item_id, warehouse_id)
			WHERE IFNULL(cs.tarifa_class,3) = 3 
			GROUP BY warehouse_id, item_id;
            
  -- ***** Fin Modifica t_bionic_rate las diferentes tarifas    
        
	DROP TEMPORARY TABLE IF EXISTS tmp.bionic_price;
	CREATE TEMPORARY TABLE tmp.bionic_price 
		LIKE template_bionic_price;

	INSERT INTO tmp.bionic_price (warehouse_id, item_id, rate, `grouping`, price)
		SELECT * FROM (
			SELECT * FROM t_bionic_rate ORDER BY price
		) t
		GROUP BY item_id, warehouse_id, `grouping`;


	DROP TEMPORARY TABLE IF EXISTS tmp.travel_tree;
	CREATE TEMPORARY TABLE tmp.travel_tree
    ENGINE = MEMORY
		SELECT * FROM tmp.agencyHourGetShipped;
    
	-- Limpieza

	DROP TEMPORARY TABLE tmp.agencyHourGetShipped;
    DROP TEMPORARY TABLE t_bionic_temp;
    DROP TEMPORARY TABLE t_component_sum;
    DROP TEMPORARY TABLE t_components_base;
    DROP TEMPORARY TABLE t_bionic_rate;
    DROP TEMPORARY TABLE tmp.bionic_component_copy;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_dateKk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_dateKk`(v_ticket INT)
proc: BEGIN
/**
 * Este procedimiento asigna la fecha de llegada correcta a un ticket.
 *
 * @param v_ticket Id del ticket
 **/
    DECLARE v_shipment DATE;
	DECLARE v_agency_id INT;  
	DECLARE v_wh SMALLINT;
    DECLARE v_province INT;
    DECLARE v_landing DATE;

    SELECT agency_id, DATE(Fecha), t.warehouse_id, province_id
		INTO v_agency_id, v_shipment, v_wh, v_province
		FROM Tickets t
			JOIN Consignatarios c ON c.Id_Consigna = t.Id_Consigna
			JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia
		WHERE Id_Ticket = v_ticket;

 	SELECT landing INTO v_landing FROM (
		SELECT
			@d := TIMESTAMPADD(DAY, subtract_day, v_shipment),
			@w := WEEKDAY(@d),
			IF(week_day IS NOT NULL, TIMESTAMPADD(DAY, (week_day - @w) + IF(@w > week_day, 7, 0), @d), @d) landing
/*
			TIMESTAMPADD(DAY,
				IFNULL(IF(WEEKDAY(@vdate) > week_day, 7, 0) + week_day - WEEKDAY(@vdate),
				subtract_day) - CAST(subtract_day AS DECIMAL),
			@vdate) landing
*/
			FROM agency_hour
			WHERE warehouse_id = v_wh
				AND (province_id = v_province OR province_id IS NULL)
				AND agency_id = v_agency_id
			ORDER BY
				(province_id IS NOT NULL) * 3 + (week_day IS NOT NULL) DESC, landing
 			LIMIT 1
 	) t;

	IF v_landing IS NULL THEN
		SET v_landing = v_shipment;
	END IF;

	UPDATE Tickets SET landing = v_landing WHERE Id_Ticket = v_ticket;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_movement` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `bionic_calc_movement`(IN v_id_mov BIGINT )
proc: BEGIN

/*
Este procedimiento bioniza una linea de movimiento
*/
	DECLARE v_shipment DATE; 
	DECLARE v_customer INT;
	DECLARE v_wh SMALLINT;
    DECLARE v_agencia INT;
    DECLARE v_consigna INT;
    DECLARE v_ticket BIGINT;
    DECLARE v_id_article BIGINT;
    DECLARE v_landing DATE; 
    DECLARE v_ticket_free BOOLEAN DEFAULT TRUE;
    
  
    SELECT FALSE
    INTO v_ticket_free
    FROM Tickets t
    JOIN Movimientos m ON m.Id_Ticket = t.Id_Ticket
    LEFT JOIN vn.ticketState ts on ts.ticket = t.Id_Ticket
    WHERE Id_Movimiento = v_id_mov
    AND (t.Factura != ""
			or 
            (
            ts.alertLevel > 0 
			AND 
            m.Preu != 0
            )
		)
    LIMIT 1;
	
    SELECT Id_Ticket, Id_Article INTO v_ticket, v_id_article FROM Movimientos WHERE Id_Movimiento = v_id_mov;
    
    REPLACE order_Tickets(order_id,Id_Ticket) VALUES(48, v_ticket);
    	
	SELECT Id_Cliente , t.warehouse_id, date(t.Fecha), Id_Consigna  , Id_Agencia
    INTO v_customer ,v_wh, v_shipment   , v_consigna   , v_agencia
    FROM vn2008.Agencias a 
    JOIN vn2008.Tickets t using(Id_Agencia)
    WHERE Id_Ticket = v_ticket;
	
	DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetShipped;
	CREATE TEMPORARY TABLE tmp.agencyHourGetShipped	ENGINE = MEMORY
	SELECT v_wh warehouseFk, v_shipment shipped, v_landing landed;
    
    CALL item_last_buy_ (v_wh, v_shipment);  -- rellena la tabla t_item_last_buy con la ultima compra
	DELETE FROM t_item_last_buy WHERE item_id != v_id_article;
    
    DROP TEMPORARY TABLE IF EXISTS tmp.bionic_lot;
    CREATE TEMPORARY TABLE tmp.bionic_lot 
	SELECT v_wh warehouse_id,NULL available,
		m.Id_Article item_id,ilb.buy_id
			FROM Movimientos m
			LEFT JOIN t_item_last_buy ilb ON ilb.item_id = m.Id_Article
				WHERE m.Id_Movimiento = v_id_mov;
                
	CALL bionic_calc_component(v_consigna,v_agencia);
    
    DROP TEMPORARY TABLE IF EXISTS tmp.movement;
	CREATE TEMPORARY TABLE tmp.movement
					(PRIMARY KEY (Id_Movimiento))  ENGINE = MEMORY
				SELECT Id_Movimiento,v_wh warehouse_id FROM Movimientos m WHERE m.Id_Movimiento =  v_id_mov;
                
	CALL bionic_movement_update(IF(v_ticket_free,1,6)); -- si el ticket esta facturado, respeta los precios

	-- Log
	INSERT INTO vn.ticketLog (originFk, userFk, `action`, description)
		VALUES (v_ticket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', v_id_mov));

	-- Limpieza
    
	DROP TEMPORARY TABLE t_item_last_buy;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_movement_ok` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_movement_ok`(IN v_ticket BIGINT)
BEGIN

/*
Este procedimiento "rebioniza" una linea, eliminando los componentes existentes e insertandolos de nuevo
*/
	DECLARE v_shipment DATE; 
	DECLARE v_customer INT;
	DECLARE v_wh SMALLINT;
    DECLARE v_agencia INT;
    DECLARE v_consigna INT;
    DECLARE v_landing DATE; 
    	
	SELECT Id_Cliente , t.warehouse_id, date(t.Fecha), Id_Consigna  , Id_Agencia
    INTO v_customer ,v_wh, v_shipment   , v_consigna   , v_agencia
    FROM vn2008.Agencias a 
    JOIN vn2008.Tickets t using(Id_Agencia)
    WHERE Id_Ticket = v_ticket;
	
	DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetShipped;
	CREATE TEMPORARY TABLE tmp.agencyHourGetShipped	ENGINE = MEMORY
	SELECT v_wh warehouseFk, v_shipment shipped, v_landing landed;
    
    CALL item_last_buy_ (v_wh, v_shipment);  -- rellena la tabla t_item_last_buy con la ultima compra
    
    DROP TEMPORARY TABLE IF EXISTS tmp.bionic_lot;
    CREATE TEMPORARY TABLE tmp.bionic_lot 
	SELECT v_wh warehouse_id,NULL available,
		m.Id_Article item_id,ilb.buy_id
			FROM Movimientos m
			LEFT JOIN t_item_last_buy ilb ON ilb.item_id = m.Id_Article
				WHERE m.Id_Ticket = v_ticket GROUP BY m.Id_Article;
                
	CALL bionic_calc_component(v_consigna,v_agencia);
    
    DROP TEMPORARY TABLE IF EXISTS tmp.movement;
	CREATE TEMPORARY TABLE tmp.movement
				(PRIMARY KEY (Id_Movimiento))  ENGINE = MEMORY
			SELECT Id_Movimiento, v_wh warehouse_id FROM Movimientos m WHERE m.Id_Ticket =  v_ticket;
	CALL bionic_movement_update(1);

	-- Log
    call Ditacio(v_ticket
            ,'Bioniza Lineas OK'
            ,'T' 
            , 20
            , 'proc bionic_calc_movement_ok '
            , NULL);

	-- Limpieza
	DROP TEMPORARY TABLE t_item_last_buy;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_reverse` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_reverse`(
    vWarehouse INT,
    vMargin DECIMAL(10,3),
    vRetailedPrice DECIMAL(10,3),
    vM3 DECIMAL(10,3),
    vConsigna INT,
    vAgencia INT)
proc: BEGIN

    DECLARE COEFICIENTE_DE_INFLACION_GENERAL INT DEFAULT 1.3;
    DECLARE DENSIDAD_MINIMA_PESO_VOLUMETRICO INT DEFAULT 167;
    DECLARE VOLUMEN_CAJA_VERDNATURA BIGINT DEFAULT 138000;    
    DECLARE vCost DECIMAL(10,4) DEFAULT 0;
    DECLARE vCustomer INT;
    DECLARE vRecovery DECIMAL(10,4) DEFAULT 0;
	DECLARE vMana DECIMAL(10,4) DEFAULT 0;
    DECLARE vPort DECIMAL(10,4) DEFAULT 0;
    
    SELECT Id_Cliente INTO vCustomer FROM Consignatarios WHERE Id_Consigna = vConsigna;
      
   -- Recobro
	SELECT ROUND(LEAST(recobro,0.25), 3) INTO vRecovery
		FROM bi.claims_ratio
			WHERE Id_Cliente = vCustomer AND recobro > 0.009;
            
	-- Componente de maná automático, en función del maná acumulado por el comercial.
    SELECT ROUND(prices_modifier_rate, 3) INTO vMana
		FROM Clientes c 
		JOIN bs.mana_spellers ms ON c.Id_Trabajador = ms.Id_Trabajador 
		WHERE ms.prices_modifier_activated AND c.Id_Cliente = vCustomer;
 
	-- Reparto
	SELECT COEFICIENTE_DE_INFLACION_GENERAL
				* ROUND(
						vM3 
						* az.price 
						* az.inflacion 
						/ VOLUMEN_CAJA_VERDNATURA, 4
						) INTO vPort
    FROM vn2008.Agencias a 
        JOIN vn2008.Consignatarios c ON c.Id_Consigna = vConsigna AND a.Id_Agencia = vAgencia
		JOIN vn2008.Agencias_province ap ON ap.agency_id = a.agency_id AND ap.warehouse_id = vWarehouse AND ap.province_id = c.province_id
        JOIN vn2008.Agencias_zonas az ON az.Id_Agencia = vAgencia AND az.zona = ap.zona AND az.Id_Article = 71 AND az.warehouse_id = vWarehouse;
	
	-- Modificacion de precio por dia de preparacion del pedido
	-- No aplicada
    
    SET vCost = ((vRetailedPrice - vPort) / ( 1 + (vRecovery + vMana))) - vMargin;
    
    SELECT vCost,vRetailedPrice,vPort,vRecovery,vMana,vMargin,vCustomer;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_ticket` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_ticket`(IN v_ticket BIGINT )
proc: BEGIN

/*
Este procedimiento trata de "rebionizar" un ticket, eliminando los componentes existentes e insertandolos de nuevo
*/
	DECLARE v_shipment DATE;   
	DECLARE v_customer INT;
	DECLARE v_wh SMALLINT;
    DECLARE v_agencia INT;
    DECLARE v_consigna INT;
    DECLARE v_landing DATE;
    DECLARE v_ticket_free BOOLEAN;
    DECLARE v_agency INT;
    
	CALL bionic_free();
    
	SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(Factura,"") != "") = FALSE
		INTO v_ticket_free
		FROM Tickets t LEFT JOIN vn.ticketState ts ON t.Id_Ticket = ts.ticket
		WHERE t.Id_Ticket = v_ticket;
    
    /*SELECT (EtiquetasEmitidas or PedidoImpreso or Firmado or  nz(Factura)) = FALSE
    INTO v_ticket_free
    FROM Tickets 
    WHERE Id_Ticket = v_ticket;*/
	
	SELECT Id_Cliente, t.warehouse_id, date(t.Fecha), Id_Consigna, t.Id_Agencia, landing, a.agency_id
		INTO v_customer, v_wh, v_shipment, v_consigna, v_agencia, v_landing, v_agency
    FROM vn2008.Tickets t LEFT JOIN vn2008.Agencias a ON t.Id_Agencia = a.Id_Agencia WHERE Id_Ticket = v_ticket;
		
	DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetShipped;
	CREATE TEMPORARY TABLE tmp.agencyHourGetShipped	ENGINE = MEMORY
	SELECT v_wh warehouseFk, v_shipment shipped, v_landing landed;
	
    CALL item_last_buy_ (v_wh, v_shipment);  -- rellena la tabla t_item_last_buy con la ultima compra
	
    DROP TEMPORARY TABLE IF EXISTS tmp.bionic_lot;
    CREATE TEMPORARY TABLE tmp.bionic_lot 
	SELECT v_wh warehouse_id,NULL available,
		m.Id_Article item_id,ilb.buy_id
			FROM Movimientos m
			LEFT JOIN t_item_last_buy ilb ON ilb.item_id = m.Id_Article
				WHERE m.Id_Ticket = v_ticket GROUP BY m.Id_Article;
                                
	CALL bionic_calc_component(v_consigna,v_agencia);
   
	DROP TEMPORARY TABLE IF EXISTS tmp.movement;
	CREATE TEMPORARY TABLE tmp.movement
				(PRIMARY KEY (Id_Movimiento))  ENGINE = MEMORY
			      SELECT Id_Movimiento, v_wh warehouse_id
                  FROM Movimientos m
                  where m.Id_Ticket = v_ticket;  
                                    
	CALL bionic_movement_update(IF(v_ticket_free,1,6)); -- si el ticket esta facturado, respeta los precios
    
	IF v_landing IS NULL THEN

		CALL travel_tree_shipment(v_shipment, v_consigna, v_agency,v_wh);
        UPDATE Tickets t
				JOIN travel_tree_shipment tts ON t.warehouse_id = tts.warehouse_id 
			SET t.landing = tts.landing 
			WHERE Id_Ticket = v_ticket;

    END IF;
	-- Limpieza    
	-- DROP TEMPORARY TABLE t_item_last_buy;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_free` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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_free`()
BEGIN
	DROP TEMPORARY TABLE IF EXISTS tmp.bionic_lot;
	DROP TEMPORARY TABLE IF EXISTS tmp.bionic_item;	
    DROP TEMPORARY TABLE IF EXISTS tmp.bionic_price;
	DROP TEMPORARY TABLE IF EXISTS tmp.bionic_component;
	DROP TEMPORARY TABLE IF EXISTS tmp.travel_tree;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_date DATE,
    v_consigna INT,
    v_agencia INT,
    v_item INT)
BEGIN
	DROP TEMPORARY TABLE IF EXISTS tmp.bionic_calc;
	CREATE TEMPORARY TABLE tmp.bionic_calc
	(PRIMARY KEY (item_id))
	ENGINE = MEMORY
		SELECT v_item item_id;

	CALL bionic_calc (v_date, v_consigna, v_agencia);
    
    DROP TEMPORARY TABLE tmp.bionic_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 `bionic_from_order` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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_order`(
    v_date DATE, --  fecha de recepcion de mercancia
    v_consigna INT,
    v_agencia INT,
    v_order INT)
BEGIN
	DROP TEMPORARY TABLE IF EXISTS tmp.bionic_calc;
	CREATE TEMPORARY TABLE tmp.bionic_calc
	(PRIMARY KEY (item_id))
	ENGINE = MEMORY
		SELECT item_id FROM order_row 
			WHERE order_id = v_order GROUP BY item_id;

	CALL bionic_calc (v_date, v_consigna, v_agencia);
    DROP TEMPORARY TABLE tmp.bionic_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 `bionic_from_ticket` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_from_ticket`(
	-- DEPRECATED use vn.ticketComponentPreview
    v_date DATE, --  fecha de recepcion de mercancia
    v_consigna INT,
    v_agencia INT,
    v_ticket INT)
BEGIN
	DECLARE int_warehouse SMALLINT;
	DECLARE v_agency_id INT;  
	DECLARE v_shipment DATE;
  
    SELECT warehouse_id INTO int_warehouse FROM Tickets WHERE Id_Ticket = v_ticket;
	SELECT agency_id INTO v_agency_id FROM Agencias WHERE Id_Agencia = v_agencia;


	CALL bionic_free();
	CALL vn.agencyHourGetShipped(v_date,v_consigna, v_agency_id);


    SELECT shipped INTO v_shipment FROM tmp.agencyHourGetShipped WHERE warehouseFk = int_warehouse;
    
	CALL item_last_buy_ (int_warehouse, v_shipment);
	
	DROP TEMPORARY TABLE IF EXISTS tmp.bionic_lot;
    CREATE TEMPORARY TABLE tmp.bionic_lot 
	SELECT int_warehouse warehouse_id,NULL available,
		m.Id_Article item_id,ilb.buy_id
			FROM Movimientos m
			LEFT JOIN t_item_last_buy ilb ON ilb.item_id = m.Id_Article
				WHERE m.Id_Ticket = v_ticket
                AND m.Id_Article != 100
                GROUP BY warehouse_id, item_id;
                                
	DROP TEMPORARY TABLE t_item_last_buy;
    
	CALL bionic_calc_component ( v_consigna, v_agencia);
    
	REPLACE INTO tmp.bionic_component (warehouse_id, item_id, component_id, cost)
		SELECT t.warehouse_id, m.Id_Article, mc.Id_Componente, mc.Valor
			FROM Movimientos_componentes mc
				JOIN Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento
				JOIN Tickets t ON t.Id_Ticket = m.Id_Ticket
				JOIN tarifa_componentes tc ON tc.Id_componente = mc.Id_Componente
			WHERE m.Id_Ticket = v_ticket AND tc.is_renewable = FALSE;
	
    -- para recuperar el shipment en caso de que se necesite
    
    SET @shipment = v_shipment;
    DROP TEMPORARY TABLE tmp.bionic_lot;
    
	IF IFNULL(v_shipment,CURDATE() - 1) < CURDATE() THEN
		SIGNAL SQLSTATE '45000'
		SET MESSAGE_TEXT = 'No se puede realizar el cambio'; 
    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_type` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_from_type`(
	-- DEPRECATED use vn.ticketCalculate
	v_date DATE, --  fecha de recepcion de mercancia
    v_consigna INT,
    v_agencia INT,
    v_type INT)
BEGIN
	DROP TEMPORARY TABLE IF EXISTS tmp.bionic_calc;
	CREATE TEMPORARY TABLE tmp.bionic_calc
	(PRIMARY KEY (item_id))
	ENGINE = MEMORY
		SELECT Id_Article AS item_id FROM Articles WHERE tipo_id = v_type;

	CALL bionic_calc (v_date, v_consigna, v_agencia);
    
   DROP TEMPORARY TABLE tmp.bionic_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 `bionic_make_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 `bionic_make_update`(
	 i_ticket INT
	,i_agencia INT
	,i_consigna INT
	,i_warehouse INT
	,d_shipment DATE
	,d_landing DATE
	,i_option INT)
BEGIN
/**
* DEPRECATED use vn.ticketComponentUpdate
*
 * Ejecuta los cambios en el ticket, en los movimientos y en los componentes.
 */
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
		ROLLBACK;
        RESIGNAL;
	END;

	-- Cambios en el ticket

	START TRANSACTION;
    
	UPDATE Tickets t 
		SET 
			t.Id_Agencia = i_agencia,
			t.Id_Consigna = i_consigna,
			t.warehouse_id = i_warehouse,
			t.landing = d_landing,
			t.Fecha = d_shipment
		WHERE
			t.Id_Ticket = i_ticket;

	-- La opcion 8 es No realizar modificaciones en los precios

	IF i_option <> 8
    THEN
		DROP TEMPORARY TABLE IF EXISTS tmp.movement;
		CREATE TEMPORARY TABLE tmp.movement
			(PRIMARY KEY (Id_Movimiento))
            ENGINE = MEMORY
			SELECT Id_Movimiento, i_warehouse warehouse_id
				FROM Movimientos m WHERE m.Id_Ticket = i_ticket;

		CALL bionic_movement_update (i_option);
        DROP TEMPORARY TABLE tmp.movement;
	END IF;

	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 `bionic_make_updateTest` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_make_updateTest`(
	 i_ticket INT
	,i_agencia INT
	,i_consigna INT
	,i_warehouse INT
	,d_shipment DATE
	,d_landing DATE
	,i_option INT)
BEGIN
/**
 * Ejecuta los cambios en el ticket, en los movimientos y en los componentes.
 */
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
		ROLLBACK;
        RESIGNAL;
	END;

	-- Cambios en el ticket

	START TRANSACTION;
    
	UPDATE Tickets t 
		SET 
			t.Id_Agencia = i_agencia,
			t.Id_Consigna = i_consigna,
			t.warehouse_id = i_warehouse,
			t.landing = d_landing,
			t.Fecha = d_shipment
		WHERE
			t.Id_Ticket = i_ticket;

	-- La opcion 8 es No realizar modificaciones en los precios

	IF i_option <> 8
    THEN
		DROP TEMPORARY TABLE IF EXISTS tmp.movement;
		CREATE TEMPORARY TABLE tmp.movement
			(PRIMARY KEY (Id_Movimiento))
            ENGINE = MEMORY
			SELECT Id_Movimiento, i_warehouse warehouse_id
				FROM Movimientos m WHERE m.Id_Ticket = i_ticket;

		CALL bionic_movement_updateTest(i_option);
        DROP TEMPORARY TABLE tmp.movement;
	END IF;

	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 `bionic_movement_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 `bionic_movement_update`(i_option INT)
BEGIN
/**
* DEPRECATED use vn.ticketComponentUpdateSale
*
 * A partir de la tabla tmp.movement, crea los Movimientos_componentes
 * y modifica el campo Preu de la tabla Movimientos
 *
 * @param i_option integer tipo de actualizacion
 * @param table tmp.movement  tabla memory con el campo Id_Movimiento, warehouse_id
 **/
	DECLARE intComponent INT;
    DECLARE bolRENUEVA_COMPONENTES BOOLEAN;
    DECLARE bolRESPETA_PRECIOS BOOLEAN;
    
    CASE i_option
    
		WHEN 1 THEN  -- caso normal
		
			SET bolRENUEVA_COMPONENTES = TRUE;
            SET bolRESPETA_PRECIOS = FALSE;
		
		WHEN 2 THEN
		
			SET intComponent = 17;  -- greuge al client
			SET bolRENUEVA_COMPONENTES = TRUE;
            SET bolRESPETA_PRECIOS = TRUE;
            
		WHEN 3 THEN 
		
			SET intComponent = 37; -- convertir en maná
			SET bolRENUEVA_COMPONENTES = TRUE;
            SET bolRESPETA_PRECIOS = TRUE;
            		
		WHEN 4 THEN 
		
			SET intComponent = 34; -- greuge contra la cartera del producto
			SET bolRENUEVA_COMPONENTES = TRUE;
            SET bolRESPETA_PRECIOS = TRUE;
            		
		WHEN 5 THEN 
		
			SET intComponent = 35;   -- greuge contra la cartera del comprador
			SET bolRENUEVA_COMPONENTES = TRUE;
            SET bolRESPETA_PRECIOS = TRUE;
            		
		WHEN 6 THEN 
    
			SET intComponent = 36;   -- descuadre para la empresa
			SET bolRENUEVA_COMPONENTES = TRUE;
            SET bolRESPETA_PRECIOS = TRUE;
            
        WHEN 7 THEN
			-- Insertamos el 80% para el coste
		    REPLACE INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
				SELECT m.Id_Movimiento,28, round(((m.Preu * (100 - m.Descuento) /100 ) - SUM(IFNULL(mc.Valor,0))) * 0.8 ,3) 
				FROM Movimientos m 
                JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento
				LEFT JOIN Movimientos_componentes mc  ON mc.Id_Movimiento = m.Id_Movimiento AND  mc.Id_Componente NOT IN (28,29)
                GROUP BY m.Id_Movimiento;
                
			-- Insertamos el 20% para el margen
			REPLACE INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
				SELECT m.Id_Movimiento,29, round(((m.Preu * (100 - m.Descuento) /100 ) - SUM(IFNULL(mc.Valor,0))) * 0.2 ,3) 
				FROM Movimientos m 
                JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento
				LEFT JOIN Movimientos_componentes mc  ON mc.Id_Movimiento = m.Id_Movimiento AND  mc.Id_Componente NOT IN (28,29)
                GROUP BY m.Id_Movimiento;
                
			SET bolRENUEVA_COMPONENTES = FALSE;
            SET bolRESPETA_PRECIOS = FALSE;
            
		WHEN 8 THEN
			-- Eliminamos todos los componentes exceptos los propios de la tarifa para no perderla                 
				DELETE mc.* 
				FROM tmp.movement mo
				JOIN Movimientos_componentes mc ON mo.Id_Movimiento = mc.Id_Movimiento;
                
			-- Insertamos el 100% para el coste Tipo 78 (Genérico)
			REPLACE INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
				SELECT m.Id_Movimiento,28, round(((m.Preu * (100 - m.Descuento) /100 )) ,3) 
				FROM Movimientos m
					JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento;
				
			SET bolRENUEVA_COMPONENTES = FALSE;
			SET bolRESPETA_PRECIOS = FALSE;
            
		WHEN 9 THEN  -- PAK 2017-02-06 caso especial de artículos cuyo precio se pone a mano, como los portes
			
			SET bolRENUEVA_COMPONENTES = TRUE;
            SET bolRESPETA_PRECIOS = TRUE;
            
    END CASE;

    IF bolRENUEVA_COMPONENTES THEN
			
				-- Eliminamos todos los componentes exceptos los propios de la tarifa para no perderla                 
				DELETE mc.* 
				FROM tmp.movement mo 
				JOIN Movimientos_componentes mc ON mo.Id_Movimiento = mc.Id_Movimiento
				JOIN tarifa_componentes tc ON tc.Id_Componente = mc.Id_Componente
				WHERE tc.is_renewable = TRUE;
				
				-- Insertamos los componentes actuales
				REPLACE INTO Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
					SELECT m.Id_Movimiento, bc.component_id, bc.cost
					FROM Movimientos m 
                    JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento
					JOIN tmp.bionic_component bc ON bc.item_id = m.Id_Article AND bc.warehouse_id = mo.warehouse_id
						LEFT JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = bc.component_id 
						LEFT JOIN tarifa_componentes tc ON tc.Id_Componente = bc.component_id 
						WHERE IF(mc.Id_Componente IS NULL AND tc.is_renewable = FALSE,FALSE,TRUE);
              	
    END IF;

    IF bolRESPETA_PRECIOS THEN
        
		REPLACE INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
		SELECT m.Id_Movimiento,intComponent, round((m.Preu * (100 - m.Descuento) /100 ) - SUM(mc.Valor) ,3) dif
		FROM Movimientos m 
		JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento
		LEFT JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento
		WHERE  mc.Id_Componente <> intComponent
		GROUP BY m.Id_Movimiento
		HAVING dif <> 0;
	
    ELSE
		
		-- Cambios en movimientos. 
		UPDATE Movimientos m
        JOIN Articles a on a.Id_Article = m.Id_Article
        JOIN Tipos tp on tp.tipo_id = a.tipo_id
			JOIN (SELECT SUM(mc.Valor) sum_valor,mc.Id_Movimiento 
                    FROM Movimientos_componentes mc
					JOIN tmp.movement m ON m.Id_Movimiento = mc.Id_Movimiento
					GROUP BY mc.Id_Movimiento) mc ON mc.Id_Movimiento = m.Id_Movimiento
			SET m.Preu = sum_valor
		WHERE Tipo != 'Portes';  -- PAK 2017-02-06
            
		-- Insertamos descuento, si lo hay
                
		REPLACE INTO Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
		SELECT m.Id_Movimiento, 21,   m.Preu * (100 -m.Descuento) / 100 - sum(Valor) v_valor
		FROM Movimientos m
		JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento
		JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento
		WHERE mc.Id_Componente != 21
		GROUP BY m.Id_Movimiento having round(v_valor,4) <> 0;
		
    END IF;
    
    -- Fija el Costfixat
    
    UPDATE Movimientos m
			JOIN (SELECT SUM(mc.Valor) sum_valor,mc.Id_Movimiento 
                    FROM Movimientos_componentes mc
					JOIN tmp.movement m ON m.Id_Movimiento = mc.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
					GROUP BY mc.Id_Movimiento) mc ON mc.Id_Movimiento = m.Id_Movimiento
			SET m.CostFixat = sum_valor, PrecioFijado = 1;


	-- PAK 2017-02-06
    -- Familia PORTES, un unico componente de porte
    
    DELETE mc.*
		FROM Movimientos_componentes mc
			JOIN tmp.movement mo ON mo.Id_Movimiento = mc.Id_Movimiento
			JOIN Movimientos m on m.Id_Movimiento = mc.Id_Movimiento
			JOIN Articles a ON a.Id_Article = m.Id_Article
			JOIN Tipos tp ON tp.tipo_id = a.tipo_id
		WHERE Tipo = 'Portes';
		
    INSERT INTO Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
		SELECT m.Id_Movimiento, 15, preu   -- Reparto
			FROM Movimientos m
				JOIN tmp.movement mo ON mo.Id_Movimiento = m.Id_Movimiento
				JOIN Articles a ON a.Id_Article = m.Id_Article
				JOIN Tipos tp ON tp.tipo_id = a.tipo_id
		WHERE Tipo = 'Portes' AND preu > 0;
    
	-- PAK 2017-09-27
    -- Tipos con un unico componente de coste
  /*  
    DELETE mc.*
		FROM Movimientos_componentes mc
			JOIN tmp.movement mo ON mo.Id_Movimiento = mc.Id_Movimiento
			JOIN Movimientos m on m.Id_Movimiento = mc.Id_Movimiento
			JOIN Articles a ON a.Id_Article = m.Id_Article
			JOIN Tipos tp ON tp.tipo_id = a.tipo_id
		WHERE tp.hasComponents = FALSE;
    
	INSERT INTO Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
		SELECT m.Id_Movimiento, 28, preu   -- Coste
			FROM Movimientos m
				JOIN tmp.movement mo ON mo.Id_Movimiento = m.Id_Movimiento
				JOIN Articles a ON a.Id_Article = m.Id_Article
				JOIN Tipos tp ON tp.tipo_id = a.tipo_id
			WHERE tp.hasComponents = 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 `bionic_movement_updateTest` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_movement_updateTest`(i_option INT)
BEGIN
/**
 * A partir de la tabla tmp.movement, crea los Movimientos_componentes
 * y modifica el campo Preu de la tabla Movimientos
 *
 * @param i_option integer tipo de actualizacion
 * @param table tmp.movement  tabla memory con el campo Id_Movimiento, warehouse_id
 **/
	DECLARE intComponent INT;
    DECLARE bolRENUEVA_COMPONENTES BOOLEAN;
    DECLARE bolRESPETA_PRECIOS BOOLEAN;
    
    CASE i_option
    
		WHEN 1 THEN  -- caso normal
		
			SET bolRENUEVA_COMPONENTES = TRUE;
            SET bolRESPETA_PRECIOS = FALSE;
		
		WHEN 2 THEN
		
			SET intComponent = 17;  -- greuge al client
			SET bolRENUEVA_COMPONENTES = TRUE;
            SET bolRESPETA_PRECIOS = TRUE;
            
		WHEN 3 THEN 
		
			SET intComponent = 37; -- convertir en maná
			SET bolRENUEVA_COMPONENTES = TRUE;
            SET bolRESPETA_PRECIOS = TRUE;
            		
		WHEN 4 THEN 
		
			SET intComponent = 34; -- greuge contra la cartera del producto
			SET bolRENUEVA_COMPONENTES = TRUE;
            SET bolRESPETA_PRECIOS = TRUE;
            		
		WHEN 5 THEN 
		
			SET intComponent = 35;   -- greuge contra la cartera del comprador
			SET bolRENUEVA_COMPONENTES = TRUE;
            SET bolRESPETA_PRECIOS = TRUE;
            		
		WHEN 6 THEN 
    
			SET intComponent = 36;   -- descuadre para la empresa
			SET bolRENUEVA_COMPONENTES = TRUE;
            SET bolRESPETA_PRECIOS = TRUE;
            
        WHEN 7 THEN
			-- Insertamos el 80% para el coste
		    REPLACE INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
				SELECT m.Id_Movimiento,28, round(((m.Preu * (100 - m.Descuento) /100 ) - SUM(IFNULL(mc.Valor,0))) * 0.8 ,3) 
				FROM Movimientos m 
                JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento
				LEFT JOIN Movimientos_componentes mc  ON mc.Id_Movimiento = m.Id_Movimiento AND  mc.Id_Componente NOT IN (28,29)
                GROUP BY m.Id_Movimiento;
                
			-- Insertamos el 20% para el margen
			REPLACE INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
				SELECT m.Id_Movimiento,29, round(((m.Preu * (100 - m.Descuento) /100 ) - SUM(IFNULL(mc.Valor,0))) * 0.2 ,3) 
				FROM Movimientos m 
                JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento
				LEFT JOIN Movimientos_componentes mc  ON mc.Id_Movimiento = m.Id_Movimiento AND  mc.Id_Componente NOT IN (28,29)
                GROUP BY m.Id_Movimiento;
                
			SET bolRENUEVA_COMPONENTES = FALSE;
            SET bolRESPETA_PRECIOS = FALSE;
            
		WHEN 8 THEN
			-- Eliminamos todos los componentes exceptos los propios de la tarifa para no perderla                 
				DELETE mc.* 
				FROM tmp.movement mo
				JOIN Movimientos_componentes mc ON mo.Id_Movimiento = mc.Id_Movimiento;
                
			-- Insertamos el 100% para el coste Tipo 78 (Genérico)
			REPLACE INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
				SELECT m.Id_Movimiento,28, round(((m.Preu * (100 - m.Descuento) /100 )) ,3) 
				FROM Movimientos m
					JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento;
				
			SET bolRENUEVA_COMPONENTES = FALSE;
			SET bolRESPETA_PRECIOS = FALSE;
            
		WHEN 9 THEN  -- PAK 2017-02-06 caso especial de artículos cuyo precio se pone a mano, como los portes
			
			SET bolRENUEVA_COMPONENTES = TRUE;
            SET bolRESPETA_PRECIOS = TRUE;
            
    END CASE;

    IF bolRENUEVA_COMPONENTES THEN
			
				-- Eliminamos todos los componentes exceptos los propios de la tarifa para no perderla                 
				DELETE mc.* 
				FROM tmp.movement mo 
				JOIN Movimientos_componentes mc ON mo.Id_Movimiento = mc.Id_Movimiento
				JOIN tarifa_componentes tc ON tc.Id_Componente = mc.Id_Componente
				WHERE tc.is_renewable = TRUE;
	SELECT m.Id_Movimiento, bc.component_id, bc.cost
					FROM Movimientos m 
                    JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento
					JOIN tmp.bionic_component bc ON bc.item_id = m.Id_Article AND bc.warehouse_id = mo.warehouse_id
						LEFT JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = bc.component_id 
						LEFT JOIN tarifa_componentes tc ON tc.Id_Componente = bc.component_id 
						WHERE IF(mc.Id_Componente IS NULL AND tc.is_renewable = FALSE,FALSE,TRUE);			
				-- Insertamos los componentes actuales
				REPLACE INTO Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
					SELECT m.Id_Movimiento, bc.component_id, bc.cost
					FROM Movimientos m 
                    JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento
					JOIN tmp.bionic_component bc ON bc.item_id = m.Id_Article AND bc.warehouse_id = mo.warehouse_id
						LEFT JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = bc.component_id 
						LEFT JOIN tarifa_componentes tc ON tc.Id_Componente = bc.component_id 
						WHERE IF(mc.Id_Componente IS NULL AND tc.is_renewable = FALSE,FALSE,TRUE);
              	
    END IF;

    IF bolRESPETA_PRECIOS THEN
        
		REPLACE INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
		SELECT m.Id_Movimiento,intComponent, round((m.Preu * (100 - m.Descuento) /100 ) - SUM(mc.Valor) ,3) dif
		FROM Movimientos m 
		JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento
		LEFT JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento
		WHERE  mc.Id_Componente <> intComponent
		GROUP BY m.Id_Movimiento
		HAVING dif <> 0;
	
		SELECT m.Id_Movimiento,intComponent, round((m.Preu * (100 - m.Descuento) /100 ) - SUM(mc.Valor) ,3) dif
		FROM Movimientos m 
		JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento
		LEFT JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento
		WHERE  mc.Id_Componente <> intComponent
		GROUP BY m.Id_Movimiento
		HAVING dif <> 0;
    ELSE
		
		-- Cambios en movimientos. 
		UPDATE Movimientos m
        JOIN Articles a on a.Id_Article = m.Id_Article
        JOIN Tipos tp on tp.tipo_id = a.tipo_id
			JOIN (SELECT SUM(mc.Valor) sum_valor,mc.Id_Movimiento 
                    FROM Movimientos_componentes mc
					JOIN tmp.movement m ON m.Id_Movimiento = mc.Id_Movimiento
					GROUP BY mc.Id_Movimiento) mc ON mc.Id_Movimiento = m.Id_Movimiento
			SET m.Preu = sum_valor
		WHERE Tipo != 'Portes';  -- PAK 2017-02-06
        
            SELECT SUM(mc.Valor) sum_valor,mc.Id_Movimiento 
                    FROM Movimientos_componentes mc
					JOIN tmp.movement m ON m.Id_Movimiento = mc.Id_Movimiento
					GROUP BY mc.Id_Movimiento;
                    
		-- Insertamos descuento, si lo hay
                
		REPLACE INTO Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
		SELECT m.Id_Movimiento, 21,   m.Preu * (100 -m.Descuento) / 100 - sum(Valor) v_valor
		FROM Movimientos m
		JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento
		JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento
		WHERE mc.Id_Componente != 21
		GROUP BY m.Id_Movimiento having round(v_valor,4) <> 0;
				SELECT m.Id_Movimiento, 21,   m.Preu * (100 -m.Descuento) / 100 - sum(Valor) v_valor
		FROM Movimientos m
		JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento
		JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento
		WHERE mc.Id_Componente != 21
		GROUP BY m.Id_Movimiento having round(v_valor,4) <> 0;
    END IF;
    
    -- Fija el Costfixat
    
    UPDATE Movimientos m
			JOIN (SELECT SUM(mc.Valor) sum_valor,mc.Id_Movimiento 
                    FROM Movimientos_componentes mc
					JOIN tmp.movement m ON m.Id_Movimiento = mc.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
					GROUP BY mc.Id_Movimiento) mc ON mc.Id_Movimiento = m.Id_Movimiento
			SET m.CostFixat = sum_valor, PrecioFijado = 1;


	-- PAK 2017-02-06
    -- Familia PORTES, un unico componente de porte
    
    DELETE mc.*
		FROM Movimientos_componentes mc
			JOIN tmp.movement mo ON mo.Id_Movimiento = mc.Id_Movimiento
			JOIN Movimientos m on m.Id_Movimiento = mc.Id_Movimiento
			JOIN Articles a ON a.Id_Article = m.Id_Article
			JOIN Tipos tp ON tp.tipo_id = a.tipo_id
		WHERE Tipo = 'Portes';
		
    INSERT INTO Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
		SELECT m.Id_Movimiento, 15, preu   -- Reparto
			FROM Movimientos m
				JOIN tmp.movement mo ON mo.Id_Movimiento = m.Id_Movimiento
				JOIN Articles a ON a.Id_Article = m.Id_Article
				JOIN Tipos tp ON tp.tipo_id = a.tipo_id
		WHERE Tipo = 'Portes' AND preu > 0;
    
	-- PAK 2017-09-27
    -- Tipos con un unico componente de coste
  /*  
    DELETE mc.*
		FROM Movimientos_componentes mc
			JOIN tmp.movement mo ON mo.Id_Movimiento = mc.Id_Movimiento
			JOIN Movimientos m on m.Id_Movimiento = mc.Id_Movimiento
			JOIN Articles a ON a.Id_Article = m.Id_Article
			JOIN Tipos tp ON tp.tipo_id = a.tipo_id
		WHERE tp.hasComponents = FALSE;
    
	INSERT INTO Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
		SELECT m.Id_Movimiento, 28, preu   -- Coste
			FROM Movimientos m
				JOIN tmp.movement mo ON mo.Id_Movimiento = m.Id_Movimiento
				JOIN Articles a ON a.Id_Article = m.Id_Article
				JOIN Tipos tp ON tp.tipo_id = a.tipo_id
			WHERE tp.hasComponents = 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 `bionic_movement_update_mode` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_movement_update_mode`(IN idMOV BIGINT, IN i_MODE INT)
BEGIN
	
    DROP TEMPORARY TABLE IF EXISTS tmp.movement;
	CREATE TEMPORARY TABLE tmp.movement
					(PRIMARY KEY (Id_Movimiento))  ENGINE = MEMORY
				  SELECT Id_Movimiento, warehouse_id 
                  FROM Movimientos m 
                  JOIN Tickets t using(Id_Ticket)
                  WHERE m.Id_Movimiento =  idMOV;

	CALL bionic_movement_update(i_MODE);
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_movimiento_precio_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              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `bionic_movimiento_precio_update`(IN i_mov INT)
BEGIN

DECLARE d_compo_precio DOUBLE;
DECLARE d_mov_precio DOUBLE;

SELECT SUM(Valor) INTO d_compo_precio 
FROM bi.movimientos_componentes 
WHERE Id_Movimiento = i_mov;

SELECT Preu INTO d_mov_precio 
FROM Movimientos
WHERE Id_Movimiento = i_mov;

IF d_mov_precio <> d_compo_precio 
AND d_compo_precio IS NOT NULL 
AND d_mov_precio IS NOT NULL 
THEN

	INSERT INTO bi.movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
	VALUES (i_mov, 21, d_mov_precio - d_compo_precio)
    ON DUPLICATE KEY UPDATE Valor = Valor + d_mov_precio - d_compo_precio ;

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_tickets_range_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 `bionic_tickets_range_bionizar`(IN datSTART DATE, IN datEND DATE)
BEGIN
DECLARE done BIT DEFAULT 0;
DECLARE datEND_Midnight DATETIME DEFAULT vn2008.dayend(datEND);
DECLARE v_ticket BIGINT;
DECLARE rs CURSOR FOR 
SELECT  DISTINCT t.Id_Ticket
FROM
(
	-- Movimientos que no coincide la suma de los componentes con el precio
select t.Id_Ticket, IFNULL(sum(Valor),0) - (Preu * (100 - m.Descuento)/100)  as Diferencia, NULL as Nothing
	from  vn2008.Tickets t 
    join vn2008.Movimientos m on t.Id_Ticket = m.Id_Ticket
    join vn2008.Articles a using(Id_Article)
	left join vn2008.Movimientos_componentes mc using(Id_Movimiento)
	join vn2008.Tipos tp on a.tipo_id = tp.tipo_id
	where t.Fecha between datSTART and datEND_Midnight
	and not tp.confeccion
	and m.Cantidad > 0
    and tp.reino_id != 6
	group by Id_Movimiento
	having ABS(Diferencia) > 1 OR (Diferencia IS NULL)

UNION ALL
	-- Movimientos sin componente de coste
	SELECT DISTINCT t.Id_Ticket, NULL, NULL
    FROM Tickets t
    JOIN Movimientos m ON t.Id_Ticket = m.Id_Ticket
    JOIN Articles a ON a.Id_Article = m.Id_Article
	LEFT JOIN
    (
		SELECT DISTINCT t.Id_Ticket, 0
		FROM Tickets t
		JOIN Movimientos m on m.Id_Ticket = t.Id_Ticket
        JOIN Articles a on a.Id_Article = m.Id_Article
		JOIN Tipos tp on a.tipo_id = tp.tipo_id
		JOIN Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento
		JOIN tarifa_componentes tc on tc.Id_Componente = mc.Id_Componente
		WHERE (tarifa_componentes_series_id = 1 OR tp.reino_id = 6)
		AND t.Fecha between datSTART and datEND_Midnight
	) sub on sub.Id_Ticket = t.Id_Ticket
    WHERE sub.Id_Ticket IS NULL
    AND t.Fecha between datSTART and datEND_Midnight
    AND a.tipo_id != 84 -- Portes
	AND a.tipo_id != 78 -- Genericos
    AND t.Id_Cliente NOT IN (200,400)
    AND t.warehouse_id != 13 -- Inventario
    
UNION ALL
	-- Movimientos sin porte en tickets con agencia que SI que deberia de llevar
     SELECT m.Id_Ticket, count(Id_Movimiento) as Lineas_totales, Lineas_conPorte
	FROM Movimientos m
    JOIN Articles a on a.Id_Article = m.Id_Article
    JOIN Tipos tp on tp.tipo_id = a.tipo_id
    JOIN Tickets t on m.Id_Ticket = t.Id_Ticket
    JOIN (select Id_Ticket, SUM(shipping_charge) shipping_charge from v_expeditions_shipping_charge2 group by Id_Ticket) v on v.Id_ticket = t.Id_Ticket
    LEFT JOIN
    (
    	SELECT m.Id_Ticket, count(Id_Componente) Lineas_conPorte
		FROM Movimientos_componentes mc
		JOIN Movimientos m using(Id_Movimiento)
		JOIN Tickets t using(Id_Ticket)
		WHERE Id_Componente = 15
		AND Fecha between datSTART and datEND_Midnight
		GROUP BY m.Id_Ticket
	) sub on sub.Id_Ticket = t.Id_Ticket
    WHERE t.Fecha between datSTART and datEND_Midnight
    AND Preu != 0
    AND tp.reino_id != 6
    AND shipping_charge > 1
    GROUP BY m.Id_Ticket
    HAVING Lineas_totales > IFNULL(Lineas_conPorte,0)
) sub
JOIN Tickets t ON t.Id_Ticket = sub.Id_Ticket
JOIN warehouse w ON w.id = t.warehouse_id
WHERE w.inventario;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

                  


OPEN rs;

FETCH rs INTO v_ticket ;

WHILE NOT done DO

	CALL bionic_calc_ticket(v_ticket);
    
    call Ditacio(v_ticket
            ,'Bioniza Ticket'
            ,'T' 
            , 20
            , 'proc bionic_tickets_range_bionizar'
            , NULL);

    FETCH rs INTO v_ticket ;

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 `buy_label` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `buy_label`(IN entry_id_ INT, IN groupby TINYINT(1))
BEGIN

	DECLARE done INT DEFAULT 0;
	DECLARE label INT;
	DECLARE id INT;
	DECLARE recordset CURSOR FOR SELECT Compres.Etiquetas, Compres.Id_Compra FROM Compres INNER JOIN
        (SELECT e.Id_entrada FROM Entradas e INNER JOIN (
            SELECT Id_Entrada,Inventario,Id_proveedor,travel_id,Id_Agencia FROM Entradas e1 INNER JOIN travel t ON e1.travel_id = t.id WHERE Id_Entrada = entry_id_) y 
        ON y.Inventario = e.Inventario AND e.travel_id = y.travel_id AND e.Id_proveedor = y.Id_proveedor AND y.Id_Agencia = e.Id_Agencia
        WHERE (0 OR e.Id_Entrada = entry_id_)) entry_label 
    ON Compres.Id_Entrada = entry_label.Id_entrada 
    INNER JOIN Articles ON Compres.Id_Article = Articles.Id_Article WHERE Articles.Imprimir <> FALSE;
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
   
    DROP TEMPORARY TABLE IF EXISTS `buy_label_source`;

	CREATE TEMPORARY TABLE `buy_label_source`
	(
		`buy_id` INT(11) NOT NULL
	)
    
	ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
	OPEN recordset;

	REPEAT

		FETCH recordset INTO label, id;
		WHILE label > 0 DO
	
			SET label = label - 1;
			INSERT INTO buy_label_source (buy_id) VALUES (id);

		END WHILE;

	UNTIL done END REPEAT;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_label_bunch` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `buy_label_bunch`(IN `entry_id_` INT, IN `groupby` TINYINT(1), IN `single` TINYINT(1), IN `idCOM` BIGINT)
BEGIN
	DECLARE done INT DEFAULT 0;
	DECLARE date_ DATE;
	DECLARE provider_id INT;
	DECLARE agency_id INT;
	DECLARE i_wh INT;
	DECLARE label INT;
	DECLARE id INT;
	DECLARE recordset CURSOR FOR 
		SELECT ROUND(C.Cantidad / IF(C.caja = FALSE, 1,C.`Grouping`) + 0.49), C.Id_Compra
			FROM Compres C
				INNER JOIN entry_label ON C.Id_Entrada = entry_label.entry_id
				INNER JOIN Articles A ON C.Id_Article = A.Id_Article
			WHERE (A.Imprimir <> FALSE AND idCOM = 0 AND C.Novincular = FALSE)
				OR idCOM = C.Id_Compra;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
	SET idCOM = IFNULL(idCOM, 0);

	DROP TEMPORARY TABLE IF EXISTS `entry_label`;
	CREATE TEMPORARY TABLE `entry_label`
		(`entry_id` INT(11) NOT NULL)
		ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

	IF groupby <> FALSE THEN

		SELECT Id_Proveedor, DATE(landing), travel.agency_id, warehouse_id 
				INTO provider_id, date_, agency_id, i_wh
			FROM Entradas
				INNER JOIN travel ON travel.id = Entradas.travel_id
			WHERE Id_Entrada = entry_id_;

		INSERT INTO entry_label (entry_id) 
			SELECT Entradas.Id_Entrada 
				FROM Entradas
					INNER JOIN travel ON travel.id = Entradas.travel_id
				WHERE Entradas.Inventario = FALSE 
					AND Entradas.Id_Proveedor = provider_id
					AND warehouse_id = i_wh 
					AND DATE(landing) = date_ 
					AND travel.agency_id= agency_id;

	ELSE

	INSERT INTO entry_label (entry_id) VALUES (entry_id_);
		SELECT landing
		INTO date_ FROM
			Entradas e
				JOIN travel t ON t.id = e.travel_id
				JOIN Compres c ON c.Id_Entrada = e.Id_Entrada
		WHERE (entry_id_ = e.Id_Entrada
				OR c.Id_Compra = idCOM)
		LIMIT 1;

	END IF;

	DROP TEMPORARY TABLE IF EXISTS `buy_label_source`;

	CREATE TEMPORARY TABLE `buy_label_source`
		(`buy_id` INT(11) NOT NULL)
		ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

	OPEN recordset;
	FETCH recordset INTO label, id;
	REPEAT
		REPEAT
			SET label = label - 1;
			INSERT INTO buy_label_source (buy_id) VALUES (id);
		UNTIL label <= 0 OR single END REPEAT;

		INSERT INTO buy_label_source (buy_id) VALUES (0);
		FETCH recordset INTO label, id;
	UNTIL done END REPEAT;

	SELECT 
			C.Id_Article,
			@a:=IF(A.min
					AND IFNULL(rate_3, C.Tarifa3) < A.PVP,
				A.PVP,
				IFNULL(rate_3, C.Tarifa3)) Tarifa2,
			ROUND(IF(C.caja = FALSE, @a, @a * C.`Grouping`),
					2) AS Bunch,
			ROUND(@a / A.Tallos, 2) AS PPT,
			A.Article,
			A.Medida,
			A.Color,
			A.Categoria,
			Abreviatura AS Origen,
			p.name Productor,
			A.Tallos,
			C.`grouping`,
			E.Notas_Eva,
			P.Proveedor,
			C.Packing
		FROM
			buy_label_source bls
				LEFT JOIN
			Compres C ON C.Id_Compra = bls.buy_id
				LEFT JOIN
			Entradas E ON E.Id_Entrada = C.Id_Entrada
				LEFT JOIN
			Articles A ON A.Id_Article = C.Id_Article
				LEFT JOIN
			Proveedores P ON P.Id_Proveedor = E.Id_Proveedor
				LEFT JOIN
			Origen o ON A.id_origen = o.id
				LEFT JOIN
			producer p ON p.producer_id = A.producer_id
				LEFT JOIN
			(SELECT 
					item_id, rate_3
				FROM
					price_fixed
				WHERE
					IFNULL(date_, CURDATE()) BETWEEN date_start AND date_end
						AND rate_3
						AND warehouse_id IN (0 , i_wh)
				GROUP BY item_id) pf ON pf.item_id = A.Id_Article;

	DROP TEMPORARY TABLE `entry_label`;
	DROP TEMPORARY TABLE `buy_label_source`;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_scan` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `buy_scan`(v_barcode VARCHAR(255), v_labels INT)
BEGIN
/**
 * Marca una compra de subasta como escaneada.
 *
 * @param v_barcode Código de compra de una etiqueta de subasta
 * @param v_labels Cantidad escaneada
 **/
	DECLARE v_edi INT;
	DECLARE v_buy INT;
	DECLARE v_item INT;
	DECLARE v_do_photo BOOL;

	-- Aun no se sabe como obtener el número de serie de transacción de
	-- las compras realizadas a través de un reloj, por lo que se establece
	-- siempre a '01'

	IF SUBSTR(v_barcode, 3, 2) != '99' THEN
		SET v_barcode = CONCAT(LEFT(v_barcode, 12), '010');
	END IF;

	SELECT e.id, c.Id_Compra, c.Id_Article, a.do_photo
		INTO v_edi, v_buy, v_item, v_do_photo
		FROM buy_edi e
			JOIN Compres c ON c.buy_edi_id = e.id
			JOIN Articles a ON a.Id_Article = c.Id_Article
		WHERE e.barcode = v_barcode
			AND e.entry_year = YEAR(CURDATE())
		ORDER BY c.Id_Compra
		LIMIT 1;

	UPDATE buy_edi SET scanned = TRUE WHERE id = v_edi;

	UPDATE Compres
		SET Vida = Vida + IF(v_labels != -1, v_labels, Etiquetas)
		WHERE Id_Compra = v_buy;

	IF v_do_photo THEN
		UPDATE Articles SET do_photo = FALSE WHERE Id_Article = v_item;
	END IF;

	SELECT v_buy buy, v_do_photo do_photo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_split` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `buy_split`(IN `v_buy` INT, IN `v_fv_entry` INT, IN `v_pca_entry` INT)
BEGIN
	DECLARE v_item INT;
	DECLARE v_packing INT;
	DECLARE v_remaining INT;
	DECLARE v_labels INT;
	DECLARE v_remainder INT;
	DECLARE v_is_buy INT;
	DECLARE v_id INT;
	DECLARE v_amount INT;
	DECLARE v_done BOOL DEFAULT FALSE;

	DECLARE cur CURSOR FOR
		SELECT TRUE, c.Id_Compra, c.Cantidad - IFNULL((c.Vida * c.Packing), 0)
			FROM Compres c
				JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
				JOIN travel t ON t.id = e.travel_id
			WHERE c.Id_Article = v_item
				AND t.shipment = CURDATE() AND t.warehouse_id_out IN (7, 40)
				AND t.warehouse_id NOT IN (44, 1)
				AND NOT e.redada AND NOT e.Inventario
				AND IFNULL(c.Vida, 0) < c.Etiquetas
		UNION ALL
		SELECT FALSE, m.Id_Movimiento, m.Cantidad - IFNULL(l.stem, 0)
			FROM Movimientos m
				JOIN Tickets t ON t.Id_Ticket = m.Id_Ticket
				LEFT JOIN movement_label l ON l.Id_Movimiento = m.Id_Movimiento
			WHERE m.Id_Article = v_item
				AND t.Fecha = CURDATE() AND t.warehouse_id IN (7, 40)
				AND NOT t.Etiquetasemitidas
				AND IFNULL(l.stem, 0) < m.Cantidad
			LOCK IN SHARE MODE;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET v_done = TRUE;

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

	START TRANSACTION;

	-- Obtiene los datos de la compra

	SELECT Id_Article, Packing, Cantidad
		INTO v_item, v_packing, v_remaining
		FROM Compres WHERE Id_Compra = v_buy;

	-- Crea splits de los tickets

	DROP TEMPORARY TABLE IF EXISTS tmp.split;
	CREATE TEMPORARY TABLE tmp.split
	(
		is_buy BOOL,
		id INT,
		labels INT,
		remainder INT
	)
	ENGINE = MEMORY;

	OPEN cur;

	l: LOOP
		SET v_done = FALSE;
		FETCH cur INTO v_is_buy, v_id, v_amount;
		
		IF v_done OR v_remaining = 0 THEN
			LEAVE l;
		END IF;
		
		SET v_amount = LEAST(v_amount, v_remaining);
		SET v_remaining = v_remaining - v_amount;
		SET v_labels = v_amount DIV v_packing;
        
		INSERT INTO tmp.split
			VALUES (v_is_buy, v_id, v_labels, v_amount % v_packing);

		IF v_is_buy
		THEN
			UPDATE Compres
				SET Vida = Vida + v_labels
				WHERE Id_Compra = v_id;
		ELSE
			INSERT INTO movement_label
				SET
					Id_Movimiento = v_id,
					stem = v_amount,
					label = v_labels
				ON DUPLICATE KEY UPDATE
					stem = stem + VALUES(stem),
					label = label + VALUES(label);
		END IF;
	END LOOP;

	CLOSE cur;

	-- Crea los movimientos de almacén a silla

	CALL buy_transfer (v_buy, v_fv_entry, v_pca_entry);
    
    UPDATE Compres SET dispatched = Vida * Packing
		WHERE Id_Compra = v_buy;

	-- Devuelve los splits creados

	DROP TEMPORARY TABLE IF EXISTS tmp.aux;
	CREATE TEMPORARY TABLE tmp.aux
		ENGINE = MEMORY
		SELECT s.labels, s.remainder, w.`name` destination,
			a.Id_Article, a.Article, a.Medida, '        ' counter
			FROM tmp.split s
				JOIN Compres c ON c.Id_Compra = s.id
				JOIN Articles a ON a.Id_Article = c.Id_Article
				JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
				JOIN travel t ON t.id = e.travel_id
				JOIN warehouse w ON t.warehouse_id = w.id
			WHERE s.is_buy;

	INSERT INTO tmp.aux
		SELECT s.labels, s.remainder, o.Consignatario,
				a.Id_Article, a.Article, a.Medida, 
				vn.ticketSplitCounter(t.Id_Ticket)
			FROM tmp.split s
				JOIN Movimientos m ON m.Id_Movimiento = s.id
				JOIN Articles a ON a.Id_Article = m.Id_Article
				JOIN Tickets t ON t.Id_Ticket = m.Id_Ticket
				JOIN Consignatarios o ON o.Id_Consigna = t.Id_Consigna
			WHERE NOT s.is_buy;
			
	SELECT * FROM tmp.aux;

	-- Limpia y confirma cambios
			
	DROP TEMPORARY TABLE
		tmp.split,
		tmp.aux;

	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 `buy_splitKk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `buy_splitKk`(IN `v_buy` INT, IN `v_fv_entry` INT, IN `v_pca_entry` INT)
BEGIN
	DECLARE v_item INT;
	DECLARE v_packing INT;
	DECLARE v_remaining INT;
	DECLARE v_labels INT;
	DECLARE v_remainder INT;
	DECLARE v_is_buy INT;
	DECLARE v_id INT;
	DECLARE v_amount INT;
	DECLARE v_done BOOL DEFAULT FALSE;

	DECLARE cur CURSOR FOR
		SELECT TRUE, c.Id_Compra, c.Cantidad - IFNULL((c.Vida * c.Packing), 0)
			FROM Compres c
				JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
				JOIN travel t ON t.id = e.travel_id
			WHERE c.Id_Article = v_item
				AND t.shipment = CURDATE() AND t.warehouse_id_out IN (7, 40)
				AND t.warehouse_id NOT IN (44, 1)
				AND NOT e.redada AND NOT e.Inventario
				AND IFNULL(c.Vida, 0) < c.Etiquetas
		UNION ALL
		SELECT FALSE, m.Id_Movimiento, m.Cantidad - IFNULL(l.stem, 0)
			FROM Movimientos m
				JOIN Tickets t ON t.Id_Ticket = m.Id_Ticket
				LEFT JOIN movement_label l ON l.Id_Movimiento = m.Id_Movimiento
			WHERE m.Id_Article = v_item
				AND t.Fecha = CURDATE() AND t.warehouse_id IN (7, 40)
				AND NOT t.Etiquetasemitidas
				AND IFNULL(l.stem, 0) < m.Cantidad
			LOCK IN SHARE MODE;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET v_done = TRUE;

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

	START TRANSACTION;

	-- Obtiene los datos de la compra

	SELECT Id_Article, Packing, Cantidad
		INTO v_item, v_packing, v_remaining
		FROM Compres WHERE Id_Compra = v_buy;

	-- Crea splits de los tickets

	DROP TEMPORARY TABLE IF EXISTS tmp.split;
	CREATE TEMPORARY TABLE tmp.split
	(
		is_buy BOOL,
		id INT,
		labels INT,
		remainder INT
	)
	ENGINE = MEMORY;

	OPEN cur;

	l: LOOP
		SET v_done = FALSE;
		FETCH cur INTO v_is_buy, v_id, v_amount;
		
		IF v_done OR v_remaining = 0 THEN
			LEAVE l;
		END IF;
		
		SET v_amount = LEAST(v_amount, v_remaining);
		SET v_remaining = v_remaining - v_amount;
		SET v_labels = v_amount DIV v_packing;
        
		INSERT INTO tmp.split
			VALUES (v_is_buy, v_id, v_labels, v_amount % v_packing);

		IF v_is_buy
		THEN
			UPDATE Compres
				SET Vida = Vida + v_labels
				WHERE Id_Compra = v_id;
		ELSE
			INSERT INTO movement_label
				SET
					Id_Movimiento = v_id,
					stem = v_amount,
					label = v_labels
				ON DUPLICATE KEY UPDATE
					stem = stem + VALUES(stem),
					label = label + VALUES(label);
		END IF;
	END LOOP;

	CLOSE cur;

	-- Crea los movimientos de almacén a silla

	CALL buy_transfer (v_buy, v_fv_entry, v_pca_entry);
    
    UPDATE Compres SET dispatched = Vida * Packing
		WHERE Id_Compra = v_buy;

	-- Devuelve los splits creados

	DROP TEMPORARY TABLE IF EXISTS tmp.aux;
	CREATE TEMPORARY TABLE tmp.aux
		ENGINE = MEMORY
		SELECT s.labels, s.remainder, w.`name` destination,
			a.Id_Article, a.Article, a.Medida
			FROM tmp.split s
				JOIN Compres c ON c.Id_Compra = s.id
				JOIN Articles a ON a.Id_Article = c.Id_Article
				JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
				JOIN travel t ON t.id = e.travel_id
				JOIN warehouse w ON t.warehouse_id = w.id
			WHERE s.is_buy;

	INSERT INTO tmp.aux
		SELECT s.labels, s.remainder, o.Consignatario,
			a.Id_Article, a.Article, a.Medida
			FROM tmp.split s
				JOIN Movimientos m ON m.Id_Movimiento = s.id
				JOIN Articles a ON a.Id_Article = m.Id_Article
				JOIN Tickets t ON t.Id_Ticket = m.Id_Ticket
				JOIN Consignatarios o ON o.Id_Consigna = t.Id_Consigna
			WHERE NOT s.is_buy;
			
	SELECT * FROM tmp.aux;

	-- Limpia y confirma cambios
			
	DROP TEMPORARY TABLE
		tmp.split,
		tmp.aux;

	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 `buy_splitTest` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `buy_splitTest`(IN `v_buy` INT, IN `v_fv_entry` INT, IN `v_pca_entry` INT)
BEGIN
	DECLARE v_item INT;
	DECLARE v_packing INT;
	DECLARE v_remaining INT;
	DECLARE v_labels INT;
	DECLARE v_remainder INT;
	DECLARE v_is_buy INT;
	DECLARE v_id INT;
	DECLARE v_amount INT;
	DECLARE v_done BOOL DEFAULT FALSE;

	DECLARE cur CURSOR FOR
		SELECT TRUE, c.Id_Compra, c.Cantidad - IFNULL((c.Vida * c.Packing), 0)
			FROM Compres c
				JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
				JOIN travel t ON t.id = e.travel_id
			WHERE c.Id_Article = v_item
				AND t.shipment = CURDATE() AND t.warehouse_id_out IN (7, 40)
				AND t.warehouse_id NOT IN (44, 1)
				AND NOT e.redada AND NOT e.Inventario
				AND IFNULL(c.Vida, 0) < c.Etiquetas
		UNION ALL
		SELECT FALSE, m.Id_Movimiento, m.Cantidad 
			FROM Movimientos m
				JOIN Tickets t ON t.Id_Ticket = m.Id_Ticket
				LEFT JOIN movement_label l ON l.Id_Movimiento = m.Id_Movimiento
			WHERE m.Id_Article = v_item
				AND t.Fecha = CURDATE() AND t.warehouse_id IN (7, 40)
				AND NOT t.Etiquetasemitidas
			LOCK IN SHARE MODE;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET v_done = TRUE;

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

	START TRANSACTION;

	-- Obtiene los datos de la compra

	SELECT Id_Article, Packing, Cantidad
		INTO v_item, v_packing, v_remaining
		FROM Compres WHERE Id_Compra = v_buy;

	-- Crea splits de los tickets

	DROP TEMPORARY TABLE IF EXISTS tmp.split;
	CREATE TEMPORARY TABLE tmp.split
	(
		is_buy BOOL,
		id INT,
		labels INT,
		remainder INT
	)
	ENGINE = MEMORY;

	OPEN cur;

	l: LOOP
		SET v_done = FALSE;
		FETCH cur INTO v_is_buy, v_id, v_amount;
		
		IF v_done OR v_remaining = 0 THEN
			LEAVE l;
		END IF;
		
		SET v_amount = LEAST(v_amount, v_remaining);
		SET v_remaining = v_remaining - v_amount;
		SET v_labels = v_amount DIV v_packing;
        
		INSERT INTO tmp.split
			VALUES (v_is_buy, v_id, v_labels, v_amount % v_packing);

	/*	IF v_is_buy
		THEN
			UPDATE Compres
				SET Vida = Vida + v_labels
				WHERE Id_Compra = v_id;
		ELSE
			INSERT INTO movement_label
				SET
					Id_Movimiento = v_id,
					stem = v_amount,
					label = v_labels
				ON DUPLICATE KEY UPDATE
					stem = stem + VALUES(stem),
					label = label + VALUES(label);
		END IF;*/
	END LOOP;

	CLOSE cur;

	-- Crea los movimientos de almacén a silla
/*
	CALL buy_transfer (v_buy, v_fv_entry, v_pca_entry);
    
    UPDATE Compres SET dispatched = Vida * Packing
		WHERE Id_Compra = v_buy;
*/
	-- Devuelve los splits creados

	DROP TEMPORARY TABLE IF EXISTS tmp.aux;
	CREATE TEMPORARY TABLE tmp.aux
		ENGINE = MEMORY
		SELECT s.labels, s.remainder, w.`name` destination,
			a.Id_Article, a.Article, a.Medida, '        ' counter
			FROM tmp.split s
				JOIN Compres c ON c.Id_Compra = s.id
				JOIN Articles a ON a.Id_Article = c.Id_Article
				JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
				JOIN travel t ON t.id = e.travel_id
				JOIN warehouse w ON t.warehouse_id = w.id
			WHERE s.is_buy;

	INSERT INTO tmp.aux
		SELECT s.labels, s.remainder, o.Consignatario,
				a.Id_Article, a.Article, a.Medida, 
				vn.ticketSplitCounter(t.Id_Ticket)
			FROM tmp.split s
				JOIN Movimientos m ON m.Id_Movimiento = s.id
				JOIN Articles a ON a.Id_Article = m.Id_Article
				JOIN Tickets t ON t.Id_Ticket = m.Id_Ticket
				JOIN Consignatarios o ON o.Id_Consigna = t.Id_Consigna
			WHERE NOT s.is_buy;
            
	SELECT s.labels, s.remainder, o.Consignatario,
				a.Id_Article, a.Article, a.Medida, 
				vn.ticketSplitCounter(t.Id_Ticket),NOT s.is_buy
			FROM tmp.split s
				JOIN Movimientos m ON m.Id_Movimiento = s.id
				JOIN Articles a ON a.Id_Article = m.Id_Article
				JOIN Tickets t ON t.Id_Ticket = m.Id_Ticket
				JOIN Consignatarios o ON o.Id_Consigna = t.Id_Consigna
                where NOT s.is_buy
			;
            
	SELECT * FROM tmp.aux;

	-- Limpia y confirma cambios
			
	DROP TEMPORARY TABLE
		tmp.split,
		tmp.aux;

	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 `buy_tarifas` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `buy_tarifas`(v_buy INT)
BEGIN
	DECLARE v_entry INT;
	DECLARE v_wh INT;

	SELECT Id_Entrada, warehouse_id
		INTO v_entry, v_wh
		FROM Compres
			JOIN Entradas USING(Id_Entrada)
			JOIN travel ON travel.id = travel_id
		WHERE v_buy = Id_Compra;

	CALL buy_tarifas_table (v_entry);

	UPDATE Compres C
			LEFT JOIN Cubos CB USING(Id_Cubo)
			JOIN Articles A USING(Id_Article)
			JOIN Tipos TP USING(tipo_id)
			JOIN Entradas E USING(Id_Entrada)
			JOIN travel TR ON TR.id = E.travel_id
			JOIN Agencias AG ON TR.agency_id = AG.Id_Agencia
			LEFT JOIN recibida_entrada re ON E.Id_Entrada = re.Id_Entrada
			LEFT JOIN awb_recibida ar ON re.awb_recibida = ar.recibida_id
			LEFT JOIN v_awb_volumen va ON va.awb_id = ar.awb_id
			JOIN tblTARIFAS TC
		SET C.Portefijo = @PF:= 
			IF (va.importe, 
                ROUND((va.importe * A.density * CM3_2(C.Id_Cubo, C.Id_Article) / 1000) / (va.Vol_Total * 167 * C.Packing ),3),
				ROUND(IFNULL(((AG.m3 * cm3_2(C.Id_Cubo, C.Id_Article)) / 1000000) / C.Packing,0),3)
			),
			C.Comisionfija = @CF:= ROUND(IFNULL(E.comision * C.Costefijo / 100,0),3),
			C.Embalajefijo = @EF:= ROUND((CB.costeRetorno + IF(CB.Retornable != 0, 0, CB.Valor)) / C.packing,3),
			C.Tarifa3 = @t3:= IF(TC.t3 = 0, C.Costefijo,ROUND((C.Costefijo + @CF + @EF + @PF) / ((100 - TC.t3 - TP.promo ) /100) ,2)),    -- He añadido que el coste sea igual a tarifa3 si t3 = 0
			C.Tarifa2 = @t2:= ROUND(@t3 * (1 + (  (TC.t2 - TC.t3)/100)  ),2),
			C.Tarifa2 = IF(@t2 <= @t3, @t3 , @t2)
		WHERE C.Id_Compra = v_buy;

    CALL vn2008.buy_tarifas_priceBuilder_Buy(v_buy);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_tarifas_awb` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `buy_tarifas_awb`(IN strAWB varchar(18))
BEGIN

DECLARE datINV DATE;
DECLARE wh_id INT;
DECLARE idENTRADA INT;

DECLARE done BOOL DEFAULT FALSE;
DECLARE entryFk INT;

DECLARE rs CURSOR FOR
		SELECT de.entryFk Id_Entrada
			FROM vn.duaEntry de 
                 JOIN vn.dua d ON d.id = de.duaFk
                 JOIN vn.awb a ON a.id = d.awbFk
			WHERE a.code = strAWB;
                 
/*				 JOIN recibida_entrada re on e.Id_Entrada = re.Id_Entrada
				 JOIN awb_recibida ar ON re.awb_recibida = ar.recibida_id
				 JOIN v_awb_volumen va ON va.awb_id = ar.awb_id
			WHERE va.codigo = strAWB ;
*/
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

SELECT tr.warehouseInFk, de.entryFk
		INTO wh_id, idENTRADA
	FROM vn.travel tr 
		JOIN vn.entry e ON e.travelFk = tr.id
		JOIN vn.duaEntry de ON de.entryFk = e.id
		JOIN vn.dua d ON d.id = de.duaFk
		JOIN vn.awb a ON a.id = d.awbFk
	WHERE a.code = strAWB
		LIMIT 1;


		CALL buy_tarifas_table(idENTRADA);

		UPDATE Compres C
				 LEFT JOIN Cubos CB USING(Id_Cubo)
				 JOIN Articles A USING(Id_Article)
				 JOIN Entradas E USING(Id_Entrada)
                 JOIN vn.duaEntry de ON de.entryFk = E.Id_Entrada
                 JOIN vn.dua d ON d.id = de.duaFk
				 -- JOIN recibida_entrada re on E.Id_Entrada = re.Id_Entrada
				 -- JOIN awb_recibida ar ON re.awb_recibida = ar.recibida_id
				 JOIN v_awb_volumen va ON va.awb_id = d.awbFk
				 JOIN Tipos TP USING(tipo_id)  
				 JOIN travel TR ON TR.id = E.travel_id
				 JOIN Agencias AG ON TR.agency_id = AG.Id_Agencia
				 JOIN tblTARIFAS TC

				SET C.Portefijo = @PF:= round((va.importe * A.density * CM3_2(C.Id_Cubo, C.Id_Article) / 1000) / (va.Vol_Total * 167 * C.Packing ),3),

					C.Comisionfija = @CF:= ROUND(IFNULL(E.comision * C.Costefijo / 100,0),3),

					C.Embalajefijo = @EF:= ROUND((CB.costeRetorno + IF(CB.Retornable != 0, 0, CB.Valor)) / C.Packing,3),
                    
					C.Tarifa3 = @t3:= IF(TC.t3 = 0, C.Costefijo,ROUND((C.Costefijo + @CF + @EF + @PF) / ((100 - TC.t3 - TP.promo ) /100) ,2)),    -- He añadido que el coste sea igual a tarifa3 si t3 = 0

					C.Tarifa2 = @t2:= round(@t3 * (1 + (  (TC.t2 - TC.t3)/100)  ),2),

					C.Tarifa2 = @t2:= IF(@t2 <= @t3, @t3 , @t2)


				WHERE va.codigo = strAWB ;
                
OPEN rs;

	FETCH rs INTO entryFk;

	WHILE NOT done DO
    
		CALL vn2008.buy_tarifas_priceBuilder_Entry(entryFk);

		FETCH rs INTO entryFk;

	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 `buy_tarifas_awb_bucle` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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`@`localhost` PROCEDURE `buy_tarifas_awb_bucle`()
BEGIN

DECLARE strAWB VARCHAR(25);
DECLARE done INT DEFAULT FALSE;
DECLARE rs CURSOR  FOR 
SELECT codigo 
FROM awb 
WHERE MYSQL_TIME > '2015-06-30' AND importe > 0 ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;


OPEN rs;

FETCH rs INTO strAWB;
-- drop temporary table if exists killme;
-- create temporary table killme select strAWB, now() as fecha, 0;

WHILE NOT done DO

	insert into killme select strAWB, MYSQL_TIME, importe from awb where codigo = strAWB;
	call buy_tarifas_awb(strAWB);
	FETCH rs INTO strAWB;
    select * from killme order by fecha desc;
END WHILE;



drop temporary table killme;


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 `buy_tarifas_entry` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `buy_tarifas_entry`(IN entryFk INT(11))
BEGIN

	DECLARE datINV DATE;

	CALL buy_tarifas_table(entryFk);

	UPDATE Compres C
			LEFT JOIN Cubos CB USING(Id_Cubo)
			JOIN Articles A USING(Id_Article)
			JOIN Entradas E USING(Id_Entrada)
			LEFT JOIN vn.duaEntry de on E.Id_Entrada = de.entryFk
			LEFT JOIN vn.dua d ON d.id = de.duaFk
			LEFT JOIN v_awb_volumen va ON va.awb_id = d.awbFk
			JOIN Tipos TP USING(tipo_id)
			JOIN travel TR ON TR.id = E.travel_id
			JOIN Agencias AG ON TR.agency_id = AG.Id_Agencia
			JOIN tblTARIFAS TC

		SET C.Portefijo = @PF:= 
			IF (va.importe, 

				round((va.importe * A.density * CM3_2(C.Id_Cubo, C.Id_Article) / 1000) / (va.Vol_Total * 167 * C.Packing ),3),
				
				ROUND(IFNULL(((AG.m3 * @cm3:= cm3_2(C.Id_Cubo, C.Id_Article)) / 1000000) / C.Packing,0),3)
			),

			C.Comisionfija = @CF:= ROUND(IFNULL(E.comision * C.Costefijo / 100,0),3),

			C.Embalajefijo = @EF:= IF(CB.Retornable != 0, 0, ROUND(IFNULL( CB.Valor / C.Packing ,0),3)),

			C.Tarifa3 = @t3:= IF(TC.t3 = 0, C.Costefijo,ROUND((C.Costefijo + @CF + @EF + @PF) / ((100 - TC.t3 - TP.promo ) /100) ,2)),    -- He añadido que el coste sea igual a tarifa3 si t3 = 0

			C.Tarifa2 = @t2:= round(@t3 * (1 + (  (TC.t2 - TC.t3)/100)),2),

			C.Tarifa2 = @t2:= IF(@t2 <= @t3, @t3 , @t2)

		WHERE C.Id_Entrada = entryFk;
    
    -- priceBuilder
    call buy_tarifas_priceBuilder_Entry(entryFk);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_tarifas_entryKk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `buy_tarifas_entryKk`(IN idENTRADA INT(11))
BEGIN

	DECLARE datINV DATE;
	DECLARE wh_id INT;
	DECLARE m3i INTEGER;


	SELECT  warehouse_id INTO  wh_id 
	FROM Entradas 
	JOIN travel ON travel.id = travel_id
	WHERE Id_Entrada = idENTRADA;

	CALL buy_tarifas_table(idENTRADA);

	SELECT AG.m3 * sum(     etiquetas * IFNULL(((AG.m3  * cm3_2(C.Id_Cubo, C.Id_Article)) / 1000000) ,0)    )  /
	sum(etiquetas * IFNULL(((AG.m3 * ( A.density / 167 ) * cm3_2(C.Id_Cubo, C.Id_Article)) / 1000000) ,0)) INTO m3i
	FROM Compres C
	JOIN Articles A USING(Id_Article)
	JOIN Entradas E USING(Id_Entrada)
	JOIN Tipos TP USING(tipo_id)  
	JOIN travel TR ON TR.id = E.travel_id
	JOIN Agencias AG ON TR.agency_id = AG.Id_Agencia
	WHERE E.Id_Entrada = idENTRADA;



	UPDATE Compres C
			 LEFT JOIN Cubos CB USING(Id_Cubo)
			 JOIN Articles A USING(Id_Article)
			 JOIN Entradas E USING(Id_Entrada)
				 LEFT JOIN recibida_entrada re on E.Id_Entrada = re.Id_Entrada
				 LEFT JOIN awb_recibida ar ON re.awb_recibida = ar.recibida_id
				 LEFT JOIN v_awb_volumen va ON va.awb_id = ar.awb_id
			 JOIN Tipos TP USING(tipo_id)
			 JOIN travel TR ON TR.id = E.travel_id
			 JOIN Agencias AG ON TR.agency_id = AG.Id_Agencia
			 JOIN tblTARIFAS TC

	SET C.Portefijo = @PF:= 
		IF (va.importe, 

			round((va.importe * A.density * CM3_2(C.Id_Cubo, C.Id_Article) / 1000) / (va.Vol_Total * 167 * C.Packing ),3),
			
			ROUND(IFNULL(((AG.m3 * @cm3:= cm3_2(C.Id_Cubo, C.Id_Article)) / 1000000) / C.Packing,0),3)
		),

		C.Comisionfija = @CF:= ROUND(IFNULL(E.comision * C.Costefijo / 100,0),3),

		C.Embalajefijo = @EF:= IF(CB.Retornable != 0, 0, ROUND(IFNULL( CB.Valor / C.Packing ,0),3)),

		C.Tarifa3 = @t3:= IF(TC.t3 = 0, C.Costefijo,ROUND((C.Costefijo + @CF + @EF + @PF) / ((100 - TC.t3 - TP.promo ) /100) ,2)),    -- He añadido que el coste sea igual a tarifa3 si t3 = 0

		C.Tarifa2 = @t2:= round(@t3 * (1 + (  (TC.t2 - TC.t3)/100)),2),

		C.Tarifa2 = @t2:= IF(@t2 <= @t3, @t3 , @t2)

	WHERE C.Id_Entrada = idENTRADA ;


	CASE wh_id

		WHEN 41 THEN -- Canarias

				UPDATE Compres 
						SET Tarifa2 = Tarifa3
						WHERE Id_Entrada = idENTRADA;
		   ELSE

				BEGIN
				END;

	END CASE;
    
    -- priceBuilder
    call buy_tarifas_priceBuilder_Entry(idENTRADA);

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

DECLARE intWHIN INTEGER(3);
DECLARE intDAYS INTEGER(3);
DECLARE dbM3 DOUBLE;
DECLARE done INT DEFAULT 0;
DECLARE datFEC DATE;
DECLARE wh INTEGER(3);
DECLARE idART INTEGER(11);
DECLARE dbCOST DOUBLE;
DECLARE m3value DOUBLE;
DECLARE intLIFE INTEGER;
DECLARE intPACK INTEGER;
DECLARE intPromo DOUBLE;
DECLARE whlc CURSOR FOR SELECT whin, days, m3 FROM warehouse_lc WHERE whout = @wh:= wh UNION ALL SELECT @wh, 0, 0 ;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;

SELECT 
    Id_Article,
    warehouse_id,
    landing,
    nz(Costefijo) + nz(Embalajefijo) + nz(Portefijo) + nz(Comisionfija),
    life,
	C.Packing,
    (cm3_2(C.Id_Cubo, C.Id_Article) / 1000000) / C.Packing,
    promo
INTO idART , wh , datFEC , dbCOST , intLIFE, intPACK, m3value, intPromo FROM
    Compres C
        JOIN
    Articles A USING (Id_Article)
        JOIN
    Tipos TP USING (tipo_id)
        JOIN
    Entradas E USING (Id_Entrada)
        JOIN
    travel tr ON tr.id = E.travel_id
WHERE
    Id_Compra = idCOMPRA;



OPEN whlc;

FETCH whlc INTO intWHIN, intDAYS, dbM3; 

WHILE NOT done DO 

SELECT idART , wh , datFEC , dbCOST , intLIFE, intPACK, m3value, intWHIN, intDAYS, dbM3, done, dbCOST +  (m3value * dbM3);

	INSERT INTO price_fixed(item_id,
								rate_3,
								rate_2,
								date_start,
								date_end,
								warehouse_id)

							SELECT 	idART,
										round(     (dbCOST + (m3value * dbM3)) / ((100 - t3 - intPromo )/100)         ,       2),
										@tf2 :=  round((dbCOST +  (m3value * dbM3)) / ((100 - t2 - intPromo)/100)         ,2),
										TIMESTAMPADD(DAY,  intDAYS, datFEC),
										TIMESTAMPADD(DAY,  intLIFE, datFEC),
										intWHIN
								FROM tarifas
								WHERE warehouse_id = intWHIN AND fecha  <=  TIMESTAMPADD(DAY,  intDAYS, datFEC) 
								ORDER BY fecha  DESC
								LIMIT 1;
											
FETCH whlc INTO intWHIN, intDAYS, dbM3; 

 END WHILE;

CALL buy_tarifas_priceBuilder_Buy(idCOMPRA);

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

UPDATE vn.buy b
	JOIN
		(
			SELECT i.id, i.name, i.size, pb.price, difTags.numTags , count(DISTINCT pbt.tagFk) matchedTags
				FROM vn.item i
					JOIN vn.buy b ON b.itemFk = i.id
					JOIN vn.entry e ON e.id = b.entryFk
					JOIN vn.travel tr ON tr.id = e.travelFk
					JOIN vn.itemTag it ON it.itemFk = i.id
					JOIN vn.priceBuilder pb ON pb.itemTypeFk = i.typeFk
					JOIN vn.priceBuilderWarehouse pbw ON pbw.priceBuilderFk = pb.id AND pbw.warehouseFk = tr.warehouseInFk
					LEFT JOIN vn.priceBuilderTag pbt ON pbt.priceBuilderFk = pb.id AND  pbt.tagFk = it.tagFk AND pbt.value = it.value
					JOIN vn.priceBuilderDistinctTags difTags ON difTags.priceBuilderFk = pb.id
				WHERE b.entryFk = entryFk
					AND tr.landed BETWEEN pb.started AND pb.finished
				GROUP BY i.id
				HAVING matchedTags = numTags
		) sub ON sub.id = b.itemFk
	SET b.price2 = sub.price, b.price3 = sub.price * 0.95
	WHERE b.entryFk = entryFk;

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

UPDATE vn.buy b
	JOIN
		(
			SELECT i.id, i.name, i.size, pb.price, difTags.numTags , count(DISTINCT pbt.tagFk) matchedTags
				FROM vn.item i
					JOIN vn.buy b ON b.itemFk = i.id
					JOIN vn.entry e ON e.id = b.entryFk
					JOIN vn.travel tr ON tr.id = e.travelFk
					JOIN vn.itemTag it ON it.itemFk = i.id
					JOIN vn.priceBuilder pb ON pb.itemTypeFk = i.typeFk
					JOIN vn.priceBuilderWarehouse pbw ON pbw.priceBuilderFk = pb.id AND pbw.warehouseFk = tr.warehouseInFk
					LEFT JOIN vn.priceBuilderTag pbt ON pbt.priceBuilderFk = pb.id AND  pbt.tagFk = it.tagFk AND pbt.value = it.value
					JOIN vn.priceBuilderDistinctTags difTags ON difTags.priceBuilderFk = pb.id
				WHERE b.id = buyFk
					AND tr.landed BETWEEN pb.started AND pb.finished
				GROUP BY i.id
				HAVING matchedTags = numTags
		) sub ON sub.id = b.itemFk
	SET b.price2 = sub.price, b.price3 = sub.price * 0.95
	WHERE b.id = buyFk;

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

UPDATE vn.buy b
	JOIN
		(
			SELECT i.id, i.name, i.size, pb.price, difTags.numTags , count(DISTINCT pbt.tagFk) matchedTags
				FROM vn.item i
					JOIN vn.buy b ON b.itemFk = i.id
					JOIN vn.entry e ON e.id = b.entryFk
					JOIN vn.travel tr ON tr.id = e.travelFk
					JOIN vn.itemTag it ON it.itemFk = i.id
					JOIN vn.priceBuilder pb ON pb.itemTypeFk = i.typeFk
					JOIN vn.priceBuilderWarehouse pbw ON pbw.priceBuilderFk = pb.id AND pbw.warehouseFk = tr.warehouseInFk
					LEFT JOIN vn.priceBuilderTag pbt ON pbt.priceBuilderFk = pb.id AND  pbt.tagFk = it.tagFk AND pbt.value = it.value
					JOIN vn.priceBuilderDistinctTags difTags ON difTags.priceBuilderFk = pb.id
				WHERE b.entryFk = entryFk
					AND tr.landed BETWEEN pb.started AND pb.finished
				GROUP BY i.id
				HAVING matchedTags = numTags
		) sub ON sub.id = b.itemFk
	SET b.price2 = sub.price, b.price3 = sub.price * 0.95
	WHERE b.entryFk = entryFk;

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

DECLARE done INT DEFAULT 0;
DECLARE idE INT;

DECLARE cur1 CURSOR FOR 
SELECT Id_Entrada
FROM Entradas
JOIN travel ON travel.id = travel_id
WHERE landing >= datFEC AND wh_id IN (0,warehouse_id);

DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;

OPEN cur1;

REPEAT

	FETCH cur1 INTO idE;

	IF NOT done THEN

		Call buy_tarifas_entry(idE);

		

	END IF;

  
UNTIL done END REPEAT;

 CLOSE cur1;

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

	DECLARE idENTRADA BIGINT;
	DECLARE wh_id INT;

	SELECT Id_Entrada, warehouse_id INTO idENTRADA, wh_id 
	FROM Compres
	JOIN Entradas using(Id_Entrada)
	JOIN travel ON travel.id = travel_id
	WHERE idCOMPRA = Id_Compra;

	CALL buy_tarifas_table(idENTRADA);

	UPDATE Compres C
		JOIN tblTARIFAS TC

		SET 
			C.Tarifa3 = @t3:= C.Tarifa3,

			C.Tarifa2 =  @t2:= round(@t3 * (1 + (  (TC.t2 - TC.t3)/100)  ),2),

			C.Tarifa2 = @t2:= IF(@t2 <= @t3, @t3 + 0.01, @t2)

		WHERE C.Id_Compra = idCOMPRA;
    
    CALL buy_tarifas_priceBuilder_Buy(idCOMPRA);

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

DECLARE idENTRADA BIGINT;
DECLARE idCOMPRA BIGINT;
DECLARE datFEC DATE;
DECLARE wh INT;
DECLARE idART BIGINT;

SELECT date_start, warehouse_id, item_id INTO datFEC, wh, idART
FROM price_fixed WHERE price_fixed_id = idPRICE;

SELECT C.Id_Entrada, Id_Compra INTO idENTRADA, idCOMPRA 
FROM Compres C
JOIN Entradas E using(Id_Entrada)
JOIN travel TR on TR.id = E.travel_id
WHERE Id_Article = idART
AND wh IN (0, warehouse_id)
AND Novincular = FALSE
AND NOT Redada
AND landing <= datFEC
ORDER BY landing DESC
LIMIT 1;

CALL buy_tarifas_table(idENTRADA);

SELECT  

	 @t2:= round(t3 * (1 + (  (TC.t2 - TC.t3)/100)  ),2) as rate_2b,

	 @t2:= IF(@t2 <= t3, t3 + 0.01, @t2) as rate_2

FROM price_fixed PF
		 JOIN Compres C ON C.Id_Compra = idCOMPRA AND price_fixed_id = idPRICE
         JOIN tblTARIFAS TC;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_tarifas_table` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `buy_tarifas_table`(v_entry INT)
BEGIN
	DECLARE v_date DATE;
	DECLARE v_wh INT;

	-- Obtiene fecha de llegada y almacén entrante

	SELECT landing, warehouse_id INTO v_date , v_wh
		FROM travel TR
			JOIN Entradas E ON TR.id = E.travel_id
		WHERE Id_Entrada = v_entry;

	-- Prepara una tabla con las tarifas aplicables en funcion de la fecha y el almacén

	DROP TEMPORARY TABLE IF EXISTS tblTARIFAS;
	CREATE TEMPORARY TABLE tblTARIFAS
		ENGINE = MEMORY
		SELECT * FROM
		(
			SELECT * FROM
				(    
					SELECT t0, t1, t2, t3
					FROM tarifas
					WHERE fecha <= v_date
					AND warehouse_id = v_wh
					ORDER BY fecha DESC
							
				) sub
			UNION ALL
			SELECT t0, t1, t2, t3
			FROM tblContadores
		) sub2
		LIMIT 1;

	UPDATE bi.rotacion r
		JOIN Compres c ON c.Id_Article = r.Id_Article
		SET cm3 = vn2008.cm3_unidad(c.Id_Compra) 
		WHERE Id_Entrada = v_entry
			AND r.warehouse_id = v_wh;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_transfer` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `buy_transfer`(IN `v_buy` INT, IN `v_fv_entry` INT, IN `v_pca_entry` INT)
proc: BEGIN
/**
 * Traslada la cantidad restante de una compra de Holanda
 * al almacén de Silla.
 **/
	DECLARE v_wh INT;
	DECLARE v_entry INT;
	DECLARE v_fv INT;
	DECLARE v_amount INT;
	DECLARE v_item INT;
	DECLARE v_holland_wh INT DEFAULT 7;
    DECLARE vIsIgnored BOOL DEFAULT FALSE;
    DECLARE vDestinationWarehouse INT;
	
	-- Comprueba que es mercancía que llega al almacén de Holanda
    
	SELECT t.warehouse_id, IF(tp.warehouseFk=1,1,0), tp.warehouseFk, c.Id_Article, c.Novincular  
			INTO v_wh, v_fv, vDestinationWarehouse, v_item, vIsIgnored
		FROM Compres c
			JOIN Entradas e ON c.Id_Entrada = e.Id_Entrada
			JOIN travel t ON t.id = e.travel_id
			JOIN Articles a ON a.Id_Article = c.Id_Article
			JOIN Tipos tp ON tp.tipo_id = a.tipo_id
		WHERE c.Id_Compra = v_buy;
        
	IF v_wh != v_holland_wh THEN
		LEAVE proc;
	END IF;

	-- Calcula a que almacén de Silla debe transladar la mercancía

	SET v_entry = IF(v_fv, v_fv_entry, v_pca_entry);
	SET v_entry = COALESCE(v_entry, v_pca_entry, v_fv_entry);

	IF v_entry IS NULL THEN
		LEAVE proc;
	END IF;

	-- Calcula la cantidad a trasladar

	SELECT IFNULL(SUM(amount), 0) INTO v_amount
		FROM (
			SELECT SUM(c.Cantidad) amount
				FROM Compres c 
					JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada 
					JOIN travel t ON t.id = e.travel_id
				WHERE c.Id_Article = v_item
					AND t.landing = CURDATE()
					AND t.warehouse_id = v_holland_wh
			UNION ALL
			SELECT -SUM(c.Cantidad)
				FROM Compres c
					JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
					JOIN travel t ON t.id = e.travel_id
				WHERE c.Id_Article = v_item
					AND t.shipment = CURDATE()
					AND t.warehouse_id_out = v_holland_wh
			UNION ALL
			SELECT -SUM(Cantidad)
				 FROM Movimientos m
					JOIN Tickets t ON t.Id_Ticket = m.Id_Ticket
				 WHERE m.Id_Article = v_item
					AND t.Fecha = CURDATE()
					AND t.warehouse_id = v_holland_wh
		) t;

	IF v_amount <= 0 THEN
		LEAVE proc;
	END IF;

	-- Si la linea tiene no vincular hay que buscar la anterior válida
	IF vIsIgnored THEN
		CALL buyUltimate(vDestinationWarehouse, CURDATE());
        SELECT buyFk INTO v_buy 
			FROM tmp.buyUltimate
            LIMIT 1;
		DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate;
	END IF;
    
	-- Crea la nueva línea de compra con el translado
    
	INSERT INTO Compres (
			Id_Article, Etiquetas, Cantidad, Id_Entrada,
			Id_Cubo, Packing, `grouping`, caja, Costefijo, Portefijo, 
			Embalajefijo, Comisionfija, buy_edi_id)
		SELECT c.Id_Article,
				v_amount DIV c.Packing,
				v_amount,
				v_entry,
				c.Id_Cubo,
				c.Packing,
				c.`grouping`,
				c.caja,
				@cost := IFNULL(c.Costefijo, 0) + IFNULL(c.Comisionfija, 0) + IFNULL(c.Portefijo, 0),
				@porte := ROUND((@cm3:= cm3_2(c.Id_Cubo, c.Id_Article)) * a.m3 / 1000000 / c.Packing, 3),
				c.EmbalajeFijo,
				@comision := ROUND(c.Costefijo * e.comision / 100, 3),
				c.buy_edi_id
			FROM Compres c
				JOIN Cubos cu ON cu.Id_Cubo = c.Id_Cubo 
				JOIN Entradas e ON e.Id_Entrada = v_entry
				JOIN travel t ON t.id = e.travel_id
				JOIN Agencias a ON t.agency_id = a.Id_Agencia
			WHERE c.Id_Compra = v_buy;

	CALL buy_tarifas (LAST_INSERT_ID());
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_transferBeta` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `buy_transferBeta`(IN `v_buy` INT, IN `v_fv_entry` INT, IN `v_pca_entry` INT)
proc: BEGIN
/**
 * Traslada la cantidad restante de una compra de Holanda
 * al almacén de Silla.
 **/
	DECLARE v_wh INT;
	DECLARE v_entry INT;
	DECLARE v_fv INT;
	DECLARE v_amount INT;
	DECLARE v_item INT;
	DECLARE v_holland_wh INT DEFAULT 7;
    DECLARE vIsIgnored BOOL DEFAULT FALSE;
    DECLARE vDestinationWarehouse INT;
	
	-- Comprueba que es mercancía que llega al almacén de Holanda
    
	SELECT t.warehouse_id, IF(tp.warehouseFk=1,1,0), tp.warehouseFk, c.Id_Article, c.Novincular  
			INTO v_wh, v_fv, vDestinationWarehouse, v_item, vIsIgnored
		FROM Compres c
			JOIN Entradas e ON c.Id_Entrada = e.Id_Entrada
			JOIN travel t ON t.id = e.travel_id
			JOIN Articles a ON a.Id_Article = c.Id_Article
			JOIN Tipos tp ON tp.tipo_id = a.tipo_id
		WHERE c.Id_Compra = v_buy;
        
	IF v_wh != v_holland_wh THEN
		LEAVE proc;
	END IF;

	-- Calcula a que almacén de Silla debe transladar la mercancía

	SET v_entry = IF(v_fv, v_fv_entry, v_pca_entry);
	SET v_entry = COALESCE(v_entry, v_pca_entry, v_fv_entry);

	IF v_entry IS NULL THEN
		LEAVE proc;
	END IF;

	-- Calcula la cantidad a trasladar

	SELECT IFNULL(SUM(amount), 0) INTO v_amount
		FROM (
			SELECT SUM(c.Cantidad) amount
				FROM Compres c 
					JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada 
					JOIN travel t ON t.id = e.travel_id
				WHERE c.Id_Article = v_item
					AND t.landing = CURDATE()
					AND t.warehouse_id = v_holland_wh
			UNION ALL
			SELECT -SUM(c.Cantidad)
				FROM Compres c
					JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
					JOIN travel t ON t.id = e.travel_id
				WHERE c.Id_Article = v_item
					AND t.shipment = CURDATE()
					AND t.warehouse_id_out = v_holland_wh
			UNION ALL
			SELECT -SUM(Cantidad)
				 FROM Movimientos m
					JOIN Tickets t ON t.Id_Ticket = m.Id_Ticket
				 WHERE m.Id_Article = v_item
					AND t.Fecha = CURDATE()
					AND t.warehouse_id = v_holland_wh
		) t;

	IF v_amount <= 0 THEN
		LEAVE proc;
	END IF;

	-- Si la linea tiene no vincular hay que buscar la anterior válida
	IF vIsIgnored THEN
		CALL buyUltimate(vDestinationWarehouse, CURDATE());
        SELECT buyFk INTO v_buy 
			FROM tmp.buyUltimate
            LIMIT 1;
		DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate;
	END IF;
    
	-- Crea la nueva línea de compra con el translado
    
	INSERT INTO Compres (
			Id_Article, Etiquetas, Cantidad, Id_Entrada,
			Id_Cubo, Packing, `grouping`, caja, Costefijo, Portefijo, 
			Embalajefijo, Comisionfija, buy_edi_id)
		SELECT c.Id_Article,
				v_amount DIV c.Packing,
				v_amount,
				v_entry,
				c.Id_Cubo,
				c.Packing,
				c.`grouping`,
				c.caja,
				@cost := IFNULL(c.Costefijo, 0) + IFNULL(c.Comisionfija, 0) + IFNULL(c.Portefijo, 0),
				@porte := ROUND((@cm3:= cm3_2(c.Id_Cubo, c.Id_Article)) * a.m3 / 1000000 / c.Packing, 3),
				c.EmbalajeFijo,
				@comision := ROUND(c.Costefijo * e.comision / 100, 3),
				c.buy_edi_id
			FROM Compres c
				JOIN Cubos cu ON cu.Id_Cubo = c.Id_Cubo 
				JOIN Entradas e ON e.Id_Entrada = v_entry
				JOIN travel t ON t.id = e.travel_id
				JOIN Agencias a ON t.agency_id = a.Id_Agencia
			WHERE c.Id_Compra = v_buy;

	CALL buy_tarifas (LAST_INSERT_ID());
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_transferKk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `buy_transferKk`(IN `v_buy` INT, IN `v_fv_entry` INT, IN `v_pca_entry` INT)
proc: BEGIN
/**
 * Traslada la cantidad restante de una compra de Holanda
 * al almacén de Silla.
 **/
	DECLARE v_wh INT;
	DECLARE v_entry INT;
	DECLARE v_fv INT;
	DECLARE v_amount INT;
	DECLARE v_item INT;
	DECLARE v_holland_wh INT DEFAULT 7;
	
	-- Comprueba que es mercancía que llega al almacén de Holanda
    
	SELECT t.warehouse_id, IF(tp.warehouseFk=1,1,0) AS v_fv INTO v_wh,v_fv
		FROM Compres c
			JOIN Entradas e ON c.Id_Entrada = e.Id_Entrada
			JOIN travel t ON t.id = e.travel_id
			JOIN Articles a ON a.Id_Article = c.Id_Article
			JOIN Tipos tp ON tp.tipo_id = a.tipo_id
		WHERE c.Id_Compra = v_buy;
        
	IF v_wh != v_holland_wh THEN
		LEAVE proc;
	END IF;

	-- Calcula a que almacén de Silla debe transladar la mercancía

	SET v_entry = IF(v_fv, v_fv_entry, v_pca_entry);
	SET v_entry = COALESCE(v_entry, v_pca_entry, v_fv_entry);

	IF v_entry IS NULL THEN
		LEAVE proc;
	END IF;
	
	-- Calcula la cantidad a trasladar

	SELECT Id_Article INTO v_item
		FROM Compres WHERE Id_Compra = v_buy;

	SELECT IFNULL(SUM(amount), 0) INTO v_amount
		FROM (
			SELECT SUM(c.Cantidad) amount
				FROM Compres c 
					JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada 
					JOIN travel t ON t.id = e.travel_id
				WHERE c.Id_Article = v_item
					AND t.landing = CURDATE()
					AND t.warehouse_id = v_holland_wh
			UNION ALL
			SELECT -SUM(c.Cantidad)
				FROM Compres c
					JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
					JOIN travel t ON t.id = e.travel_id
				WHERE c.Id_Article = v_item
					AND t.shipment = CURDATE()
					AND t.warehouse_id_out = v_holland_wh
			UNION ALL
			SELECT -SUM(Cantidad)
				 FROM Movimientos m
					JOIN Tickets t ON t.Id_Ticket = m.Id_Ticket
				 WHERE m.Id_Article = v_item
					AND t.Fecha = CURDATE()
					AND t.warehouse_id = v_holland_wh
		) t;

	IF v_amount <= 0 THEN
		LEAVE proc;
	END IF;

	-- Crea la nueva línea de compra con el translado

	INSERT INTO Compres (
		Id_Article, Etiquetas, Cantidad, Id_Entrada,
		Id_Cubo, Packing, `grouping`, caja, Costefijo, Portefijo, 
		Embalajefijo, Comisionfija, novincular, buy_edi_id)
		SELECT 
			c.Id_Article,
			v_amount DIV c.Packing,
			v_amount,
			v_entry,
			c.Id_Cubo,
			c.Packing,
			c.`grouping`,
			c.caja,
			@cost := IFNULL(c.Costefijo, 0) + IFNULL(c.Comisionfija, 0) + IFNULL(c.Portefijo, 0),
			@porte := ROUND((@cm3:= cm3_2(c.Id_Cubo, c.Id_Article)) * a.m3 / 1000000 / c.Packing, 3),
			c.EmbalajeFijo,
			@comision := ROUND(c.Costefijo * e.comision / 100, 3),
			c.novincular,
			c.buy_edi_id
			FROM Compres c
				JOIN Cubos cu ON cu.Id_Cubo = c.Id_Cubo 
				JOIN Entradas e ON e.Id_Entrada = v_entry
				JOIN travel t ON t.id = e.travel_id
				JOIN Agencias a ON t.agency_id = a.Id_Agencia
			WHERE c.Id_Compra = v_buy;

	CALL buy_tarifas (LAST_INSERT_ID());
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cacheReset` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `cacheReset`(vCacheName VARCHAR(10), vParams VARCHAR(15))
BEGIN

	UPDATE cache.cache_calc 
		SET expires = NOW() 
		WHERE cacheName = vCacheName collate utf8_unicode_ci
        AND params = vParams collate utf8_unicode_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 `Cajas_Saldo_Detalle` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `Cajas_Saldo_Detalle`()
BEGIN

        Select Proveedores.Id_Proveedor, Proveedor, Fecha, round(Importe) as Importe
        from Proveedores
        join
        (
        select Fecha, sub.Id_Proveedor, sum(Importe) as Importe
        from
        
        (

        select round(sum(Importe),2) as Importe, TIMESTAMPADD(DAY,-1,CURDATE()) as Fecha, Id_Proveedor
        from pago
        join Proveedores using(Id_Proveedor)
        where Fecha >= '2011-01-01'
        and Id_Proveedor NOT IN (select id from empresa)
        group by Id_Proveedor

        union all

        select IFNULL(-1 * round(sum(rv.Cantidad / if(Id_Moneda = 2,rate,1)),2),0) AS Vto, TIMESTAMPADD(DAY,-1,CURDATE()), proveedor_id
        from recibida_vencimiento rv
        join recibida r on r.id = rv.recibida_id
        join reference_rate rr on rr.`date` = rv.fecha
        join Proveedores P on P.Id_Proveedor = r.proveedor_id
        join Paises PS on PS.Id = P.pais_id 
        where rv.fecha between '2011-01-01' and CURDATE()-1
        and Id_Proveedor NOT IN (select id from empresa)
        group by proveedor_id

        union all

        select -1 * round(rv.Cantidad / if(Id_Moneda = 2,currate(),1),2) AS Vto, rv.fecha, proveedor_id 
        from recibida_vencimiento rv
        join recibida r on r.id = rv.recibida_id
        join Proveedores P on P.Id_Proveedor = r.proveedor_id
        join Paises PS on PS.Id = P.pais_id 
        where rv.fecha >= CURDATE() 
        and Id_Proveedor NOT IN (select id from empresa)

        union all

        select @remesas:= @pago:=  @saldo:= 0.0000, curdate(), @prov:= 0) sub
        group by Fecha,Id_Proveedor
        ) sub2 using(Id_Proveedor)
        having Importe < -100
        ;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `CalculoRemesas` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `CalculoRemesas`(IN vFechaRemesa DATE)
BEGIN

	DROP TEMPORARY TABLE IF EXISTS TMP_REMESAS;
	CREATE TEMPORARY TABLE TMP_REMESAS 	
		SELECT
			CONCAT(p.NIF,REPEAT('0', 12-LENGTH(p.NIF))) as CIF1,
			cli.Id_Cliente,
			cli.Cliente,
			cli.`IF` as NIF,
			c.PaymentDate as Vencimiento,
			0 ImporteFac,
			cast(c.Recibo as decimal(10,2)) as ImporteRec,
			0 as ImporteActual,
			c.company_id empresa_id,
			cli.RazonSocial,
			cast(c.Recibo as decimal(10,2)) as ImporteTotal,
			cast(c.Recibo as decimal(10,2)) as Saldo,
			p.Proveedor as Empresa,
			e.abbreviation as EMP,
			cli.cuenta,
			iban AS Iban,
			CONVERT(SUBSTRING(iban,5,4),UNSIGNED INT) AS nrbe,
			sepavnl as SEPA,
			corevnl as RecibidoCORE,
			hasLcr,
            be.bic,
            be.`name` entityName
		FROM Clientes cli
		JOIN
			(SELECT risk.company_id,
					c.Id_Cliente,
					sum(risk.amount) as Recibo,
					IF((c.Vencimiento + graceDays) mod 30.001 <= day(vFechaRemesa)
						,TIMESTAMPADD(DAY, (c.Vencimiento + graceDays) MOD 30.001, LAST_DAY(TIMESTAMPADD(MONTH,-1,vFechaRemesa)))
						,TIMESTAMPADD(DAY, (c.Vencimiento + graceDays) MOD 30.001, LAST_DAY(TIMESTAMPADD(MONTH,-2,vFechaRemesa)))    
						) as PaymentDate												
			FROM Clientes c
            JOIN pay_met pm on pm.id = pay_met_id
			JOIN
				(
					SELECT company_id, customer_id, amount
						FROM Clientes c 
							JOIN bi.customer_risk cr ON cr.customer_id = c.Id_Cliente
						WHERE pay_met_id = 4
					
				UNION ALL
                    
					SELECT empresa_id, Id_Cliente, - Importe
						FROM Facturas f 
							JOIN Clientes c using(Id_Cliente)
							JOIN pay_met pm on pm.id = pay_met_id
						WHERE f.Vencimiento > vFechaRemesa
							AND pay_met_id = 4 AND pm.deudaviva
							AND Importe > 0
						
				) risk ON c.Id_Cliente = risk.customer_id
				GROUP BY risk.company_id, Id_Cliente
			HAVING Recibo > 10
			) c on c.Id_Cliente = cli.Id_Cliente
		JOIN Proveedores p on p.Id_Proveedor = c.company_id
		JOIN empresa e on e.id = c.company_id
        LEFT JOIN vn.bankEntity be ON be.id = cli.bankEntityFk; 
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `CalculoRemesasKk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `CalculoRemesasKk`(IN vFechaRemesa DATE)
BEGIN

	DROP TEMPORARY TABLE IF EXISTS TMP_REMESAS;
	CREATE TEMPORARY TABLE TMP_REMESAS 	
		SELECT
			CONCAT(p.NIF,REPEAT('0', 12-LENGTH(p.NIF))) as CIF1,
			cli.Id_Cliente,
			cli.Cliente,
			cli.`IF` as NIF,
			c.PaymentDate as Vencimiento,
			0 ImporteFac,
			cast(c.Recibo as decimal(10,2)) as ImporteRec,
			0 as ImporteActual,
			c.company_id empresa_id,
			cli.RazonSocial,
			cast(c.Recibo as decimal(10,2)) as ImporteTotal,
			cast(c.Recibo as decimal(10,2)) as Saldo,
			p.Proveedor as Empresa,
			e.abbreviation as EMP,
			cli.cuenta,
			iban AS Iban,
			CONVERT(SUBSTRING(iban,5,4),UNSIGNED INT) AS nrbe ,
			sepavnl as SEPA,
			corevnl as RecibidoCORE,
			hasLcr
            -- JGF descomentar cuando en salix este el bankEntityFk -- bic
            -- JGF descomentar cuando en salix este el bankEntityFk -- description
		FROM Clientes cli
		JOIN
			(SELECT risk.company_id,
					c.Id_Cliente,
					sum(risk.amount) as Recibo,
					IF((c.Vencimiento + graceDays) mod 30.001 <= day(vFechaRemesa)
						,TIMESTAMPADD(DAY, (c.Vencimiento + graceDays) MOD 30.001, LAST_DAY(TIMESTAMPADD(MONTH,-1,vFechaRemesa)))
						,TIMESTAMPADD(DAY, (c.Vencimiento + graceDays) MOD 30.001, LAST_DAY(TIMESTAMPADD(MONTH,-2,vFechaRemesa)))    
						) as PaymentDate												
			FROM Clientes c
            JOIN pay_met pm on pm.id = pay_met_id
			JOIN
				(
					SELECT company_id, customer_id, amount
						FROM Clientes c 
							JOIN bi.customer_risk cr ON cr.customer_id = c.Id_Cliente
						WHERE pay_met_id = 4
					
				UNION ALL
                    
					SELECT empresa_id, Id_Cliente, - Importe
						FROM Facturas f 
							JOIN Clientes c using(Id_Cliente)
							JOIN pay_met pm on pm.id = pay_met_id
						WHERE f.Vencimiento > vFechaRemesa
							AND pay_met_id = 4 AND deudaviva
							AND Importe > 0
						
				) risk ON c.Id_Cliente = risk.customer_id
				GROUP BY risk.company_id, Id_Cliente
			HAVING Recibo > 10
			) c on c.Id_Cliente = cli.Id_Cliente
		JOIN Proveedores p on p.Id_Proveedor = c.company_id
		JOIN empresa e on e.id = c.company_id
        -- JGF descomentar cuando en salix este el bankEntityFk -- LEFT JOIN vn.bankEntity be ON be.id = c.bankEntityFk 
        ; 
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `calling` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `calling`()
BEGIN

DROP TEMPORARY TABLE IF EXISTS Agenda, Agenda2;


 CREATE TEMPORARY TABLE IF NOT EXISTS Agenda (Telefono varchar(15) PRIMARY KEY, Cliente  VARCHAR(45));

CREATE TEMPORARY TABLE IF NOT EXISTS Agenda2 LIKE Agenda;

REPLACE Agenda(Telefono, Cliente)  
       SELECT Telefono, Nombre from v_Agenda2;
               

REPLACE Agenda(Telefono, Cliente) 
     SELECT DISTINCT src, clid FROM cdr  WHERE src < 6000 AND clid NOT LIKE '%device%' 
       AND calldate > TIMESTAMPADD(DAY, -7,CURDATE()) ;

      
      
INSERT INTO Agenda2(Telefono, Cliente)  
               SELECT Telefono, Cliente FROM Agenda; 

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `camiones` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `camiones`(vWarehouse INT, vDate DATE)
BEGIN
	SELECT Temperatura
		,ROUND(SUM(Etiquetas * volume)) AS cm3 
		,ROUND(SUM(IF(scanned, Etiquetas, 0) * volume)) AS cm3s
		,ROUND(SUM(Vida * volume)) AS cm3e 
		FROM (
			SELECT t.Temperatura, c.Etiquetas, b.scanned, c.Vida,
					IF(cu.Volumen > 0, cu.Volumen, cu.x * cu.y * IF(cu.z > 0, cu.z, a.Medida + 10)) volume
				FROM Compres c
					LEFT JOIN buy_edi b ON b.id = c.buy_edi_id
					JOIN Articles a ON a.Id_Article = c.Id_Article
					JOIN Tipos t ON t.tipo_id = a.tipo_id
					JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
					JOIN travel tr ON tr.id = e.travel_id
					JOIN Cubos cu ON cu.Id_Cubo = c.Id_Cubo
				WHERE tr.warehouse_id = vWarehouse
					AND tr.landing = vDate
		) sub
		GROUP BY Temperatura;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `Campaigns_Generator` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `Campaigns_Generator`(IN datFEC DATE, IN intDAYS INT, IN intIMP INT)
BEGIN
DELETE FROM Campaigns;

INSERT INTO Campaigns(Id_Cliente, Notas)
SELECT T.Id_Cliente, CONCAT('Consumo aÃ±o anterior: ',FORMAT(SUM(M.Cantidad * M.Preu * (100 - M.Descuento) / 100), 0), ' â‚¬ ') as Total
FROM Movimientos M
INNER JOIN Tickets T ON T.Id_Ticket = M.Id_Ticket
WHERE Date(T.Fecha) BETWEEN ADDDATE(datFEC,-1 * intDAYS) AND datFEC
GROUP BY T.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 `check_table_existence` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `check_table_existence`(IN table_name CHAR(64))
BEGIN
    DECLARE CONTINUE HANDLER FOR SQLSTATE '42S02' SET @err = 1;
    SET @err = 0;
    SET @table_name = table_name;
    SET @sqlString = CONCAT('SELECT NULL FROM ',@table_name);
    PREPARE stmt1 FROM @sqlString;
    IF (@err = 1) THEN
        SET @table_exists = 0;
    ELSE
        SET @table_exists = 1;
        DEALLOCATE PREPARE stmt1;
    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 `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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clean`(IN `v_full` TINYINT(1))
proc: BEGIN
	DECLARE v_date DATETIME;
	DECLARE v_date18 DATETIME;
	DECLARE v_date8 DATE;
	DECLARE v_date6 DATE;
	DECLARE v_date3Month DATE;
    DECLARE vDate2000 DATE;
    DECLARE vRangeDeleteTicket INT;
	DECLARE strtable varchar(15)  DEFAULT NULL;
	DECLARE done BIT DEFAULT 0;

	SET v_date = TIMESTAMPADD(MONTH, -2, CURDATE());
	SET v_date18 = TIMESTAMPADD(MONTH, -18,CURDATE());
	SET v_date3Month = TIMESTAMPADD(MONTH, -3, CURDATE());
	SET v_date8 = TIMESTAMPADD(DAY, -8,CURDATE());
	SET v_date6 = TIMESTAMPADD(DAY, -6,CURDATE());
	SET vRangeDeleteTicket = 60;

	DELETE FROM cdr WHERE calldate < v_date;
	DELETE FROM Monitoring WHERE ODBC_TIME < v_date;
	DELETE FROM Conteo WHERE Fecha < v_date;
	DELETE FROM XDiario WHERE FECHA < v_date3Month OR FECHA IS NULL;
	DELETE FROM mail WHERE DATE_ODBC < v_date;

	-- DELETE FROM Cajas WHERE CajaFecha < v_date18;

	DELETE rr FROM Recibos_recorded rr JOIN Recibos r ON rr.Id_Recibos = r.Id WHERE r.Fechacobro < v_date;

	SELECT MAX(idTickets_dits)
		INTO @id 
		FROM Tickets_dits 
		WHERE ODBC_DATE < v_date;
	DELETE FROM Tickets_dits WHERE idTickets_dits <= @id;

	DELETE FROM expeditions WHERE odbc_date < v_date18;
	DELETE FROM expeditions_deleted WHERE odbc_date < v_date18;
	DELETE FROM Entradas_dits WHERE ODBC_DATE < v_date18;
	DELETE FROM log_articles WHERE ODBC_DATE < v_date;
	DELETE FROM sms WHERE DATE_ODBC < v_date18;
	DELETE FROM Movimientos_mark WHERE odbc_date < v_date;
	DELETE FROM Splits WHERE Fecha < v_date18;
	DELETE ts FROM Tickets_stack ts JOIN Tickets t ON ts.Id_Ticket = t.Id_Ticket WHERE t.Fecha < v_date;
	DELETE tobs FROM ticket_observation tobs JOIN Tickets t ON tobs.Id_Ticket = t.Id_Ticket WHERE t.Fecha < v_date;
	DELETE tobs FROM movement_label tobs JOIN Movimientos m ON tobs.Id_Movimiento = m.Id_Movimiento 
			JOIN Tickets t ON m.Id_Ticket = t.Id_Ticket WHERE t.Fecha < v_date;
	DELETE FROM chat WHERE odbc_date < v_date;
	DELETE FROM Extractos WHERE Fecha < v_date;
	DELETE FROM Remesas WHERE `Fecha Remesa`  < v_date18;
	DELETE FROM sharingcart where datEND < v_date;
	DELETE FROM sharingclient where datEND < v_date;
	DELETE FROM Stockcontrol WHERE Datestart < v_date18;
	-- DELETE FROM reference_rate WHERE date < v_date18;
    DELETE tt.* FROM Tickets_turno tt LEFT JOIN Movimientos m using(Id_Ticket) WHERE m.Id_Article IS NULL;
	DELETE FROM cl_main WHERE Fecha < v_date18;
	DELETE FROM hedera.`order` WHERE date_send < v_date18;
    -- DELETE FROM Ordenes WHERE odbc_date < v_date18; JGF 2018-12-21 Si estan en un turno no hay que borrarlas.
    
	SELECT MAX(inter_id)
		INTO @id 
		FROM vncontrol.inter 
		WHERE odbc_date < v_date18;
	DELETE FROM vncontrol.inter WHERE inter_id <= @id;

	DELETE FROM Entradas_dits WHERE ODBC_DATE < v_date;
	DELETE FROM cyc_declaration WHERE Fecha < v_date18;
	DELETE FROM vn.message WHERE sendDate < v_date;
	DELETE FROM travel_reserve WHERE odbc_date < v_date;
	-- DELETE FROM syslog.systemevents WHERE odbc_date < v_date8;

	DELETE mc FROM Movimientos_checked mc JOIN Movimientos m ON mc.Id_Movimiento = m.Id_Movimiento WHERE m.odbc_date < v_date;
	DELETE FROM cache.departure_limit WHERE Fecha < TIMESTAMPADD(MONTH,-1,CURDATE());
	DELETE cm
		FROM Compres_mark cm 
			JOIN Compres c ON c.Id_Compra = cm.Id_Compra 
			JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
			JOIN travel t ON t.id = e.travel_id
		WHERE t.landing <= v_date;
	DELETE co
		FROM Compres_ok co JOIN Compres c ON c.Id_Compra = co.Id_Compra 
			JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
			JOIN travel t ON t.id = e.travel_id
		WHERE t.landing <= v_date;

	DELETE FROM vn2008.scan WHERE odbc_date < v_date6 AND id <> 1;

	SET vDate2000 = TIMESTAMPADD(YEAR, 2000 - YEAR(CURDATE()), CURDATE());

	IF v_full
    THEN
		DELETE t FROM Tickets t
				LEFT JOIN Tickets_turno tt ON tt.Id_Ticket = t.Id_Ticket
			WHERE Fecha NOT IN ('2000-01-01','2000-01-02')
				AND YEAR(Fecha) = 2000
				AND ABS(DATEDIFF(Fecha,vDate2000)) > vRangeDeleteTicket
                AND tt.Id_Ticket IS NULL;

		DELETE e.* FROM Entradas e
				LEFT JOIN recibida_entrada re ON e.Id_Entrada = re.Id_Entrada
			WHERE travel_id IS NULL 
				AND re.Id_Entrada IS NULL;
	END IF;

	-- Tickets Nulos PAK 11/10/2016

	UPDATE vn2008.Tickets 
		SET empresa_id = 965 
		WHERE Id_Cliente = 31
		AND empresa_id != 965;
		
	-- Equipos duplicados

	DELETE w.* 
		FROM vn2008.workerTeam w
		JOIN (SELECT id, team, user, COUNT(*) - 1 as duplicated
				FROM vn.workerTeam
				GROUP BY team,user
				HAVING duplicated
			 ) d ON d.team = w.team AND d.user = w.user AND d.id != w.id;

    -- CAP 29/10/2018 Mantenimiento tabla Movimientos_componentes 
    
    DELETE mc 
		FROM  vn2008.Movimientos_componentes mc
			JOIN vn2008.Movimientos  mv 
				ON mv.Id_Movimiento=mc.Id_Movimiento
			JOIN vn2008.Tickets t 
				ON t.Id_Ticket= mv.Id_Ticket
		WHERE t.Fecha<v_date18;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clean_launcher`()
BEGIN
	CALL clean(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 `Clientes_Calidad` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `Clientes_Calidad`()
BEGIN

	DECLARE intMONTH INTEGER;
	DECLARE intYEAR INTEGER;

	SET intYEAR = YEAR(Curdate());
	SET intMONTH = MONTH(curdate())-1;

	IF intMONTH = 0 THEN

		SET intYEAR = intYEAR -1;
		SET intMONTH = 12;

	END IF;

	UPDATE Clientes 
	SET 
		Calidad = 0;

	TRUNCATE bi.calidad_detalle;

	INSERT INTO bi.calidad_detalle(Id_Cliente,calidad_parametros_id,valor)
		SELECT Id_Cliente, calidad_parametros_id, 0
		FROM bi.calidad_parametros
		JOIN Clientes;

	-- Valoramos del 0 al 5 su consumo

	REPLACE INTO bi.calidad_detalle(Id_Cliente,calidad_parametros_id,valor)
		SELECT Id_Cliente, 1, LEAST(5, Consumo) 
		FROM (
		SELECT Id_Cliente, round(sum(importe)/1000) as Consumo
		from bs.ventas v
		join vn2008.time t on t.date = v.fecha
		where year =intYEAR and month = intMONTH
		group by Id_Cliente) sub;


	-- Incrementamos dos puntos a los de giro bancario, y restamos uno a los de pago contado/contrareembolso

	REPLACE INTO bi.calidad_detalle(Id_Cliente,calidad_parametros_id,valor)
		SELECT Id_Cliente, 3, CASE pay_met_id WHEN 4   -- giro
																						  THEN 2

																		WHEN 1  -- contado
																						  THEN -1 

																		WHEN 5   -- tarjeta

																							THEN 1

																		WHEN 7   -- tarjeta

																							THEN 1

																		 WHEN 6 -- contrareembolso
																						   THEN -1 

																	   ELSE 0 END
	FROM Clientes;

	/* Incrementamos a los que tengan reclamaciones 0%, 2 puntos
	1%, +1 punto
	2%   0 puntos
	3%  -3 puntos
	4%  -6 puntos
	5%  -9 puntos
	*/

	REPLACE INTO bi.calidad_detalle(Id_Cliente,calidad_parametros_id,valor)
	SELECT Id_Cliente, 2,  CASE nz(Ratio) 
											 WHEN 0 THEN 2 
											 WHEN 0.01 THEN 1 
											 WHEN 0.02 THEN 0 
											 WHEN 0.03 THEN -3 
											 WHEN 0.04 THEN -6
											ELSE -9
											 END
	FROM bi.claims_ratio ;

	-- Ahora les ponemos un punto a los que compran por la web mas del 50% de sus pedidos

	REPLACE INTO bi.calidad_detalle(Id_Cliente,calidad_parametros_id,valor)
	SELECT Id_Cliente, 4, Webs
	FROM
	( SELECT Id_Cliente, sum(sub.Id_Trabajador = 4) / count(sub.Id_Trabajador)  as Webs
	FROM Tickets
	JOIN 
	(SELECT Id_Ticket, Id_Trabajador
	FROM Tickets_dits
	WHERE idaccion_dits = 84
	AND ODBC_DATE >= TIMESTAMPADD(DAY,-30,CURDATE())) sub USING(Id_Ticket)
	WHERE Fecha > '2001-01-01' AND Id_Agencia <> 23 -- ni tickets borrados, ni abonos cuentan
	GROUP BY Id_Cliente
	HAVING Webs > 0.5) sub2;


	-- Marcamos con un 11 a los clientes recien nacidos, para protegerlos

	REPLACE INTO bi.calidad_detalle(Id_Cliente,calidad_parametros_id,valor)
	SELECT Id_Cliente, 5, 11
	FROM
	(SELECT Id_Cliente, MIN(Fecha) as Inicio
	FROM Tickets
	WHERE Fecha > '2001-01-01'
	GROUP BY Id_Cliente
	HAVING Inicio >= TIMESTAMPADD(DAY,-30,CURDATE())) sub ;

	-- Ahora actualizamos la tabla Clientes

	UPDATE Clientes
			JOIN
		(SELECT 
			Id_Cliente, SUM(valor) AS valoracion
		FROM
			bi.calidad_detalle
		GROUP BY Id_Cliente) sub USING (Id_Cliente) 
	SET 
		calidad = IF(valoracion > 11, 11, valoracion);

	IF DAY(CURDATE()) = 1 THEN
		-- Y de paso, desactivamos a los que hace tiempo que no compran.alter
		-- JGF Sólo desctivamos a los clientes que no han comprado en los dos ultimos meses
		UPDATE account.user u 
		SET 
			active = 0
		WHERE
			u.role = 2
				AND id NOT IN (SELECT DISTINCT
					c.Id_Cliente
				FROM
					Clientes c LEFT JOIN Tickets t ON t.Id_Cliente = c.Id_Cliente
				WHERE
					Created > TIMESTAMPADD(MONTH, - 2, CURDATE()) OR
					Fecha > TIMESTAMPADD(MONTH, - 2, 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 `Clientes_Calidad_detalle` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `Clientes_Calidad_detalle`(IN IdC INT)
BEGIN


SELECT descripcion Concepto,  valor Puntos
FROM bi.calidad_parametros
JOIN bi.calidad_detalle using(calidad_parametros_id)
WHERE Id_Cliente = idC;



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



DROP TEMPORARY TABLE IF EXISTS clientes_pendientes;

CREATE TEMPORARY TABLE clientes_pendientes
( Id_Cliente INT NOT NULL
, empresa_id INT NOT NULL
, saldo double NOT NULL
, PRIMARY KEY(Id_Cliente, empresa_id));

INSERT INTO clientes_pendientes
SELECT Id_Cliente, empresa_id, sum(importe) as saldo
    FROM
    (
		SELECT 
				Id_Cliente,
				empresa_id,
				- Entregado as importe
				
		FROM
				Recibos
		JOIN
				Clientes USING(Id_Cliente)
		JOIN 
				pay_met p on p.id = pay_met_id
		WHERE 
				deudaviva
				
		   
    UNION ALL
    
    
		SELECT 
				Id_Cliente,
				empresa_id,
				Importe
				
		FROM
				Facturas
		JOIN
				Clientes USING(Id_Cliente)
		JOIN 
				pay_met p on p.id = pay_met_id
		WHERE 
				deudaviva
			
					
    ) sub
    GROUP BY empresa_id, Id_Cliente
    having saldo > 0;
    
   
    
    DROP TEMPORARY TABLE IF EXISTS cobros_pendientes;
    
    CREATE TEMPORARY TABLE cobros_pendientes
    (Id_Cliente INT
    ,fecha DATE
    ,empresa_id INT NOT NULL
    ,saldo DOUBLE
    ,PRIMARY KEY(Id_Cliente, empresa_id));
    
	
    
	INSERT INTO cobros_pendientes(Id_Cliente
                                      , fecha
                                      , empresa_id
                                      , saldo)
    
    
    
    SELECT cp.Id_Cliente, 
           CASE (vencimiento > 30)
           
				WHEN TRUE THEN
                
					timestampadd(DAY,vencimiento,maxFecha)	
                    
                ELSE
                
					timestampadd(
									 DAY                              
									,vencimiento - day(maxFecha)
									,timestampadd(MONTH,1,maxFecha)
                                )
                
			END as fecha,
           cp.empresa_id,
           cp.saldo
    FROM clientes_pendientes cp
    JOIN Clientes USING(Id_Cliente)
    JOIN (  SELECT
					max(Fecha) as maxFecha,
					Id_Cliente,
					empresa_id 
			FROM 
					Facturas
			GROUP BY
					Id_Cliente,
                    empresa_id
		) mf on mf.Id_Cliente = cp.Id_Cliente 
            AND mf.empresa_id = cp.empresa_id;

	
    SELECT * FROM cobros_pendientes;
    
    DROP TEMPORARY TABLE cobros_pendientes; 
    DROP TEMPORARY TABLE clientes_pendientes;
    

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `clientManaGrouped` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clientManaGrouped`(vClient INT)
BEGIN
   
        SELECT 'Tickets' as Grupo, CAST(sum(s.quantity * Valor) AS DECIMAL(10,2)) as Mana
             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 BETWEEN '2016-01-01' AND CURDATE()
				AND t.clientFk = vClient

		UNION ALL

		SELECT 'Recibos' as Grupo, - sum(Entregado) as Mana
			FROM vn2008.Recibos r
				JOIN vn2008.Clientes c using(Id_Cliente)
			WHERE r.Id_Banco = 66
				AND r.Fechacobro BETWEEN '2016-01-01' AND CURDATE()
				AND c.Id_Cliente = vClient
			
        UNION ALL
        
        SELECT 'Greuges' as Grupo, sum(g.Importe) as Mana
			FROM vn2008.Greuges g
				JOIN vn2008.Clientes c using(Id_Cliente)
			WHERE g.Greuges_type_id = 3 -- Maná
				AND g.Fecha BETWEEN '2016-01-01' AND CURDATE()
				AND c.Id_Cliente = 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 PROCEDURE IF EXISTS `clonWeeklyTickets` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clonWeeklyTickets`(IN vWeek INT)
BEGIN
	DECLARE done BIT DEFAULT 0;
	DECLARE vLanding DATE;
	DECLARE vShipment DATE;
	DECLARE vWarehouse INT;
    DECLARE vTicket INT;
    DECLARE vWeekDay INT;
    DECLARE vClient INT;
    DECLARE vEmpresa INT;
    DECLARE vConsignatario INT;
    DECLARE vAgencia INT;
    DECLARE vNewTicket INT;
    DECLARE vYear INT;
    
    DECLARE rsTicket CURSOR FOR
	SELECT tt.Id_Ticket, weekDay, Id_Cliente, warehouse_id, empresa_id, Id_Consigna, Id_Agencia
		FROM Tickets_turno tt 
		JOIN Tickets t ON tt.Id_Ticket = t.Id_Ticket;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

	SET done = 0;
    SET vYear = YEAR(CURDATE()) + IF(vWeek < WEEK(CURDATE()),1, 0);
    
	OPEN rsTicket;

	FETCH rsTicket INTO vTicket, vWeekDay, vClient, vWarehouse, vEmpresa, vConsignatario, vAgencia;

	WHILE NOT done DO
    
		SELECT date INTO vShipment 
		FROM time
		WHERE year = vYear AND week = vWeek
			AND WEEKDAY(date) = vWeekDay;
        
        -- busca si el ticket ya ha sido clonado
        IF (select count(*) FROM Tickets t JOIN ticket_observation tob ON t.Id_Ticket = tob.Id_Ticket
			WHERE Id_Consigna = vConsignatario AND Fecha = vShipment AND tob.text LIKE CONCAT('%',vTicket,'%')) = 0 
		THEN

			IF (SELECT COUNT(*) FROM Agencias WHERE Id_Agencia = vAgencia AND Agencia LIKE '%turno%') THEN
				SET vAgencia = NULL;
			END IF;

			CALL vn.ticketCreate(vClient, vShipment, vWarehouse, vEmpresa, vConsignatario, vAgencia, NULL, vLanding, vNewTicket);

			INSERT INTO Movimientos (Id_Ticket, Id_Article, Concepte, Cantidad, Preu, Descuento, CostFixat, PrecioFijado)
				SELECT vNewTicket, Id_Article, Concepte, Cantidad, Preu, Descuento, CostFixat, PrecioFijado
					FROM Movimientos WHERE Id_Ticket = vTicket;
					
			INSERT INTO Ordenes (orden,datorden,datticket,codvendedor,codcomprador,cantidad,preciomax,preu,id_article,id_cliente,comentario,
						ok, total,datcompra,ko,id_movimiento)
				SELECT o.orden,o.datorden,vShipment,o.codvendedor,o.codcomprador,o.cantidad,o.preciomax,o.preu,o.id_article,o.id_cliente,o.comentario,
						o.ok, o.total,o.datcompra,o.ko,m2.Id_Movimiento
					FROM Movimientos m JOIN Ordenes o ON o.Id_Movimiento = m.Id_Movimiento
						JOIN Movimientos m2 ON m.Concepte = m2.Concepte AND m.Cantidad = m2.Cantidad AND m.Id_Article = m2.Id_Article
						WHERE m.Id_Ticket = vTicket AND m2.Id_Ticket = vNewTicket;
				            
			INSERT INTO ticket_observation(Id_Ticket,observation_type_id,text) VALUES(vNewTicket,4,CONCAT('turno desde ticket: ',vTicket))
				ON DUPLICATE KEY UPDATE text = CONCAT(ticket_observation.text,VALUES(text),' ');  
			
			INSERT INTO ticket_observation(Id_Ticket,observation_type_id,text) VALUES(vNewTicket,1,'ATENCION: Contiene lineas de TURNO')
				ON DUPLICATE KEY UPDATE text = CONCAT(ticket_observation.text,VALUES(text),' ');  
           
			CALL bionic_calc_clon(vNewTicket);
        END IF;
		FETCH rsTicket INTO vTicket, vWeekDay, vClient, vWarehouse, vEmpresa, vConsignatario, vAgencia;
		
	END WHILE;

	CLOSE rsTicket;
    
    DROP TEMPORARY TABLE IF EXISTS travel_tree_shipment;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cobro` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `cobro`(IN datFEC DATE
                      , IN idCLI INT
                      , IN dblIMPORTE DOUBLE
                      , IN idCAJA INT
                      , IN idPAYMET INT
                      , IN strCONCEPTO VARCHAR(40)
                      , IN idEMP INT
                      , IN idWH INT
                      , IN idTRABAJADOR INT)
BEGIN
		
        DECLARE bolCASH BOOLEAN;
        DECLARE cuenta_banco BIGINT;
        DECLARE cuenta_cliente BIGINT;
        DECLARE max_asien INT;

    -- XDIARIO
    -- No se asientan los cobros directamente, salvo en el caso de las cajas de CASH
        SELECT (cash = 1) INTO bolCASH FROM Bancos WHERE Bancos.Id_Banco = idCAJA;
        
        IF bolCASH  THEN 
        
					SELECT Cuenta INTO cuenta_banco FROM Bancos WHERE Id_Banco = idCAJA;
					SELECT Cuenta INTO cuenta_cliente FROM Clientes WHERE Id_Cliente = idCLI;
					SELECT MAX(asien)+1 INTO max_asien FROM XDiario;
					
					INSERT INTO XDiario (ASIEN,FECHA,SUBCTA,CONTRA,CONCEPTO,EURODEBE,EUROHABER,empresa_id)
						SELECT max_asien,datFEC,SUBCTA,CONTRA,strCONCEPTO,EURODEBE,EUROHABER,idEMP FROM
							(
                             SELECT cuenta_banco SUBCTA, cuenta_cliente CONTRA, 0 EURODEBE, dblIMPORTE EUROHABER
					         UNION ALL
						     SELECT cuenta_cliente SUBCTA, cuenta_banco CONTRA, dblIMPORTE EURODEBE, 0 EUROHABER
                             ) gf;
				
                
		END IF;


     -- CAJERA
     
	  INSERT INTO Cajas(Id_Trabajador
                      , Id_Banco
                      , Entrada
                      , Concepto
                      , Cajafecha
                      , Serie
                      , Partida
                      , Numero
                      ,empresa_id
                      ,warehouse_id)
                      
			  VALUES ( idTRABAJADOR
					 , idCAJA
					 , dblIMPORTE
					 , strCONCEPTO
					 , datFEC
					 , 'A'
					 , TRUE
					 , idCLI
					 , idEMP
					 , idWH );
     


       -- RECIBO
       INSERT INTO Recibos(Entregado
                          ,Fechacobro
                          ,Id_Trabajador
                          ,Id_Banco
                          ,Id_Cliente
                          ,Id_Factura
                          ,empresa_id)
                          
				VALUES   ( dblIMPORTE
						 , datFEC
						 , idTRABAJADOR
                		 , idCAJA
						 , idCLI
						 , strCONCEPTO
						 , idEMP);
               



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

	INSERT INTO vn2008.Colas(Id_Informe,Id_Trabajador) VALUES (11,57);
	INSERT INTO vn2008.Colas(Id_Informe) VALUES (16);
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `comercial_caducado` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `comercial_caducado`()
BEGIN

-- Este procedimiento le pasa los clientes al jefe de ventas cuando llevan dos meses inactivos

IF day(CURDATE()) = 5 then  -- solo se ejecuta los dias 5 de cada mes

		Update Clientes 
        join
        (
			Select c.Id_Cliente
			from Clientes c
			join jerarquia j on j.worker_id = c.Id_Trabajador  -- este filtro es para que solo toque los de los comerciales
            
            join
					(
                    select Id_Cliente, sum(Importe) as Saldo
                    from
						(
						select Id_Cliente, Importe from Facturas
						union all
						select Id_Cliente, - Entregado from Recibos 
                        ) sub
                        group by Id_Cliente
					) sindeuda on sindeuda.Id_Cliente = c.Id_Cliente
            
			left join
						(
							select distinct Id_Cliente
							from Facturas 
							where Fecha BETWEEN CURDATE() - INTERVAL 12 MONTH AND CURDATE()
						) f on f.Id_Cliente = c.Id_Cliente
                        
			left join
						(
							select distinct Id_Cliente
                            from Tickets
                            where Fecha between CURDATE() - INTERVAL 2 DAY AND CURDATE() + INTERVAL 200 DAY
						
                        ) tic_vivos on tic_vivos.Id_Cliente = c.Id_Cliente
                        
			where c.Created < CURDATE() - INTERVAL 2 MONTH  -- este filtro respeta a los recien nacidos....
            and j.boss_id = 87  -- sólo afecta a los comerciales de Alfredo
			and  f.Id_Cliente is null  -- comprueba que no tenga facturas en los dos ultimos meses
            and sindeuda.Saldo < 10 -- sólo cambia a los clientes con deuda escasa o nula
            and tic_vivos.Id_Cliente is null -- si tiene tickets vivos, lo respeta
            
            
        ) sub using(Id_Cliente)
        
        set Id_Trabajador = 87 ;-- Alfredo Giner;

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_clientes` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_clientes`(IN v_date DATE,IN i_vendedor INT, IN i_comprador INT, IN i_tipo INT, IN i_wh INT, IN days INT)
BEGIN

DECLARE date_cyear_ini DATETIME;
DECLARE date_cyear_end DATETIME;
DECLARE date_lyear_ini DATETIME;
DECLARE date_lyear_end DATETIME;
DECLARE week_count TINYINT DEFAULT 7;


SET date_cyear_ini = TIMESTAMP(DATE(TIMESTAMPADD(DAY, -22 - WEEKDAY(v_date), v_date)), '00:00:00');
SET date_cyear_end = TIMESTAMP(DATE(TIMESTAMPADD(DAY, (7 * week_count) -1, date_cyear_ini)), '23:59:59');
SET date_lyear_ini = TIMESTAMPADD(DAY,-364,date_cyear_ini);
SET date_lyear_end = TIMESTAMPADD(DAY,-364,date_cyear_end);

	CALL article ();

	INSERT INTO article_inventory (article_id)
		SELECT Id_Article 
        FROM Articles a 
			JOIN Tipos t ON t.tipo_id = a.tipo_id
			LEFT JOIN reinos r ON r.id = t.reino_id
		WHERE (i_tipo = 0 OR a.tipo_id = i_tipo)
			AND r.display <> 0;

	IF v_date < CURDATE()
	THEN
		ALTER TABLE `article_inventory`
			ADD `buy_id` INT NOT NULL DEFAULT 0,
			ADD `buy_date` DATE DEFAULT '2000-01-01',
			ADD `life` INT DEFAULT 0,
			ADD `sd` INT DEFAULT 0,
			ADD `avalaible` INT DEFAULT 0,
			ADD `visible` INT DEFAULT 0;

	ELSE
		CALL inventario_multiple_2 (v_date, i_wh, days);
		CALL article_multiple_buy (v_date, i_wh);
		CALL article_multiple_buy_date (v_date, i_wh);
    END IF;



DROP TEMPORARY TABLE IF EXISTS clientcom;
CREATE TEMPORARY TABLE clientcom
SELECT vnperiod(Fecha) as period
                  ,Id_Article
				 , Cantidad
				 , Preu
				 , CS.Id_Cliente
					FROM vn2008.Movimientos M			
						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.Articles a USING (Id_Article)	
						LEFT JOIN vn2008.Tipos tp ON tp.tipo_id = a.tipo_id
						LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id
					WHERE (T.Fecha BETWEEN date_cyear_ini AND date_cyear_end or T.Fecha BETWEEN date_lyear_ini AND date_lyear_end)
						AND T.Id_Cliente NOT IN(400,200)
						AND i_vendedor IN (0, C.Id_Trabajador )
						AND i_comprador IN (0, tp.Id_Trabajador)
						AND i_tipo IN (0,tp.tipo_id)
						AND r.display <> 0 AND T.warehouse_id NOT IN (0,13)	
					ORDER BY period;

DROP TEMPORARY TABLE IF EXISTS clientcom_periods;
CREATE TEMPORARY TABLE clientcom_periods
SELECT period, @order:= @order + 1 as period_order
FROM (
SELECT DISTINCT period, @order:=0 
FROM clientcom
ORDER BY period) sub;

SELECT cc.Id_Article
				 , cc.Id_Cliente
				 ,CAST(SUM(IF(period_order = 1, cc.Cantidad, 0)) AS SIGNED) AS lweek1
				,CAST(SUM(IF(period_order = 2, cc.Cantidad, 0)) AS SIGNED) AS lweek2
				,CAST(SUM(IF(period_order = 3, cc.Cantidad, 0)) AS SIGNED) AS lweek3
				,CAST(SUM(IF(period_order = 4, cc.Cantidad, 0)) AS SIGNED) AS lweek4
				,CAST(SUM(IF(period_order = 5, cc.Cantidad, 0)) AS SIGNED) AS lweek5
				,CAST(SUM(IF(period_order = 6, cc.Cantidad, 0)) AS SIGNED) AS lweek6
				,CAST(SUM(IF(period_order = 7, cc.Cantidad, 0)) AS SIGNED) AS lweek7
				,CAST(SUM(IF(period_order = 7+1, cc.Cantidad, 0)) AS SIGNED) AS cweek1
				,CAST(SUM(IF(period_order = 7+2, cc.Cantidad, 0)) AS SIGNED) AS cweek2
				,CAST(SUM(IF(period_order = 7+3, cc.Cantidad, 0)) AS SIGNED) AS cweek3
				,CAST(SUM(IF(period_order = 7+4, cc.Cantidad, 0)) AS SIGNED) AS cweek4
				,CAST(SUM(IF(period_order = 7+5, cc.Cantidad, 0)) AS SIGNED) AS cweek5
				,CAST(SUM(IF(period_order = 7+6, cc.Cantidad, 0)) AS SIGNED) AS cweek6
				,CAST(SUM(IF(period_order = 7+7, cc.Cantidad, 0)) AS SIGNED) AS cweek7
							
				,CAST(SUM(IF(period_order = 1, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice1
				,CAST(SUM(IF(period_order = 2, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice2
				,CAST(SUM(IF(period_order = 3, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice3
				,CAST(SUM(IF(period_order = 4, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice4
				,CAST(SUM(IF(period_order = 5, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice5
				,CAST(SUM(IF(period_order = 6, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice6
				,CAST(SUM(IF(period_order = 7, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice7
				,CAST(SUM(IF(period_order = 7+1, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice1
				,CAST(SUM(IF(period_order = 7+2, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice2
				,CAST(SUM(IF(period_order = 7+3, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice3
				,CAST(SUM(IF(period_order = 7+4, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice4
				,CAST(SUM(IF(period_order = 7+5, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice5
				,CAST(SUM(IF(period_order = 7+6, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice6
				,CAST(SUM(IF(period_order = 7+7, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice7
				
				,A.Article
				,A.Medida
				,A.Color
				,A.tipo_id
				,C.Cliente
				,T1.CodigoTrabajador as Comercial
				,O.Abreviatura as Origen
				,TT.ball as Tinta
				,r.reino as Reino
				,TP.Id_Tipo
				,JF.CodigoTrabajador as Equipo
				,T2.CodigoTrabajador as Comprador
				,TT.orden as Orden_Color

,i.buy_id	
, i.life 
, CAST(IFNULL(i.sd,0) AS SIGNED) as sd
,CAST(i.avalaible AS SIGNED) avalaible
, CAST(i.visible AS SIGNED) visible
, i.buy_date
,P.Proveedor

FROM clientcom cc
JOIN clientcom_periods ccp using(period)
-- La parte del inventario
LEFT JOIN article_inventory i ON i.article_id = cc.Id_Article
LEFT JOIN Compres CM ON i.buy_id = CM.Id_Compra		
LEFT JOIN Entradas E USING(Id_Entrada)	
LEFT JOIN Proveedores P ON P.Id_Proveedor = E.Id_Proveedor	
-- Ahora la parte de los vendedores
JOIN Clientes C ON C.Id_Cliente = cc.Id_Cliente
JOIN Trabajadores T1 ON C.Id_Trabajador = T1.Id_Trabajador
LEFT JOIN jerarquia J ON J.worker_id = T1.Id_Trabajador
JOIN Trabajadores JF ON JF.Id_Trabajador = J.boss_id
-- JOIN Trabajadores JF ON T1.Id_Trabajador = JF.boss JGF propuesta para sustituir por las dos lineas superiores 

-- Ahora la parte de los compradores
JOIN Articles A ON A.Id_Article = cc.Id_Article
JOIN Origen O ON O.id = A.id_origen
JOIN Tintas TT ON TT.Id_Tinta = A.Color
JOIN Tipos TP ON TP.tipo_id = A.tipo_id
JOIN reinos r ON r.id = TP.reino_id
JOIN Trabajadores T2 ON T2.Id_Trabajador = TP.Id_Trabajador

GROUP BY Id_Article,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 `comparativa_clientes_tickets` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `comparativa_clientes_tickets`(IN i_week INT
																 , IN i_year INT
																, IN i_vendedor INT
																, IN i_comprador INT
																, IN i_article INT
																, IN i_cliente INT
																, IN i_tipo INT
																, IN i_reino INT
																, IN i_equipo INT
																, IN v_color varchar(3))
BEGIN

DECLARE datSTART DATETIME;
DECLARE datEND DATETIME;

SELECT min(date), TIMESTAMP(max(date),'23:59:59') INTO datSTART, datEND FROM time WHERE i_week = week AND i_year = year;



SELECT T.Id_Ticket, Fecha, Alias, Id_Article, Concepte, Cantidad, Preu, M.Descuento, Cantidad * Preu * (100-M.Descuento)/100 as Importe, w.name as almacen
FROM Movimientos M
JOIN Tickets T  using(Id_Ticket)
JOIN warehouse w on w.id = T.warehouse_id
JOIN Consignatarios CS using(Id_Consigna)
JOIN Clientes C ON C.Id_Cliente = CS.Id_Cliente
JOIN Trabajadores TR ON TR.Id_Trabajador = C.Id_Trabajador
JOIN jerarquia J ON J.worker_id = TR.Id_Trabajador
JOIN Articles A using(Id_Article)
JOIN Tipos TP using(tipo_id)
WHERE T.Fecha BETWEEN datSTART AND datEND
AND i_vendedor IN (0, C.Id_Trabajador)
AND i_comprador IN (0, TP.Id_Trabajador)
AND i_cliente IN (0, CS.Id_Cliente)
AND i_tipo IN (0, A.tipo_id)
AND i_article IN (0,A.Id_Article)
AND i_reino IN (0,TP.reino_id)
AND i_equipo IN(0,J.boss_id)
AND v_color IN ("",A.color);


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `comparative` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `comparative`(
	 v_date DATETIME
	,days TINYINT
	,i_wh TINYINT
	,i_tipo INT
	,i_filtro INT
)
BEGIN
    DECLARE date_cyear_ini DATETIME;
    DECLARE date_cyear_end DATETIME;
    DECLARE week_count TINYINT DEFAULT 7;
    DECLARE w1, w2, w3, w4, w5, w6, w7 INT;
    DECLARE y1, y2, y3, y4, y5, y6, y7 INT;
    DECLARE wperiod INT;-- DECLARE ws, ys INT;  -- PAK 11/01/2016
    DECLARE i INT DEFAULT 0;
    DECLARE strFILTRO VARCHAR(255) DEFAULT 'TRUE';

    IF i_filtro THEN
        SELECT `sql` INTO strFILTRO FROM filtros WHERE id = i_filtro;
    END IF;

    IF days < 0 OR days > 30 THEN
        SET days = 15;
    END IF;

    IF i_wh = NULL THEN
        SET i_wh = 0;
    END IF;
	-- JGF 2015-04-16 cambio -21 por -22 para que la semana cuente de domingo a sabado
	SET date_cyear_ini = TIMESTAMP(DATE(TIMESTAMPADD(DAY, -22 - WEEKDAY(v_date), v_date)), '00:00:00');
	SET date_cyear_end = TIMESTAMP(DATE(TIMESTAMPADD(DAY, (7 * week_count) -1, date_cyear_ini)), '23:59:59');
	-- Eliminamos el calculo del inventario para fechas en el pasado

	DROP TEMPORARY TABLE IF EXISTS `article_inventory`;
	CREATE TEMPORARY TABLE `article_inventory`
	(
		`article_id` INT(11) NOT NULL PRIMARY KEY
	)
	ENGINE = MEMORY;

	INSERT INTO article_inventory (article_id)
		SELECT Id_Article FROM Articles a 
			JOIN Tipos t ON a.tipo_id = t.tipo_id
			LEFT JOIN vn2008.reinos r ON r.id = t.reino_id
		WHERE (i_tipo = 0 OR a.tipo_id = i_tipo)
			AND r.display <> 0;

	IF v_date < CURDATE()
	THEN
		ALTER TABLE `article_inventory`
			ADD `buy_id` INT NOT NULL DEFAULT 0,
			ADD `buy_date` DATE DEFAULT '2000-01-01',
			ADD `life` INT DEFAULT 0,
			ADD `sd` INT DEFAULT 0,
			ADD `avalaible` INT DEFAULT 0,
			ADD `visible` INT DEFAULT 0;

	ELSE

		CALL inventario_multiple_2 (v_date, i_wh, days);

		CALL article_multiple_buy (v_date, i_wh);

		CALL article_multiple_buy_date (v_date, i_wh);


	END IF;
	
    
    DROP TEMPORARY TABLE IF EXISTS wtable;

    CREATE TEMPORARY TABLE wtable (
        cy INT(6),
        ly INT(6)
    );

    REPEAT
        SET i = i + 1;
        SET wperiod = vnperiod(TIMESTAMPADD(DAY, 7*(i - 1), date_cyear_ini)); -- PAK 11/01/2016 
        INSERT INTO wtable(cy, ly) VALUES(wperiod, wperiod - 100); -- VALUES( ys * 100 + ws, (ys -1) * 100 + ws); -- PAK 11/01/2016

    UNTIL i = 7 END REPEAT;
    
    
    SELECT cy, ly INTO w1, y1 FROM wtable limit 1;
    SELECT cy, ly INTO w2, y2 FROM wtable WHERE cy > w1  limit 1;
    SELECT cy, ly INTO w3, y3 FROM wtable WHERE cy > w2  limit 1;
    SELECT cy, ly INTO w4, y4 FROM wtable WHERE cy > w3  limit 1;

    SELECT cy, ly INTO w5, y5 FROM wtable WHERE cy > w4  limit 1;
    SELECT cy, ly INTO w6, y6 FROM wtable WHERE cy > w5  limit 1;
    SELECT cy, ly INTO w7, y7 FROM wtable WHERE cy > w6  limit 1;
    DROP TEMPORARY TABLE wtable;

    -- Genera una tabla con los datos del año pasado.

	DROP TEMPORARY TABLE IF EXISTS last_year;
	CREATE TEMPORARY TABLE last_year
	(KEY (Id_Article))
	ENGINE = MEMORY
	SELECT Id_Article

		,CAST(SUM(IF(Periodo = y1, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek1
		,CAST(SUM(IF(Periodo = y2, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek2
		,CAST(SUM(IF(Periodo = y3, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek3
		,CAST(SUM(IF(Periodo = y4, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek4
		,CAST(SUM(IF(Periodo = y5, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek5
		,CAST(SUM(IF(Periodo = y6, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek6
		,CAST(SUM(IF(Periodo = y7, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek7

		,CAST(SUM(IF(Periodo = y1, price, 0)) AS DECIMAL(10,0)) AS lprice1
		,CAST(SUM(IF(Periodo = y2, price, 0)) AS DECIMAL(10,0)) AS lprice2
		,CAST(SUM(IF(Periodo = y3, price, 0)) AS DECIMAL(10,0)) AS lprice3
		,CAST(SUM(IF(Periodo = y4, price, 0)) AS DECIMAL(10,0)) AS lprice4
		,CAST(SUM(IF(Periodo = y5, price, 0)) AS DECIMAL(10,0)) AS lprice5
		,CAST(SUM(IF(Periodo = y6, price, 0)) AS DECIMAL(10,0)) AS lprice6
		,CAST(SUM(IF(Periodo = y7, price, 0)) AS DECIMAL(10,0)) AS lprice7

        FROM Comparativa 
            JOIN warehouse W on W.id = warehouse_id
            WHERE (Periodo BETWEEN y1 and y7)
            AND IF(i_wh = 0, W.is_comparative, i_wh = warehouse_id)
            GROUP BY Id_Article;

	-- Genera una tabla con los datos de este año.

	DROP TEMPORARY TABLE IF EXISTS cur_year;
	CREATE TEMPORARY TABLE cur_year
	(KEY (Id_Article))
	ENGINE = MEMORY
	SELECT Id_Article

		,CAST(SUM(IF(week = w1, Total, 0)) AS DECIMAL(10,0)) AS cweek1
		,CAST(SUM(IF(week = w2, Total, 0)) AS DECIMAL(10,0)) AS cweek2
		,CAST(SUM(IF(week = w3, Total, 0)) AS DECIMAL(10,0)) AS cweek3
		,CAST(SUM(IF(week = w4, Total, 0)) AS DECIMAL(10,0)) AS cweek4
		,CAST(SUM(IF(week = w5, Total, 0)) AS DECIMAL(10,0)) AS cweek5
		,CAST(SUM(IF(week = w6, Total, 0)) AS DECIMAL(10,0)) AS cweek6
		,CAST(SUM(IF(week = w7, Total, 0)) AS DECIMAL(10,0)) AS cweek7
					
		,CAST(SUM(IF(week = w1, price, 0)) AS DECIMAL(10,0)) AS cprice1
		,CAST(SUM(IF(week = w2, price, 0)) AS DECIMAL(10,0)) AS cprice2
		,CAST(SUM(IF(week = w3, price, 0)) AS DECIMAL(10,0)) AS cprice3
		,CAST(SUM(IF(week = w4, price, 0)) AS DECIMAL(10,0)) AS cprice4
		,CAST(SUM(IF(week = w5, price, 0)) AS DECIMAL(10,0)) AS cprice5
		,CAST(SUM(IF(week = w6, price, 0)) AS DECIMAL(10,0)) AS cprice6
		,CAST(SUM(IF(week = w7, price, 0)) AS DECIMAL(10,0)) AS cprice7

        FROM (
            SELECT A.Id_Article
                ,CTS.period week
                ,SUM(Cantidad) AS Total	    	
				,TRUNCATE(SUM(Cantidad * IF(T.Fecha >= '2015-10-01',M.CostFixat,Preu * (100 - Descuento) / 100)),0) AS price
                FROM Movimientos M
                LEFT JOIN Tickets T ON T.Id_Ticket = M.Id_Ticket
                INNER JOIN `time` CTS ON CTS.`date` = DATE(T.Fecha)
                INNER JOIN Articles A USING (Id_Article)	
                INNER JOIN Tipos tp ON tp.tipo_id = A.tipo_id
                LEFT JOIN reinos r ON r.id = tp.reino_id
                JOIN warehouse W ON W.id = T.warehouse_id 
				WHERE Fecha  BETWEEN date_cyear_ini AND date_cyear_end  
				AND T.Id_Cliente NOT IN(400,200)	
				AND IF(i_wh = 0, W.is_comparative, i_wh = T.warehouse_id)
				AND r.display <> 0
                    			
                    GROUP BY A.Id_Article, week
        ) t	
        GROUP BY Id_Article;
    -- Genera la tabla con la comparativa.

    DROP TEMPORARY TABLE IF EXISTS remcom;

	SET strFILTRO = REPLACE(strFILTRO, 'Id_Article','A.Id_Article');
    SET strFILTRO = REPLACE(strFILTRO, 'tipo_id','tp.tipo_id');
	-- select * from article_inventory;
    
    DROP TEMPORARY TABLE IF EXISTS tmp.comparative;
    
    CALL util.exec (sql_printf
	(
		'CREATE TEMPORARY TABLE tmp.comparative ENGINE = MEMORY
			SELECT
				an.nicho, p.name Productor, C.Packing, C.Costefijo, C.caja	
				,A.Color, Id_Tipo as Tipo,A.tipo_id, o.Abreviatura as Origen, A.Categoria	
				,A.Tallos, A.Medida, A.Article, TR.CodigoTrabajador

				,cweek1, cweek2, cweek3, cweek4, cweek5, cweek6, cweek7
				,lweek1, lweek2, lweek3, lweek4, lweek5, lweek6, lweek7

				,cprice1, cprice2, cprice3, cprice4, cprice5, cprice6, cprice7
				,lprice1, lprice2, lprice3, lprice4, lprice5, lprice6, lprice7

				,A.Id_Article, i.buy_id	, tp.life , CAST(IFNULL(i.sd,0) AS SIGNED) as sd
				,CAST(i.avalaible AS SIGNED) avalaible, CAST(i.visible AS SIGNED) visible, i.buy_date	
				,E.Id_Proveedor AS provider_id
				,A.offer, A.bargain, A.comments, A.relevancy, A.description itemDescription
				,IF(cy.Id_Article IS NULL AND i.visible = 0 AND i.avalaible = 0 AND IFNULL(i.sd, 0) = 0, FALSE, TRUE) AS filtret
                ,(IFNULL(it.itemFk,0) != 0) isTagged
                
                ,A.tag5, A.value5, A.tag6, A.value6, A.tag7, A.value7, A.tag8, A.value8
                ,A.tag9, A.value9, A.tag10, A.value10, A.description,A.isActive
			FROM vn2008.article_inventory i
			JOIN vn2008.Articles A ON A.Id_Article = i.article_id
				LEFT JOIN vn.itemTagged it ON it.itemFk = i.article_id
				LEFT JOIN vn2008.Articles_nicho an ON A.Id_Article = an.Id_Article AND an.warehouse_id = %s
				LEFT JOIN vn2008.producer p ON p.producer_id = A.producer_id
				LEFT JOIN vn2008.Tipos tp ON A.tipo_id = tp.tipo_id
				LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id
				LEFT JOIN vn2008.Trabajadores TR ON TR.Id_Trabajador = tp.Id_Trabajador
				LEFT JOIN vn2008.Compres C ON i.buy_id = C.Id_Compra		
				LEFT JOIN vn2008.Entradas E USING(Id_Entrada)		
				LEFT JOIN vn2008.Origen o ON o.id = A.id_origen
				LEFT JOIN vn2008.last_year ly ON ly.Id_Article = A.Id_Article                  
				LEFT JOIN vn2008.cur_year cy ON cy.Id_Article = A.Id_Article AND (i.avalaible <> 0 OR i.visible <> 0 OR cweek1 OR cweek2 OR cweek3 OR cweek4
					OR cweek5 OR cweek6 OR cweek7 OR lweek1 OR lweek2 OR lweek3 OR lweek4 OR lweek5
					OR lweek6 OR lweek7) 
			WHERE r.display <> 0 AND %s '  

        ,i_wh,strFILTRO
    ));            

	-- Destruye las tablas temporales creadas.

	DROP TEMPORARY TABLE last_year;
	DROP TEMPORARY TABLE cur_year;
	DROP TEMPORARY TABLE article_inventory;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `compresFromTicket` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `compresFromTicket`(IN `vTicketId` BIGINT, IN `vEntryId` BIGINT)
BEGIN

	DECLARE vShipmentWarehouse INT;
    DECLARE vShipmentDate INT;
    
    SELECT warehouse_id_out, shipment 
    INTO vShipmentWarehouse, vShipmentDate
    FROM travel tr
    JOIN Entradas e ON e.travel_id = tr.id
    WHERE Id_Entrada = vEntryId;

	CALL item_last_buy_(vShipmentWarehouse,vShipmentDate);   
    
		INSERT INTO Compres(Id_Article,Cantidad, Id_Entrada, Id_Cubo, Packing, `grouping`, caja, Costefijo, Etiquetas) 
	 SELECT m.Id_Article,
			m.Cantidad,
			vEntryId,
			c.Id_Cubo,
			c.Packing,
			IF(c.`grouping`,c.`grouping`,1),
			c.caja,
			buyingAbsoluteCost(c.Id_Compra) Costefijo,
            ifnull(floor(m.Cantidad / c.Packing),1) Etiquetas
		FROM
			Movimientos m
			JOIN Articles a ON m.Id_Article = a.Id_Article
            LEFT JOIN t_item_last_buy b ON m.Id_Article = b.item_id AND b.warehouse_id = vShipmentWarehouse
            LEFT JOIN Compres c ON c.Id_Compra = b.buy_id
		WHERE m.Id_Ticket = vTicketId;
        
	CALL buy_tarifas_entry(vEntryId);
        
        
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `CompresTriggerBeforeDelete` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `CompresTriggerBeforeDelete`(oldId INT, oldEntrada INT)
BEGIN

    DECLARE hasToRecalculate BOOLEAN;
    DECLARE newWarehouse INT;
    
	SELECT Id_Compra INTO hasToRecalculate FROM vn.lastBuy lb
	WHERE lb.id = oldId LIMIT 1;
    
	IF hasToRecalculate THEN
		SELECT warehouse_id INTO newWarehouse FROM travel t
			JOIN Entradas e ON t.id = e.travel_id
            WHERE e.Id_Entrada = oldEntrada;
            
		CALL vn.lastBuyRefresh(newWarehouse);
	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 `compresTriggerBeforeInsert` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `compresTriggerBeforeInsert`(newNoVincular INT, newEntrada INT, newCompra INT, newItem INT)
BEGIN
	DECLARE newWarehouse INTEGER;
    
	IF newNoVincular = FALSE THEN
        
		UPDATE travel t
			JOIN vn.lastBuy lb ON newItem = lb.item AND t.warehouse_id = lb.warehouse
            JOIN Entradas e ON e.travel_id = t.id
		SET lb.id = newCompra
        WHERE e.Id_Entrada = newEntrada AND t.landing > lb.landing AND t.landing <= 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 `compresTriggerBeforeUpdate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `compresTriggerBeforeUpdate`(vOldEntrada INT, vNewEntrada INT, oldItem INT, 
	newItem INT, newNoVincular BOOLEAN, newCompra INT)
BEGIN
	DECLARE newWarehouse INTEGER;
    DECLARE hasToRecalculate BOOLEAN;
    
	IF newNoVincular = FALSE THEN
		IF oldItem <> newItem OR vOldEntrada <> vNewEntrada THEN
			SELECT Id_Compra INTO hasToRecalculate FROM travel t
				JOIN Entradas e ON e.travel_id = t.id
				JOIN vn.lastBuy lb ON lb.id = newCompra
			WHERE e.Id_Entrada = vOldEntrada LIMIT 1;
			
			IF hasToRecalculate THEN
				SELECT warehouse_id INTO newWarehouse FROM travel t
					JOIN Entradas e ON t.id = e.travel_id
                    WHERE e.Id_Entrada = vOldEntrada;
				CALL vn.lastBuyRefresh(newWarehouse);
			END IF;
		END IF;
		IF vOldEntrada <> vNewEntrada THEN
			
			UPDATE Entradas oldEntrada
				JOIN travel oldTravel ON oldEntrada.travel_id = oldtravel.id
				JOIN Entradas newEntrada ON newEntrada.Id_Entrada = vNewEntrada
                JOIN travel newTravel ON newTravel.id = newEntrada.travel_id
                JOIN vn.lastBuy lb ON newItem = lb.item AND newTravel.warehouse_id = lb.warehouse
			SET lb.id = newCompra
			WHERE oldEntrada.Id_Entrada = vOldEntrada AND oldTravel.warehouse_id <> newTravel.warehouse_id 
				AND newTravel.landing > lb.landing AND newTravel.landing <= CURDATE();
         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 `confection_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 `confection_control_source`(vScopeDays TINYINT)
BEGIN

	DECLARE vMidnight DATETIME DEFAULT TIMESTAMP(CURDATE(),'23:59:59');
	DECLARE vEndingDate DATETIME DEFAULT TIMESTAMPADD(DAY,vScopeDays,vMidnight);
	DECLARE maxAlertLevel INT DEFAULT 2;

	DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer;

	CREATE TEMPORARY TABLE tmp.production_buffer
	ENGINE = MEMORY
		SELECT 
			date(t.Fecha) as Fecha,
			hour(t.Fecha) as Hora,
			hour(t.Fecha) as Departure,
			t.Id_Ticket,
            m.Id_Movimiento,
			m.Cantidad,
			m.Concepte,
            ABS(m.Reservado) Reservado,
			i.Categoria,
			t.Alias as Cliente,
			wh.name as Almacen,
			t.warehouse_id,
			cs.province_id,
			a.agency_id,
            ct.description as Taller,
            stock.visible,
            stock.available
		FROM vn2008.Tickets t
			JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia
			JOIN vn2008.warehouse wh ON wh.id = t.warehouse_id
			JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket
            JOIN vn2008.Articles i ON i.Id_Article = m.Id_Article
			JOIN vn2008.Tipos tp ON tp.tipo_id = i.tipo_id
            JOIN vn.confectionType ct ON ct.id = tp.confeccion
			JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna
			LEFT JOIN vn.ticketState tls on tls.ticket = t.Id_Ticket
            LEFT JOIN 
				(					
					SELECT item_id, sum(visible) visible, sum(available) available
					FROM
					(
					SELECT a.item_id, 0 as visible, a.available
					FROM cache.cache_calc cc
					LEFT JOIN cache.available a ON a.calc_id = cc.id
					WHERE cc.cache_id IN (2,8) 
						AND cc.params IN (concat("1/", CURDATE()),concat("44/", CURDATE()))

					UNION ALL

					SELECT v.item_id, v.visible, 0 as available
					FROM cache.cache_calc cc
					LEFT JOIN cache.visible v ON v.calc_id = cc.id
					where cc.cache_id IN (2,8) and cc.params IN ("1","44")
					) sub
					GROUP BY item_id
                ) stock ON stock.item_id = m.Id_Article
		WHERE tp.confeccion 
			AND tls.alertLevel < maxAlertLevel
			AND wh.hasConfectionTeam
			AND t.Fecha BETWEEN CURDATE() AND vEndingDate
            AND m.Cantidad > 0;

	-- Hora limite de preparación

	CALL production_buffer_set_priority;

	-- Entradas

	INSERT INTO tmp.production_buffer(
										Fecha,
										Id_Ticket,
										Cantidad,
										Concepte,
										Categoria,
										Cliente,
										Almacen,
                                        Taller
										)
	    SELECT 
				tr.shipment AS Fecha, 
				e.Id_Entrada AS Id_Ticket,
				c.Cantidad,
				a.Article,
				a.Categoria,
				whi.name as Cliente,
				who.name as Almacen,
				ct.description as Taller
			FROM vn2008.Compres c
				JOIN vn2008.Entradas e ON e.Id_Entrada = c.Id_Entrada
				JOIN vn2008.travel tr ON tr.id = e.travel_id
				JOIN vn2008.warehouse whi ON whi.id = tr.warehouse_id
				JOIN vn2008.warehouse who ON who.id = tr.warehouse_id_out
				JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article
				JOIN vn2008.Tipos tp ON tp.tipo_id = a.tipo_id
				JOIN vn.confectionType ct ON ct.id = tp.confeccion
			WHERE who.hasConfectionTeam
				AND tp.confeccion
				AND tr.shipment BETWEEN CURDATE() AND vEndingDate;
                
		
		SELECT * FROM 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 */ ;
/*!50003 DROP PROCEDURE IF EXISTS `createBouquet` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `createBouquet`(
	vName VARCHAR(50), 
	vType int, 
	vSize int, 
	vColour VARCHAR(5),
	OUT vItem INT(11)

)
BEGIN
 DECLARE vDate DATE;
 DECLARE vCodintrastat INT(11);
 
	-- COMPROBAMOS SI EXISTE UN ARTÍCULO IGUAL.
	SELECT 
		Id_Article
	INTO vItem FROM
		Articles
	WHERE
		(Id_Article BETWEEN 161000 AND 169000)
			AND Article LIKE CONCAT('%', vName)
			AND tipo_id = vType
			AND Medida = vSize
			AND Color = vColour
		LIMIT 1;
		
 -- SI NO EXISTE CREAMOS UNO NUEVO
 IF vItem IS NULL THEN
	
	 
 -- OBTENER EL ID ENTRE 161000 Y 169000 DEL SIGUIENTE ARTÍCULO
	SELECT (IF(MAX(Id_Article) IS NULL, 161000, (MAX(Id_Article) + 1))) INTO vItem FROM Articles WHERE Id_Article BETWEEN 161000 AND 169000;
 
 -- INSERTAR EL ARTÍCULO
		INSERT INTO Articles(Id_Article, Article, tipo_id, Medida, color, id_origen) 
			VALUES ( 
				vItem,
				vName, 
				vType, 
				vSize, 
				vColour, 
				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 `credit_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              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `credit_update`()
BEGIN

DECLARE dblDiferencia DOUBLE DEFAULT 10.0;
DECLARE dblImporteRec,auxdblImporteRec DOUBLE DEFAULT 0.0;
DECLARE dblImporteFac,auxdblImporteFac DOUBLE DEFAULT 0.0;
DECLARE intIdRecibo,auxintIdRecibo	INT (11) DEFAULT 0;
DECLARE intId_Cliente,auxintId_Cliente,intId_ClienteRec,auxintId_ClienteRec INT DEFAULT 0;
DECLARE bitFin,bitFinRecord,bitFinRecord1 BIT DEFAULT 0;
DECLARE datFechaVencimiento DATE DEFAULT CURDATE();
DECLARE intEmpresa_id INT DEFAULT 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 `customerDebtEvolution` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `customerDebtEvolution`(IN vCustomer INT)
BEGIN

SELECT * FROM
(
	SELECT day, date, @s:= round(IFNULL(Euros,0) + @s,2) as Saldo, Euros, Credito, 0 as Cero
	FROM
	(
	SELECT day, date, IFNULL(Euros,0) as Euros, Credito
	FROM time
	JOIN (SELECT @s:= 0, - Credito as Credito FROM Clientes WHERE Id_Cliente = vCustomer) c
	LEFT JOIN
	(SELECT Euros, date(Fecha) as Fecha FROM
		(
			SELECT Fechacobro as Fecha, Entregado as Euros
			FROM Recibos 
			WHERE Id_Cliente = vCustomer
			AND Fechacobro >= '2017-01-01'
			UNION ALL
			SELECT paymentday(f.Fecha,c.Vencimiento), - Importe
			FROM Facturas f
            JOIN Clientes c ON f.Id_Cliente = c.Id_Cliente
			WHERE f.Id_Cliente = vCustomer
			AND Fecha >= '2017-01-01'
			UNION ALL
			SELECT '2016-12-31', Debt
			FROM bi.customerDebtInventory
			WHERE Id_Cliente = vCustomer
            UNION ALL
            SELECT Fecha, - SUM(Cantidad * Preu * (100 - Descuento ) * 1.10 / 100)
            FROM Tickets t
            JOIN Movimientos m on m.Id_Ticket = t.Id_Ticket
            WHERE Id_Cliente = vCustomer
            AND Factura IS NULL
            AND Fecha >= '2017-01-01'
            GROUP BY Fecha
		) sub2
		ORDER BY Fecha
	)sub ON time.date = sub.Fecha
	WHERE time.date BETWEEN '2016-12-31' AND CURDATE()
	ORDER BY date
	) sub3
)sub4
;


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cycDueDateClassification` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `cycDueDateClassification`(vCompany INT,vDate DATE)
BEGIN

	SELECT Fecha, Clasificacion, CAST(SUM(Importe) AS DECIMAL(10,2)) as Importe, empresa_id
	FROM
	(
		SELECT CASE 
				WHEN C.Vencimiento <= 30 THEN '0-30 dias'
				WHEN C.Vencimiento BETWEEN 31 AND 60 THEN '31-60 dias'
				WHEN C.Vencimiento BETWEEN 61 AND 90 THEN '61-90 dias'
				ELSE '> 90 dias'
				END AS Clasificacion,
				F.Importe,
				C.Fecha,
				F.empresa_id
						
		FROM cyc_declaration C
			JOIN Facturas F USING(factura_id)
		WHERE C.Riesgo > 0 AND C.Fecha = vDate AND F.empresa_id = vCompany
		
	) cyc
	GROUP BY Fecha, Clasificacion, empresa_id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cycGeneralClassification` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `cycGeneralClassification`(vCompany INT,vDate DATE)
BEGIN
	SELECT Fecha, Clasificacion, CAST(SUM(Importe) AS DECIMAL(10,2)) as Importe, empresa_id
	FROM
	(
		SELECT CASE IFNULL(C.Riesgo,-1)
				WHEN 0 THEN 'No aseguradas'
				WHEN -1 THEN 'Clasificacion nada'
				ELSE 'Asegurados'
				END AS Clasificacion,
				F.Importe,
				C.Fecha,
				F.empresa_id
						
		FROM cyc_declaration C
			JOIN Facturas F ON F.factura_id = C.factura_id
        WHERE C.Fecha = vDate AND F.empresa_id = vCompany
		
	) cyc
	GROUP BY Fecha, Clasificacion, empresa_id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cycNoInsurancedClassification` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `cycNoInsurancedClassification`(vCompany INT,vDate DATE)
BEGIN

SELECT 'ORG. PUBLICOS' AS Tipo, C.Fecha, CAST(SUM(F.Importe) AS DECIMAL(10,2)) as Importe, F.empresa_id

    FROM cyc_declaration C
    INNER JOIN Facturas F USING(factura_id)
    JOIN Clientes CL USING(Id_Cliente)
    WHERE C.Riesgo IS NULL
    AND LEFT(CL.`IF`,1) = 'G'
    AND C.Fecha = vDate AND F.empresa_id = vCompany
    
GROUP BY Fecha, F.empresa_id

UNION ALL

SELECT 'VINCULADAS' , C.Fecha, CAST(SUM(F.Importe) AS DECIMAL(10,2)) as Importe, F.empresa_id

    FROM cyc_declaration C
    INNER JOIN Facturas F USING(factura_id)
    WHERE C.Riesgo IS NULL
    AND F.Id_Cliente IN(2066, 2067)
    AND C.Fecha = vDate AND F.empresa_id = vCompany
    
GROUP BY Fecha, F.empresa_id

UNION ALL

SELECT 'CONTADO', C.Fecha, CAST(SUM(F.Importe) AS DECIMAL(10,2)) as Importe, F.empresa_id

    FROM cyc_declaration C
    INNER JOIN Facturas F USING(factura_id)
    JOIN Clientes CL USING(Id_Cliente)
    WHERE C.Riesgo IS NULL
    AND pay_met_id = 1
    AND LEFT(CL.`IF`,1) <> 'G'
    AND F.Id_Cliente NOT IN(2066, 2067)
    AND C.Fecha = vDate AND F.empresa_id = vCompany
    
GROUP BY Fecha, F.empresa_id

UNION ALL

SELECT 'OTROS', C.Fecha, CAST(SUM(F.Importe) AS DECIMAL(10,2)) as Importe, F.empresa_id

    FROM cyc_declaration C
    INNER JOIN Facturas F USING(factura_id)
    JOIN Clientes CL USING(Id_Cliente)
    WHERE C.Riesgo IS NULL
    AND pay_met_id <> 1
    AND LEFT(CL.`IF`,1) <> 'G'
    AND F.Id_Cliente NOT IN(2066, 2067)
    AND C.Fecha = vDate AND F.empresa_id = vCompany
    
GROUP BY Fecha, F.empresa_id


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

REPLACE cyc_declaration(factura_id, Riesgo, Fecha, Vencimiento)
SELECT F.factura_id, R.Riesgo, @fecha, IFNULL(C.Vencimiento,0)
FROM Facturas F
INNER JOIN Clientes C ON F.Id_Cliente = C.Id_Cliente
INNER JOIN empresa E ON E.id = F.empresa_id
LEFT JOIN 
    (   SELECT * 
        FROM (
            SELECT Id_Cliente, Riesgo
            FROM cyc
            WHERE Fecha <= @fecha:= TIMESTAMPADD(DAY, -1 * DAY(datFEC), datFEC) 
            ORDER BY Fecha DESC
            ) sub
        GROUP BY Id_Cliente
    ) R ON F.Id_Cliente = R.Id_Cliente
WHERE E.cyc
AND periodo(Fecha) = periodo(@fecha)
;

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

SELECT 
 c.Id_Cliente,
 hasChanged,
 Cliente,
 amount as Deuda,
 CodigoTrabajador,
 CyC,
 Apuntador,
 Fecha_obs,
 last_obs,
 defaulterSince
from
 bi.defaulters d
 join
 ( 
	SELECT customer_id Id_Cliente,SUM(amount) AS Saldo
	FROM bi.customerRiskOverdue
	GROUP BY customer_id
 ) saldos ON saldos.Id_Cliente = d.client
 join
 Clientes c  on c.Id_Cliente = d.client
 join
 Trabajadores t USING (Id_Trabajador)
left join
(
SELECT Id_Cliente, last_obs, CodigoTrabajador as Apuntador, Fecha as Fecha_obs
FROM
(
SELECT Id_Cliente, `text` as last_obs, CodigoTrabajador, client_observation.odbc_date as Fecha
FROM client_observation
JOIN Trabajadores using(Id_Trabajador)
order by client_observation.odbc_date desc
) sub GROUP BY Id_Cliente
) obs on obs.Id_Cliente = d.client
WHERE
date = CURDATE()
and amount > 0
and not (Saldo > amount AND amount < 0)
and CodigoTrabajador not in ('CYC','BUD','EJE')
ORDER BY amount 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 `desglose_volume` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `desglose_volume`(IN agency_id INT)
BEGIN
    DECLARE v_start DATETIME DEFAULT TIMESTAMP(CURDATE());
    DECLARE v_end DATETIME DEFAULT TIMESTAMP(CURDATE(), '23:59:59');

	SET v_start = IF(WEEKDAY(CURDATE()), CURDATE(),TIMESTAMPADD(DAY,-1,CURDATE()));
	SET v_start = IF(CURDATE() = '2014-05-02', '2014-05-01',v_start);

    DROP TEMPORARY TABLE IF EXISTS zeleVOL;
    CREATE TEMPORARY TABLE zeleVOL
    (
         Id_Ticket INT PRIMARY KEY
        ,Provincia VARCHAR(30)
        ,Bultos INT DEFAULT 0
        ,Faltan INT DEFAULT 0
    );

    -- Insertamos los tickets que ya tienen la linea de portes
          
    INSERT INTO zeleVOL(Provincia, Id_Ticket, Bultos)
    SELECT p.name, t.Id_Ticket, sum(m.Cantidad)
        FROM Tickets t
        JOIN Consignatarios c USING(Id_Consigna)
        JOIN province p ON c.province_id = p.province_id
        JOIN Movimientos m USING(Id_Ticket)
        JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia
		JOIN warehouse_joined wj ON wj.warehouse_id = t.warehouse_id
            WHERE m.Id_Article = 71
            AND wj.warehouse_alias_id = 1 -- El 1 equivale a Silla (SillaFV-SillaPCA)
            AND t.Fecha BETWEEN v_start AND v_end
            AND a.agency_id = agency_id
            GROUP BY p.name, Id_Ticket;
       
    -- Insertamos los tickets que ya tienen expediciones, que fallaran si se repite la clave primaria.

    INSERT INTO zeleVOL(Provincia, Id_Ticket, Bultos)
    SELECT p.name, e.ticket_id, COUNT(e.ticket_id) 
        FROM expeditions e
        JOIN Tickets t ON ticket_id = Id_Ticket
        JOIN Consignatarios c USING(Id_Consigna)
        JOIN province p ON c.province_id = p.province_id
        JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia
		JOIN warehouse_joined wj ON wj.warehouse_id = t.warehouse_id
            WHERE e.odbc_date BETWEEN v_start AND v_end
			AND wj.warehouse_alias_id = 1 -- El 1 equivale a Silla (SillaFV-SillaPCA)
            AND a.agency_id = agency_id
            GROUP BY p.name, ticket_id 
            ON DUPLICATE KEY UPDATE Bultos = Bultos;

    -- Por encajar

    INSERT INTO zeleVOL(Provincia, Id_Ticket, Faltan)
    SELECT province, Id_Ticket, COUNT(Id_Ticket) as Faltan
        FROM
        (
            SELECT p.name AS province, Id_Ticket, COUNT(Id_Movimiento) l, SUM(Cantidad) c
                FROM Movimientos m
                JOIN Tickets t USING(Id_Ticket)
                JOIN Consignatarios c USING(Id_Consigna)
                JOIN province p ON c.province_id = p.province_id
                JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia
				LEFT JOIN expeditions e ON t.Id_Ticket = e.ticket_id
				JOIN warehouse_joined wj ON wj.warehouse_id = t.warehouse_id
                    WHERE Fecha BETWEEN v_start AND v_end
                    AND wj.warehouse_alias_id = 1 -- El 1 equivale a Silla (SillaFV-SillaPCA)
                    AND a.agency_id = agency_id
					AND (Bultos = 0 AND expeditions_id IS NULL AND EtiquetasEmitidas = 0)
                    GROUP BY p.name, Id_Ticket
        ) sub GROUP BY province
        ON DUPLICATE KEY UPDATE Faltan = Faltan;

    -- Mostramos el resultado

    SELECT Provincia, COUNT(Id_Ticket) expediciones, SUM(Bultos) Bultos, SUM(Faltan) Prevision
        FROM zeleVOL
            GROUP BY Provincia;

    DROP TEMPORARY TABLE IF EXISTS zeleVOL;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `dif_porte` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `dif_porte`(IN datFEC DATE)
BEGIN

/*  Calcula los greuges de porte que no coinciden con lo esperado
/
/
/
*/


drop temporary table if exists tmp.bionic_porte;
create temporary table tmp.bionic_porte
select Id_Ticket, sum(Valor * Cantidad) as bionic
from vn2008.Movimientos m
join vn2008.Movimientos_componentes mc using(Id_Movimiento)
where Id_Componente = 15
group by Id_Ticket;

ALTER TABLE tmp.bionic_porte
ADD KEY bp_Id_Ticket_ix (Id_Ticket);


drop temporary table if exists tmp.shipping_porte;
create temporary table tmp.shipping_porte
select Id_Ticket, SUM(shipping_charge) from vn2008.v_expeditions_shipping_charge2 where Fecha >= datFEC group by Id_Ticket;

ALTER TABLE tmp.shipping_porte
ADD KEY sp_Id_Ticket_ix (Id_Ticket);


drop temporary table if exists tmp.greuge_porte;
create temporary table tmp.greuge_porte
select Id as Id_Greuge, cast(right(Comentario,7) as decimal(10,0)) Id_Ticket, Importe 
FROM vn2008.Greuges 
where Comentario like 'dif_porte%';
ALTER TABLE tmp.greuge_porte
ADD KEY Id_Ticket_ix (Id_Ticket);
select * from tmp.greuge_porte;



SELECT Id_Ticket,shipping_charge as Teorico, bionic as Practico, Importe as Greuge, shipping_charge - bionic - Importe as dif 
FROM tmp.shipping_porte
join tmp.greuge_porte using(Id_Ticket)
join tmp.bionic_porte using(Id_Ticket)

;




END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `Ditacio` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `Ditacio`(IN intId INT,IN straccion varchar(100),IN strtabla CHAR(1),IN intIdTrabajador INT,
IN straccion_old VARCHAR(100),IN straccion_new VARCHAR(100))
proc_label:BEGIN

	DECLARE intlengthaccion TINYINT;
	DECLARE strtabla_dits VARCHAR(35);

	SELECT CASE
		WHEN strtabla='A' THEN 'Articles_dits'
		WHEN strtabla='I' THEN 'Inventario_dits'
		WHEN strtabla='E' THEN 'Entradas_dits'
		WHEN strtabla='T' THEN 'Tickets_dits'
		WHEN strtabla='C' THEN 'Clientes_dits'
		WHEN strtabla='V' THEN 'travel_dits'
        WHEN strtabla='R' THEN 'Rutas_dits'
        WHEN strtabla='G' THEN 'Agencias_dits'
        WHEN strtabla='S' THEN 'salarioDits'
		ELSE NULL
	END 
	INTO strtabla_dits;

	IF (strtabla_dits IS NULL)
		THEN LEAVE proc_label;
	END IF;

	SET @intIdTrabajador = intIdTrabajador;
	SET @intId = intId;
	SET @strvalue_old = straccion_old;
	SET @strvalue_new = straccion_new;
	SET @intidaccion = NULL;

	SELECT idaccion_dits
	INTO @intidaccion
	FROM accion_dits
	WHERE accion=left(straccion,CHAR_LENGTH(accion))
	ORDER BY CHAR_LENGTH(accion) DESC
	LIMIT 1;
	
	IF @intidaccion IS null THEN -- idaccion genèric per a evitar errors en cas de no existir
		SET @intidaccion = 103;
	END IF;

	SET @SQL=CONCAT('INSERT INTO ',strtabla_dits,' (idaccion_dits,Id_Trabajador,Id_Ticket,value_old,value_new) 
			 VALUES (?,?,?,?,?)');

	PREPARE stmt1 FROM @SQL;
	EXECUTE stmt1 USING @intidaccion,@intIdTrabajador,@intId,@strvalue_old,@strvalue_new;
	DEALLOCATE PREPARE stmt1;


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

DECLARE awbFk INT;
DECLARE newInvoiceInFk INT;

SELECT awb_id INTO awbFk
    FROM vn2008.awb_recibida
        WHERE recibida_id = oldInvoiceInFk;

INSERT INTO vn2008.recibida(proveedor_id, fecha, dateOperation)
    SELECT supplierFk, curdate(), curdate()
        FROM vn.invoiceIn
        WHERE id = oldInvoiceInFk;

SELECT LAST_INSERT_ID() INTO newInvoiceInFk;

INSERT INTO awb_recibida(awb_id,recibida_id)
    VALUES(awbFk, newInvoiceInFk);

INSERT INTO vn2008.recibida_entrada(recibida_id,Id_Entrada, percentage,awb_recibida)
    SELECT  re.recibida_id, 
            Id_Entrada, 
            100 - sum(percentage) as entryRemaining,
            newInvoiceInFk
        FROM vn2008.recibida_entrada re
        JOIN vn2008.awb_recibida ar ON ar.recibida_id = re.awb_recibida
        WHERE ar.awb_id = awbFk
        GROUP BY Id_Entrada
        HAVING entryRemaining > 0;
        
DELETE re.*
	FROM vn2008.recibida_entrada re
	JOIN vn2008.awb_recibida ar ON ar.recibida_id = re.awb_recibida
        WHERE ar.awb_id = awbFk
        AND re.percentage = 0;
        
SELECT newInvoiceInFk;


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `emailYesterdayPurchasesByConsigna` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `emailYesterdayPurchasesByConsigna`(IN v_Date DATE, IN v_Client_Id INT)
BEGIN


DECLARE MyIdTicket BIGINT;
DECLARE MyAlias VARCHAR(50);
DECLARE MyDomicilio VARCHAR(255);
DECLARE MyPoblacion VARCHAR(25);
DECLARE MyImporte DOUBLE;
DECLARE MyMailTo VARCHAR(250);
DECLARE MyMailReplyTo VARCHAR(250);
DECLARE done INT DEFAULT FALSE;
DECLARE emptyList INT DEFAULT 0;
DECLARE txt TEXT;

DECLARE rs CURSOR FOR 
SELECT t.Id_Ticket, Alias, cast(amount as decimal(10,2)) Importe, Domicilio, POBLACION
FROM Tickets t
JOIN Consignatarios cs on t.Id_Consigna = cs.Id_Consigna
JOIN v_ticket_amount v on v.Id_Ticket = t.Id_Ticket
WHERE t.Fecha BETWEEN v_Date AND dayend(v_Date)
AND t.Id_Cliente = v_Client_Id;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

SET v_Date = IFNULL(v_Date, util.yesterday());

OPEN rs;

FETCH rs INTO MyIdTicket, MyAlias, MyImporte, MyDomicilio, MyPoblacion;

SET emptyList = done;

SET txt = CONCAT('<p><font face="verdana" >',
				 '<h2> Relación de envíos.</h2>',
				 '<h3><font color="green">Dia: ', v_Date, '</font></h3>');

WHILE NOT done DO

	SET txt = CONCAT(txt, '<br><br>',
					'<table>
						<tr>
							<th> <a href = "https://www.verdnatura.es/#!form=ecomerce/ticket&ticket=',MyIdTicket,'">
                            <font color="green"> Ticket ', MyIdTicket,'</font></th>
                            <th></th><th></th><th></th><th></th>
                            <th></th><th></th><th></th><th></th>
                            <th> <font color="orange"> ', MyImporte, ' € </a></font></th>
						</tr>
					</table>'
     			   , '             ', MyAlias, '<br>'
				   , '             ', MyDomicilio, '(', MyPoblacion, ')');

FETCH rs INTO MyIdTicket, MyAlias, MyImporte, MyDomicilio, MyPoblacion;

END WHILE;


SET txt = CONCAT(txt, 
				'<table>',
                '<tr><th></th></tr>',
                '</table>',
				'<br><br>Puede acceder al detalle de los albaranes haciendo click sobre el número de Ticket',
				'<br><h3> Muchas gracias por su confianza</h3>',
				'</font></p>');

-- Envío del email
IF emptyList = 0 THEN

	SELECT CONCAT(`e-mail`,',pako@verdnatura.es') INTO MyMailTo
	FROM Clientes
	WHERE Id_Cliente = v_Client_Id AND `e-mail`>'';
    
    IF v_Client_Id = 7818 THEN -- LOEWE
    
		SET MyMailTo = 'isabel@elisabethblumen.com,emunozca@loewe.es,pako@verdnatura.es';
    
    END IF;

	INSERT INTO mail(`to`, reply_to, subject, text)
	VALUES (IFNULL(MyMailTo,'pako.natek@gmail.com'),'pako@verdnatura.es','Resumen de pedidos preparados',txt);

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

DECLARE done INT DEFAULT 0;
DECLARE vMyClientId INT;

DECLARE rs CURSOR FOR
SELECT Id_Cliente
FROM Clientes
WHERE EYPBC != 0;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

OPEN rs;

FETCH rs INTO vMyClientId;

WHILE NOT done DO

	CALL emailYesterdayPurchasesByConsigna(util.yesterday(), vMyClientId);
    
	FETCH rs INTO vMyClientId;

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

if bolCLIENT then

	select m.Id_Article,  Article, - cast(sum(m.Cantidad) as decimal) as Saldo
	from Movimientos m
    join Articles a on m.Id_Article = a.Id_Article
    join Tipos tp on tp.tipo_id = a.tipo_id 
	join Tickets t using(Id_Ticket)
	join Consignatarios cs using(Id_Consigna)
	where cs.Id_Cliente = idPEOPLE
    and Tipo = 'Contenedores'
	and t.Fecha > '2010-01-01'
    group by m.Id_Article;

else

select Id_Article, Article, sum(Cantidad) as Saldo
from
(select Id_Article, Cantidad
from Compres c
join Articles a using(Id_Article)
join Tipos tp using(tipo_id)
join Entradas e using(Id_Entrada)
join travel tr on tr.id = travel_id
where Id_Proveedor = idPEOPLE
and landing >= '2010-01-01'
and reino_id = 6

union all

select Id_Article,  - Cantidad
from Movimientos m
join Articles a using(Id_Article)
join Tipos tp using(tipo_id)
join Tickets t using(Id_Ticket)
join Consignatarios cs using(Id_Consigna)
join proveedores_clientes pc on pc.Id_Cliente = cs.Id_Cliente
where Id_Proveedor = idPEOPLE
and reino_id = 6
and t.Fecha > '2010-01-01') mov

join Articles a using(Id_Article)
group by Id_Article;

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


if bolCLIENT then

	select m.Id_Article
         , Article
		 , IF(Cantidad < 0, - Cantidad, NULL) as Entrada
		 , IF(Cantidad < 0, NULL, Cantidad) as  Salida
		 , 'T' as Tabla
		 , t.Id_Ticket  as Registro
		 , t.Fecha
		 , w.name as Almacen
		 , cast(Preu as Decimal(5,2)) Precio
         , c.Cliente as Proveedor
         , abbreviation as Empresa
	from Movimientos m
    join Articles a using(Id_Article)
	join Tickets t using(Id_Ticket)
    join empresa e on e.id = t.empresa_id
    join warehouse w on w.id = t.warehouse_id
	join Consignatarios cs using(Id_Consigna)
    join Clientes c on c.Id_Cliente = cs.Id_Cliente
    where cs.Id_Cliente = idPEOPLE
	and m.Id_Article = idARTICLE
	and t.Fecha > '2010-01-01';

else

select Id_Article, Tabla, Registro, Fecha, Article
, w.name as Almacen,  Entrada, Salida, Proveedor, cast(Precio as Decimal(5,2)) Precio

from

(select Id_Article
      , IF(Cantidad > 0, Cantidad, NULL) as Entrada
      , IF(Cantidad > 0, NULL,- Cantidad) as Salida
      , 'E' as Tabla
      , Id_Entrada as Registro
      , landing as Fecha
      , tr.warehouse_id
      , Costefijo as Precio
from Compres c
join Entradas e using(Id_Entrada)
join travel tr on tr.id = travel_id
where Id_Proveedor = idPEOPLE
and Id_Article = idARTICLE
and landing >= '2010-01-01'

union all

select Id_Article
	 , IF(Cantidad < 0, - Cantidad, NULL) as Entrada
	 , IF(Cantidad < 0, NULL, Cantidad) as  Salida
     , 'T'
     , Id_Ticket
     , Fecha
     , t.warehouse_id
     , Preu
from Movimientos m
join Tickets t using(Id_Ticket)
join Consignatarios cs using(Id_Consigna)
join proveedores_clientes pc on pc.Id_Cliente = cs.Id_Cliente
where Id_Proveedor = idPEOPLE
and Id_Article = idARTICLE
and t.Fecha > '2010-01-01') mov

join Articles a using(Id_Article)
join Proveedores p on Id_Proveedor = idPEOPLE
join warehouse w on w.id = mov.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 `EntradasTriggerBeforeDelete` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `EntradasTriggerBeforeDelete`(oldTravel INT, oldId INT)
BEGIN

    DECLARE hasToRecalculate BOOLEAN;
	DECLARE newWarehouse INT;
    
	SELECT Id_Compra INTO hasToRecalculate FROM Compres c
		JOIN vn.lastBuy lb ON lb.id = c.Id_Compra
	WHERE c.Id_Entrada = newId LIMIT 1;
	IF hasToRecalculate THEN
		SELECT warehouse_id INTO newWarehouse FROM travel WHERE id = oldTravel;
		CALL vn.lastBuyRefresh(newWarehouse);
	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 `EntradasTriggerBeforeUpdate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `EntradasTriggerBeforeUpdate`(oldTravel INT, newTravel INT, oldRedada BOOLEAN, 
		newRedada BOOLEAN, newId INT)
BEGIN
	DECLARE newWarehouse INTEGER;
    DECLARE hasToRecalculate BOOLEAN;
    
	IF oldRedada <> newRedada OR newTravel IS NULL THEN
        
		SELECT Id_Compra INTO hasToRecalculate FROM Compres c
			JOIN vn.lastBuy lb ON lb.id = c.Id_Compra
		WHERE c.Id_Entrada = newId LIMIT 1;
		IF hasToRecalculate THEN
			SELECT warehouse_id INTO newWarehouse FROM travel WHERE id = newtravel;
			CALL vn.lastBuyRefresh(newWarehouse);
		END IF;
	END IF;
		
	IF newTravel <> oldTravel AND newTravel IS NOT NULL THEN
		UPDATE travel t
			JOIN Compres c ON c.Id_Entrada = newId
			JOIN vn.lastBuy lb ON c.Id_Article = lb.item AND t.warehouse_id = lb.warehouse
		SET lb.id = c.Id_Compra
        WHERE t.id = newTravel AND t.landing BETWEEN date_inv() AND util.yesterday()
			AND t.landing > lb.landing;
    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 `Entradas_Restar` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `Entradas_Restar`(IN Id_Minuendo INT, IN Id_Sustraendo INT)
BEGIN

UPDATE Compres c
JOIN
(
	SELECT Id_Article, Cantidad
    FROM Compres
    WHERE Id_Entrada = Id_Sustraendo
) sub using(Id_Article)
SET c.Cantidad = c.Cantidad - sub.Cantidad
WHERE Id_Entrada = Id_Minuendo;


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entryFromOrder` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `entryFromOrder`(IN vShipmentWarehouse INTEGER, IN vLandingWarehouse INTEGER, IN vItem INTEGER,
		IN vAmount INTEGER,IN vVolume INTEGER,vCost DECIMAL(10,2), IN vRetailedPrice DECIMAL(10,2), vInOutDate DATE)
BEGIN

    DECLARE vTravel INT;
    DECLARE vEntry INT;
    DECLARE vBucket VARCHAR(10);

	-- seleccionamos travel
	SELECT id, Id_Entrada INTO vTravel, vEntry
		FROM travel t LEFT JOIN Entradas e ON t.id = e.travel_id
        WHERE t.landing = vInOutDate AND t.shipment = vInOutDate AND t.warehouse_id_out = vShipmentWarehouse 
			AND t.warehouse_id = vLandingWarehouse AND agency_id = 15
	LIMIT 1; 

    -- creamos el travel si es necesario
    IF NOT IFNULL(vTravel,0) THEN
		INSERT INTO travel (shipment, landing, warehouse_id, warehouse_id_out, agency_id)
			VALUES (vInOutDate, vInOutDate, vLandingWarehouse, vShipmentWarehouse, 15);
		SELECT LAST_INSERT_ID() INTO vTravel;
    END IF;
    -- creamos la Entrada si es necesario
	IF NOT IFNULL(vEntry,0) THEN
		INSERT INTO Entradas (Id_Proveedor, travel_id)
				VALUES (13, vTravel); -- proveedor 'MOVIMIENTO ALMACEN'
		SELECT LAST_INSERT_ID() INTO vEntry;
	END IF;
   
	 -- creamos el cubo si es necesario
	SELECT Id_Cubo INTO vBucket FROM Cubos WHERE Volumen = vVolume LIMIT 1;
    
	IF NOT IFNULL(vBucket,'') > '' THEN
		INSERT INTO Cubos (Id_Cubo, Volumen)
				VALUES (CONCAT('dm',vVolume/1000), vVolume);
		SELECT LAST_INSERT_ID() INTO vBucket;
	END IF;
    
	INSERT INTO Compres(Id_Article,Cantidad, Id_Entrada, Id_Cubo, Packing, `grouping`, caja, Costefijo, Portefijo, Embalajefijo,
				Comisionfija, Tarifa2, Tarifa3) 
	 VALUES(vItem,
			vAmount,
			vEntry,
			vBucket,
			1,
			1,
			0,
			vCost,
			0,
			0,
			0,
			vRetailedPrice,
			vRetailedPrice);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entryFromTicket` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `entryFromTicket`(IN vTicket INTEGER, IN vLandingWarehouse INTEGER)
BEGIN

	DECLARE vShipmentWarehouse INT;
	DECLARE vLandingDate DATE;
    DECLARE vShipmentDate DATE;
    DECLARE vTravel INT;
    DECLARE vEntry INT;

	SELECT warehouse_id, Fecha, Fecha INTO vShipmentWarehouse, vShipmentDate, vLandingDate FROM Tickets WHERE Id_Ticket = vTicket;

	-- seleccionamos travel
	SELECT id, Id_Entrada INTO vTravel, vEntry
		FROM travel t LEFT JOIN Entradas e ON t.id = e.travel_id
        WHERE t.landing = vLandingDate AND t.shipment = vShipmentDate AND t.warehouse_id_out = vShipmentWarehouse AND t.warehouse_id = vLandingWarehouse
			AND agency_id = 15
		LIMIT 1;
	
    -- creamos el travel si es necesario
    IF vTravel IS NULL THEN
		select vLandingDate;
		INSERT INTO travel (shipment, landing, warehouse_id, warehouse_id_out, agency_id)
			VALUES (vShipmentDate, vLandingDate, vLandingWarehouse, vShipmentWarehouse, 15);
		SELECT LAST_INSERT_ID() INTO vTravel;
    END IF;
    
    -- creamos la Entrada si es necesario
	IF vEntry IS NULL THEN
		INSERT INTO Entradas (Id_Proveedor, travel_id)
				VALUES (13, vTravel); -- proveedor 'MOVIMIENTO ALMACEN'
		SELECT LAST_INSERT_ID() INTO vEntry;
	END IF;
            
	CALL item_last_buy_(vShipmentWarehouse,vShipmentDate);   
    
	INSERT INTO Compres(Id_Article,Cantidad, Id_Entrada, Id_Cubo, Packing, `grouping`, caja, Costefijo, Portefijo, Embalajefijo,
				Comisionfija, Tarifa2, Tarifa3) 
	 SELECT m.Id_Article,
			m.Cantidad,
			vEntry,
			c.Id_Cubo,
			c.Packing,
			IF(c.`grouping`,c.`grouping`,1),
			c.caja,
			Costefijo,
			c.Portefijo,
			c.Embalajefijo,
			c.Comisionfija,
			m.Preu Tarifa2,
			m.Preu Tarifa3
		FROM
			Movimientos m
			JOIN Articles a ON m.Id_Article = a.Id_Article
            LEFT JOIN t_item_last_buy b ON m.Id_Article = b.item_id AND b.warehouse_id = vShipmentWarehouse
            LEFT JOIN Compres c ON c.Id_Compra = b.buy_id
		WHERE m.Id_Ticket = 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 `envios_masivos` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `envios_masivos`(IN idTICKET INT, IN IdCONSIGNA_DESDE INT, IN IdCONSIGNA_HASTA INT)
BEGIN

-- Se trata de clonar el ticket semilla para todos los consignatarios del rango, con los movimientos que contenga

-- Insertamos los tickets

INSERT INTO Tickets(Id_Consigna, Id_Cliente, warehouse_id, Fecha, Alias, Tipo, Id_Trabajador, empresa_id, Id_Agencia)
SELECT c.Id_Consigna, t.Id_Cliente, t.warehouse_id, t.Fecha, c.Consignatario, t.Tipo, t.Id_Trabajador, t.empresa_id, t.Id_Agencia
FROM Tickets t
JOIN Consignatarios c
WHERE Id_Ticket = idTICKET
AND c.Id_Consigna BETWEEN IdCONSIGNA_DESDE AND IdCONSIGNA_HASTA;


-- Insertamos los movimientos

INSERT INTO Movimientos(Id_Article, Concepte, Cantidad, Preu, PrecioFijado, Id_Ticket)
SELECT Id_Article, Concepte, Cantidad, Preu, TRUE , t.Id_Ticket
FROM Tickets t
JOIN Movimientos m
WHERE m.Id_Ticket = idTICKET
AND t.Id_Consigna BETWEEN IdCONSIGNA_DESDE AND IdCONSIGNA_HASTA;


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `etiqueta_sambori` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `etiqueta_sambori`(IN lngEXPEDITION BIGINT, IN intMODE INT, IN intH INT, IN intFILAS INT)
BEGIN

DECLARE intCOLUMNAS INT;
DECLARE intBULTOS INT;
DECLARE intDESCARGAS INT;
DECLARE intRUTA INT;
DECLARE intPOSICIONES INT;



SELECT Id_Ruta INTO intRUTA
FROM Tickets t
JOIN expeditions e on e.ticket_id = t.Id_Ticket
WHERE e.expeditions_id = lngEXPEDITION;


SELECT sum(Bultos) , count(*) , CEIL(SUM(CEIL(Bultos / intH)) / intFILAS), SUM(CEIL(Bultos / intH))
  INTO intBULTOS,intDESCARGAS,  intCOLUMNAS, intPOSICIONES
from
(
SELECT Id_Consigna, sum(Bultos) Bultos
FROM Tickets 
WHERE Id_Ruta = intRUTA
group by Id_Consigna
) sub;




IF intMODE <> 2 THEN

		SELECT 
			CONCAT(   IF(posicion_min MOD intFILAS = 0, intFILAS, posicion_min MOD intFILAS)
                     , MID(' BCDEFG',CEIL(posicion_min /intFILAS),1)
                     , IF(posicion_min = posicion_max,'',' - ')
                     , IF(posicion_min = posicion_max,'',IF(posicion_max MOD intFILAS = 0, intFILAS, posicion_max MOD intFILAS))
                     , IF(posicion_min = posicion_max,'',MID(' BCDEFG',CEIL(posicion_max /intFILAS),1))
                     
				  ) sambori,
			t.Prioridad,
			t.Id_Consigna,
			CONCAT(e.counter, ' / ', t.Bultos) count_bultos,
			e.expeditions_id,
			zone,
			Matricula Vehiculo,
			trab.CodigoTrabajador Chofer,
			Rutas.Id_Ruta,
			RIGHT(Rutas.Id_Ruta, 2) Id_RutaSTR,
			t.Bultos TotalBultos,
			RIGHT(e.expeditions_id,3) expeditions_IDSTR
		FROM
			expeditions e
				JOIN
			Tickets t ON e.ticket_id = t.Id_Ticket
				JOIN
			(
				select Prioridad, cast(@s - 1 as decimal(3,0)) as posicion_max, @s:=  cast(@s - ubicaciones as decimal(3,0)) as posicion_min
				from
				(
				select t.Prioridad, sum(t.Bultos) as bultos, CEIL(sum(t.bultos) / intH) as ubicaciones, @s := intPOSICIONES + 1
				from Tickets t
				where Id_Ruta = intRUTA
				group by Prioridad) sub
				
			) posiciones on posiciones.Prioridad = t.Prioridad
			
			JOIN
			Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna
			JOIN
			province p USING (province_id)
			 JOIN
			Rutas ON t.Id_Ruta = Rutas.Id_Ruta
			 left JOIN
			Vehiculos veh USING (Id_vehiculo)
			 left   JOIN
			Trabajadores trab ON Rutas.Id_Trabajador = trab.Id_Trabajador
		WHERE
			expeditions_id = lngEXPEDITION;
ELSE


			SELECT 
				CEIL((SUM(IF(t.Prioridad > t1.Prioridad,
							t1.Bultos,
							0)) + e.Counter) / CEIL(SUM(t1.Bultos) / 13)) sambori,
				t.Prioridad,
				t.Id_Consigna,
				CONCAT(e.counter, ' / ', t.Bultos) count_bultos,
				e.expeditions_id,
				zone,
				Matricula Vehiculo,
				trab.CodigoTrabajador Chofer,
				Rutas.Id_Ruta,
				RIGHT(Rutas.Id_Ruta, 2) Id_RutaSTR,
				t.Bultos TotalBultos,
				RIGHT(e.expeditions_id,3) expeditions_IDSTR
			FROM
				expeditions e
					JOIN
				Tickets t ON e.ticket_id = t.Id_Ticket
					JOIN
				Tickets t1 ON t.Id_Ruta = t1.Id_Ruta
					JOIN
				Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna
					JOIN
				province p USING (province_id)
					JOIN
				Rutas ON t1.Id_Ruta = Rutas.Id_Ruta
				LEFT JOIN
				Vehiculos veh USING (Id_vehiculo)
				LEFT JOIN
				Trabajadores trab ON Rutas.Id_Trabajador = trab.Id_Trabajador
			WHERE
				expeditions_id = lngEXPEDITION;                      
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 `etiqueta_sambori_2` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `etiqueta_sambori_2`(IN lngEXPEDITION BIGINT, IN intMODE INT, IN intH INT, IN intFILAS INT)
BEGIN

DECLARE intCOLUMNAS INT;
DECLARE intBULTOS INT;
DECLARE intDESCARGAS INT;
DECLARE intRUTA INT;
DECLARE intPOSICIONES INT;



SELECT Id_Ruta INTO intRUTA
FROM Tickets t
JOIN expeditions e on e.ticket_id = t.Id_Ticket
WHERE e.expeditions_id = lngEXPEDITION;


SELECT sum(Bultos) , count(*) , CEIL(SUM(CEIL(Bultos / intH)) / intFILAS), SUM(CEIL(Bultos / intH))
  INTO intBULTOS,intDESCARGAS,  intCOLUMNAS, intPOSICIONES
from
(
SELECT Id_Consigna, sum(Bultos) Bultos
FROM Tickets 
WHERE Id_Ruta = intRUTA
group by Id_Consigna
) sub;




IF intMODE <> 2 THEN

		SELECT 
			CONCAT(   IF(posicion_min MOD intFILAS = 0, intFILAS, posicion_min MOD intFILAS)
                     , MID(' BCDEFG',CEIL(posicion_min /intFILAS),1)
                     , IF(posicion_min = posicion_max,'',' - ')
                     , IF(posicion_min = posicion_max,'',IF(posicion_max MOD intFILAS = 0, intFILAS, posicion_max MOD intFILAS))
                     , IF(posicion_min = posicion_max,'',MID(' BCDEFG',CEIL(posicion_max /intFILAS),1))
                     
				  ) sambori,
			t.Prioridad,
			t.Id_Consigna,
			CONCAT(e.counter, ' / ', t.Bultos) count_bultos,
			e.expeditions_id,
			zone,
			Matricula Vehiculo,
			trab.CodigoTrabajador Chofer,
			Rutas.Id_Ruta,
			RIGHT(Rutas.Id_Ruta, 2) Id_RutaSTR
		FROM
			expeditions e
				JOIN
			Tickets t ON e.ticket_id = t.Id_Ticket
				JOIN
			(
				select Prioridad, cast(@s - 1 as decimal(3,0)) as posicion_max, @s:=  cast(@s - ubicaciones as decimal(3,0)) as posicion_min
				from
				(
				select t.Prioridad, sum(t.Bultos) as bultos, CEIL(sum(t.bultos) / intH) as ubicaciones, @s := intPOSICIONES + 1
				from Tickets t
				where Id_Ruta = intRUTA
				group by Prioridad) sub
				
			) posiciones on posiciones.Prioridad = t.Prioridad
			
			JOIN
			Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna
			JOIN
			province p USING (province_id)
			 JOIN
			Rutas ON t.Id_Ruta = Rutas.Id_Ruta
			 left JOIN
			Vehiculos veh USING (Id_vehiculo)
			 left   JOIN
			Trabajadores trab ON Rutas.Id_Trabajador = trab.Id_Trabajador
		WHERE
			expeditions_id = lngEXPEDITION;
ELSE


			SELECT 
				CEIL((SUM(IF(t.Prioridad > t1.Prioridad,
							t1.Bultos,
							0)) + e.Counter) / CEIL(SUM(t1.Bultos) / 13)) sambori,
				t.Prioridad,
				t.Id_Consigna,
				CONCAT(e.counter, ' / ', t.Bultos) count_bultos,
				e.expeditions_id,
				zone,
				Matricula Vehiculo,
				trab.CodigoTrabajador Chofer,
				Rutas.Id_Ruta,
				RIGHT(Rutas.Id_Ruta, 2) Id_RutaSTR
			FROM
				expeditions e
					JOIN
				Tickets t ON e.ticket_id = t.Id_Ticket
					JOIN
				Tickets t1 ON t.Id_Ruta = t1.Id_Ruta
					JOIN
				Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna
					JOIN
				province p USING (province_id)
					JOIN
				Rutas ON t1.Id_Ruta = Rutas.Id_Ruta
				LEFT JOIN
				Vehiculos veh USING (Id_vehiculo)
				LEFT JOIN
				Trabajadores trab ON Rutas.Id_Trabajador = trab.Id_Trabajador
			WHERE
				expeditions_id = lngEXPEDITION;                      
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 `eti_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 `eti_list`(IN wh_in INT)
BEGIN

SELECT warehouse.name AS Alm_Origen
     , travel.shipment
     , travel.shipment_hour AS ETD
     , warehouse_1.name AS Alm_Destino
     , travel.landing
     ,travel.landing_hour AS ETA
     , awb.codigo AS awb
     , Entradas.Id_Entrada
     , Sum(Compres.Etiquetas) AS bultos
     , Agencias.Agencia
     , producer.name AS producer
     , Proveedores.Proveedor
     , Sum(Compres.Vida) AS Impresas
     , producer.producer_id
     , IFNULL((Entradas.Confirmada AND length(Entradas.Notas) > 0),0) as Ready_to_print
     FROM Compres 
     INNER JOIN Entradas ON Entradas.Id_Entrada = Compres.Id_Entrada
     INNER JOIN travel ON Entradas.travel_id = travel.id
     INNER JOIN warehouse AS warehouse_1  ON warehouse_1.id = travel.warehouse_id
     INNER JOIN warehouse ON warehouse.id = travel.warehouse_id_out
     INNER JOIN Agencias ON Agencias.Id_Agencia = travel.agency_id
     LEFT JOIN recibida_entrada ON Entradas.Id_Entrada = recibida_entrada.Id_Entrada
     LEFT JOIN awb_recibida ON recibida_entrada.awb_recibida = awb_recibida.recibida_id
     LEFT JOIN awb ON awb_recibida.awb_id = awb.id 
     INNER JOIN Articles ON Compres.Id_Article = Articles.Id_Article
     LEFT JOIN producer ON Articles.producer_id = producer.producer_id
     INNER JOIN Proveedores ON Entradas.Id_Proveedor = Proveedores.Id_Proveedor
     
     
	WHERE wh_in IN (travel.warehouse_id_out, travel.warehouse_id) 
    AND travel.landing Between TIMESTAMPADD(DAY,-7,CURDATE()) and TIMESTAMPADD(DAY,14,CURDATE()) 
	GROUP BY warehouse.name, travel.shipment, travel.shipment_hour
         , warehouse_1.name, travel.landing, travel.landing_hour
         , awb.codigo, Entradas.Id_Entrada, Agencias.Agencia
         , producer.name, Proveedores.Proveedor
    ORDER BY travel.landing 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 `eti_to_print` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `eti_to_print`(IN idENTRADA INT, IN idPRODUCER INT)
BEGIN

select Vida as Impresas
	  ,Etiquetas as bultos
      ,Packing
      ,Id_Article
      ,CONCAT(Article,' ',Medida,' ', Categoria) as Articat
      ,p.name as marca
      ,Proveedor
      ,Id_Entrada
      ,Id_Compra
from Compres c
join Entradas e using(Id_Entrada)
join Proveedores using(Id_Proveedor)
join travel tr on tr.id = e.travel_id
join Articles a using(Id_Article)
left join producer p using(producer_id)
where Id_Entrada = idENTRADA
    and idPRODUCER in (0,a.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 */ ;
/*!50003 DROP PROCEDURE IF EXISTS `f10_no_vincular` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `f10_no_vincular`(lngEntrada INTEGER)
    DETERMINISTIC
BEGIN
	DECLARE datFecha DATE DEFAULT CURDATE();
    
-- Modifica el NoVincular si hay dos entradas con el mismo Packing y el mismo Id_Articulo 
	DROP TEMPORARY TABLE IF EXISTS f10_no_vincular_;
	CREATE TEMPORARY TABLE IF NOT EXISTS f10_no_vincular_
		SELECT c.Id_Entrada,c.Id_Compra,c.Id_Article, c.Novincular, c.Packing, be.pri
		FROM Compres c
			JOIN buy_edi be ON c.buy_edi_id = be.id	AND be.fec = datFecha
			LEFT JOIN Entradas_kop ek ON ek.Id_Entrada = c.Id_Entrada
		WHERE
			((ek.Id_Entrada IS NOT NULL AND ek.sub IS NULL)
				OR (c.Id_Entrada = 9200 AND be.ok <> FALSE)
				OR c.Id_Entrada = lngEntrada) AND Id_Article <> 90;
                       
    -- Modifica el NoVincular si hay dos entradas con el mismo Packing y el mismo Id_Articulo
    DROP TEMPORARY TABLE IF EXISTS f10_mismo_Packing;
	CREATE TEMPORARY TABLE IF NOT EXISTS f10_mismo_Packing
		SELECT * FROM (
			SELECT * FROM f10_no_vincular_
		ORDER BY pri DESC) t
			GROUP BY Id_Article,Packing
			HAVING count(Id_Compra) > 1 AND BIT_OR(Id_Entrada = 9200);
 
	UPDATE Compres c
			JOIN buy_edi be ON c.buy_edi_id = be.id	AND be.fec = datFecha
			JOIN f10_mismo_Packing f ON f.Id_Article = c.Id_Article AND c.Packing = f.Packing
			LEFT JOIN Entradas_kop ek ON ek.Id_Entrada = f.Id_Entrada
        SET c.Novincular = IF(c.Id_Compra = f.Id_Compra,0,1)
		WHERE
			((ek.Id_Entrada IS NOT NULL AND ek.sub IS NULL)
				OR (c.Id_Entrada = 9200 AND be.ok <> FALSE)
				OR c.Id_Entrada = lngEntrada);
  
-- Modifica el Id_Articulo si hay dos entradas con packing y el mismo Id_Articulo 
	DROP TEMPORARY TABLE IF EXISTS f10_mismo_Articulo;
	CREATE TEMPORARY TABLE IF NOT EXISTS f10_mismo_Articulo
		SELECT Id_Article FROM (
			SELECT * FROM (
				SELECT * FROM f10_no_vincular_
				ORDER BY Id_Entrada = 9200 DESC) t
				GROUP BY Id_Article,Packing ) t 
          GROUP BY Id_Article HAVING COUNT(*) > 1 AND BIT_OR(Id_Entrada = 9200);
          SELECT 4;       
	UPDATE Compres c
		JOIN buy_edi be ON c.buy_edi_id = be.id	AND be.fec = datFecha
		JOIN f10_mismo_Articulo f ON f.Id_Article = c.Id_Article
		LEFT JOIN Entradas_kop ek ON ek.Id_Entrada = c.Id_Entrada
	SET c.Id_Article = 90
	WHERE c.Id_Entrada = 9200 AND be.ok <> FALSE;
  
	DROP TEMPORARY TABLE IF EXISTS f10_no_vincular_;
	DROP TEMPORARY TABLE IF EXISTS f10_mismo_Packing;
    DROP TEMPORARY TABLE IF EXISTS f10_mismo_Articulo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `F5` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `F5`(IN `idT` BIGINT)
BEGIN
SELECT  C.calidad,
		LEFT(Article, 4) as Subtipo, 
		barcode,
       'ASEGURADO' AS asegurado,
/*CASE A.tipo_id 
WHEN 75 THEN IF(M.Id_Article IN (120,2388,20100,16,10,130,104851,1,56,238,104850,104849,2),'RAMAJE',R.Reino)  
WHEN 68 THEN IF(M.Id_Article IN (11539,10,14),'RAMAJE',R.Reino) 
WHEN 69 THEN IF(M.Id_Article IN (41),'RAMAJE',R.Reino) 
WHEN 72 THEN IF(M.Id_Article IN (238),'RAMAJE',R.Reino) 
WHEN 2 THEN 'CYMBIDIUMS & ANTHURIUMS' 
WHEN 122 THEN 'CYMBIDIUMS & ANTHURIUMS' 
WHEN 12 THEN 'CYMBIDIUMS & ANTHURIUMS' 
WHEN 13 THEN 'CYMBIDIUMS & ANTHURIUMS' 
WHEN 14 THEN 'CYMBIDIUMS & ANTHURIUMS' 
WHEN 15 THEN 'CYMBIDIUMS & ANTHURIUMS'
WHEN 71 THEN IF(LEFT(Article,2) = 'HC','Flor',R.Reino) 
WHEN 19 THEN IF(LEFT(Article,3) IN ('HEL','GIN'),'CYMBIDIUMS & ANTHURIUMS',R.Reino) 
WHEN 70 THEN IF(Article like '%red beauty%' or Article like '%clarinervium%','CYMBIDIUMS & ANTHURIUMS',R.Reino) 
WHEN 86 THEN 'Flor'
ELSE R.Reino
END as*/ Reino,
 /*
CASE A.tipo_id 
WHEN 75 THEN IF(M.Id_Article IN (120,2388,20100,16,10,130,104851,1,56,238,104850,104849,2),-1,R.orden)
WHEN 68 THEN IF(M.Id_Article IN (11539,10,14),-1,R.orden) 
WHEN 69 THEN IF(M.Id_Article IN (41),-1,R.orden) 
WHEN 72 THEN IF(M.Id_Article IN (238),-1,R.orden) 
WHEN 2 THEN 0 
WHEN 122 THEN 0 
WHEN 12 THEN 0 
WHEN 13 THEN 0 
WHEN 14 THEN 0 
WHEN 15 THEN 0
WHEN 71 THEN IF(LEFT(Article,2) = 'HC',1,R.orden) 
WHEN 19 THEN IF(LEFT(Article,3) IN ('HEL','GIN'),0,R.orden) 
WHEN 70 THEN IF(Article like '%red beauty%' or Article like '%clarinervium%',0,R.orden) 
WHEN 86 THEN 1
ELSE R.orden
END as*/R.orden,
		CS.Consignatario,
		T.Id_Cliente,
		NULL AS Id_Trabajador,
		T.Id_Ticket,
		T.Fecha,
		M.Id_Article,
		M.Cantidad,
		M.quantity,
		M.Cantidad / IF(nz(Gro.`Grouping`) = 0,1,nz(Gro.`Grouping`)) as Paquetes,
		IF(sis.vHasBeenPrepared, CONCAT('    ----- PREPARADO -----              ',  M.Concepte), M.Concepte) as Concepte,
		A.Medida,
		A.Color,
		A.Categoria,
		O.Abreviatura as Origen, 
		T.Localizacion,
		CT.CodigoTrabajador as Vendedor,
		T.Bultos,
		T.Observaciones,
		Ag.Agencia Tipo,
		NULL AS CodigoTrabajador,
		M.OK,
		M.Reservado,
		A.Tallos,
		Gro.`Grouping`,
		IF(`transaction`,right(concat('000000' ,M.Id_Article),6),M.Id_Movimiento) Id_Movimiento,
		IF(sis.vHasBeenPrepared,'RES',an.Nicho) as Nicho,
		'PEDIDO ASEGURADO' AS MSG,
		T.Id_Ruta,
		RT.Id_Vehiculo,
		observation_type_id,
		group_concat(IF(observation_type_id = 1,text,'') SEPARATOR '') 'sacador',
		group_concat(IF(observation_type_id = 2,text,'') SEPARATOR '') 'encajador',
		A.Foto,
		M.Id_Movimiento movement_id,
		lpad(IF(sis.vHasBeenPrepared,99999,ifnull(cooler_path_detail_id, an.Nicho)),5,'0') as path, 
		M.Descuento,M.Preu, mm.valor as Preparado, mm.original_quantity 
        , p.`name` producer, 
        T.warehouse_id, 
        ST.id as idStowaway,
        STP.shipFk as isStowaway,
        CS.POBLACION -- JGF 2016-02-16
FROM 

    Tickets T
    LEFT JOIN Movimientos M USING(Id_Ticket)
    LEFT JOIN (SELECT DISTINCT saleFk, TRUE as vHasBeenPrepared
					FROM vn.saleItemShelving sis
						JOIN vn.sale s ON s.id = sis.saleFk
                    WHERE s.ticketFk = idT 
						AND sis.quantity > 0
			   ) sis ON sis.saleFk = M.Id_Movimiento                    
    LEFT JOIN Articles A on A.Id_Article = M.Id_Article 
	LEFT JOIN Articles_nicho an ON A.Id_Article = an.Id_Article AND an.warehouse_id = T.warehouse_id
    LEFT JOIN producer p on p.producer_id = A.producer_id -- JGF 2016-02-16
	LEFT JOIN cooler_path_detail c on left(an.Nicho,3) = pasillo 
    LEFT JOIN Origen O ON A.id_origen = O.id  
    LEFT JOIN Clientes C USING(Id_Cliente)
    LEFT JOIN Trabajadores CT ON C.Id_Trabajador = CT.Id_Trabajador
    INNER JOIN Consignatarios CS ON T.Id_Consigna = CS.Id_Consigna
	INNER JOIN Agencias Ag ON Ag.Id_Agencia = T.Id_Agencia
    LEFT JOIN (
                SELECT Id_Article, code as barcode
                FROM barcodes 
                GROUP BY Id_Article
              )  BC ON BC.Id_Article = A.Id_Article
    LEFT JOIN Tipos TP USING(tipo_id) 
    LEFT JOIN reinos R ON TP.reino_id = R.id  
    LEFT JOIN Rutas RT USING(Id_Ruta) 
    LEFT JOIN ticket_observation tobs ON T.Id_Ticket = tobs.Id_ticket 
                    AND (tobs.observation_type_id = 1 or tobs.observation_type_id = 2)

	LEFT JOIN (
				SELECT Id_Article, `Grouping`
				FROM (
						SELECT landing, Id_Article, CASE caja 
                                                       WHEN 0 THEN 1 
                                                       WHEN 2 THEN Packing
                                                       ELSE `Grouping`
													END	as `Grouping`
						FROM Compres C
						JOIN Entradas E USING(Id_Entrada)
						JOIN travel TR ON TR.id = travel_id
						WHERE warehouse_id = (SELECT warehouse_id FROM Tickets WHERE Id_Ticket = idT)
						AND landing between (SELECT FechaInventario FROM tblContadores LIMIT 1) AND (SELECT date(Fecha) FROM Tickets WHERE Id_Ticket = idT)
						ORDER BY landing DESC
					) GR1
				GROUP BY Id_Article

			  ) Gro ON Gro.Id_Article = M.Id_Article
	LEFT JOIN Movimientos_mark mm ON mm.Id_Movimiento = M.Id_Movimiento
    LEFT JOIN vn.stowaway ST ON ST.shipFk = idT
    LEFT JOIN vn.stowaway STP on STP.id = idT

    WHERE T.Id_Ticket = idT 
    group by M.Id_Movimiento;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `F5_entrada` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `F5_entrada`(IN idE BIGINT)
BEGIN


SELECT 
    NULL AS Sacador,
    NULL AS Encajador,
    v.Cantidad / v.Packing AS Paquetes,
    v.Packing AS `Grouping`,
    barcode,
    'ASEGURADO' AS asegurado,
    reino,
    r.orden,
    Alias AS Consignatario,
    v.Id_Proveedor AS Id_Cliente,
    v.Pedida,
    v.Confirmada,
    NULL AS vendedor,
    10 AS Calidad,
    LPAD(IFNULL(cooler_path_detail_id, an.Nicho),
            5,
            '0') AS path,
    TB.Id_Trabajador,
    v.Id_Entrada AS Id_Ticket,
    landing AS Fecha,
    v.Id_Article,
    v.Cantidad,
    v.article AS Concepte,
    v.Medida,
    v.Color,
    v.Categoria,
    Abreviatura AS Origen,
    NULL AS Localizacion,
    0 AS Bultos,
    w.`name` AS Tipo,
    CodigoTrabajador,
    0 AS OK,
    0 AS Reservado,
    v.Tallos,
    v.Id_Compra AS Id_Movimiento,
    an.Nicho,
    'PEDIDO ASEGURADO' AS MSG,
    0 AS Seguro,
    0 AS Id_Ruta,
    0 AS Id_Vehiculo,
	a.Foto,
	pr.name as producer
FROM
    v_compres v
		 LEFT JOIN
    Articles_nicho an ON v.Id_Article = an.Id_Article AND an.warehouse_id = v.warehouse_id_out
        JOIN
    warehouse w ON w.id = v.warehouse_id
        LEFT JOIN
    Tipos USING (tipo_id)
        LEFT JOIN
    reinos r ON r.id = Tipos.reino_id
        LEFT JOIN
    Trabajadores TB ON TB.Id_Trabajador = v.Id_Trabajador
        LEFT JOIN
    Proveedores p ON p.Id_Proveedor = v.Id_Proveedor
        LEFT JOIN
    (SELECT 
        Id_Article, code AS barcode
    FROM
        barcodes
    GROUP BY Id_Article) BC ON BC.Id_Article = v.Id_Article
        LEFT JOIN
    Articles a ON a.Id_Article = v.Id_Article
		LEFT JOIN
	producer pr on pr.producer_id = a.producer_id
        LEFT JOIN
    cooler_path_detail c ON LEFT(v.Nicho, 3) = pasillo
        LEFT JOIN
    Origen o ON o.id = v.Id_origen
WHERE
        v.Id_Entrada = idE
        AND v.tipo_id IS NOT 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 `Facturas_Saltos` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `Facturas_Saltos`(IN datSTART DATE , IN datEND DATE)
BEGIN


DECLARE strSER1 VARCHAR(2);
DECLARE strSER2 VARCHAR(2);
DECLARE intEMP1 INT;
DECLARE intEMP2 INT;
DECLARE v_done BOOLEAN DEFAULT FALSE;
DECLARE strFAC1 VARCHAR(11);
DECLARE strFAC2 VARCHAR(11);


DECLARE rs CURSOR FOR
	SELECT Id_Factura, empresa_id, Serie 
    FROM Facturas 
    WHERE Fecha BETWEEN datSTART AND datEND
    ORDER BY empresa_id, Serie, Id_Factura;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_done = TRUE;

OPEN rs;

DROP TEMPORARY TABLE IF EXISTS Facturas_Saltarinas;

CREATE TEMPORARY TABLE Facturas_Saltarinas
(Factura_Inicial VARCHAR(11),
 Factura_Final VARCHAR(11),
 Empresa VARCHAR(3),
 Serie VARCHAR(1));

FETCH rs INTO strFAC1, intEMP1, strSER1;

IF NOT v_done THEN

	FETCH rs INTO strFAC2, intEMP2, strSER2;
    
END IF;

WHILE NOT v_done DO

	IF strSER1 = strSER2 AND intEMP1 = intEMP2 AND right(strFAC2,5) - right(strFAC1,5) > 1 then
    
		INSERT INTO Facturas_Saltarinas(Factura_Inicial, Factura_Final, Empresa, Serie)
        SELECT strFAC1, strFAC2, abbreviation, strSER1
        FROM empresa
        WHERE id = intEMP1;
    
    END IF;

	SET strFAC1 = strFAC2;
	SET intEMP1 = intEMP2;
	SET STRSER1 = strSER2;

	FETCH rs INTO strFAC2, intEMP2, strSER2;

END WHILE;

SELECT * FROM Facturas_Saltarinas;

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 `Factura_vuelve` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `Factura_vuelve`(IN strFactura VARCHAR(10), IN intCLI INT )
BEGIN

DECLARE dblIMPORTE DOUBLE;
DECLARE datFEC DATE;
DECLARE intEMP INT;
DECLARE intCLI_OLD INT;

/*Este procedure no funcionara correctament perque el strFactura ha de fer referencia al factura_id*/
SELECT Importe,    Fecha,  empresa_id, Id_Cliente 
INTO   dblIMPORTE, datFEC, intEMP,     intCLI_OLD
FROM Facturas WHERE Id_Factura = strFactura;

-- Cambia la empresa de la factura

UPDATE Facturas SET empresa_id = 965, Id_Cliente = intCLI WHERE Id_Factura = strFactura;

-- Cambia la empresa de los tickets

UPDATE Tickets SET empresa_id = 965, Id_Cliente = intCLI WHERE Factura = strFactura;


-- Descuenta la cantidad del cliente antiguo

INSERT INTO Recibos(Id_Factura
                   ,Entregado
                   ,Fechacobro
                   ,Id_Trabajador
                   ,Id_Banco
                   ,Id_Cliente
                   ,empresa_id)
                    
VALUES             (strFactura
                   ,-1 * dblIMPORTE
                   ,datFEC
                   ,2
                   ,430
                   ,intCLI_OLD
                   ,intEMP);

-- Carga el cobro en la cuenta del nuevo cliente
                   
INSERT INTO Recibos(Id_Factura
                   ,Entregado
                   ,Fechacobro
                   ,Id_Trabajador
                   ,Id_Banco
                   ,Id_Cliente
                   ,empresa_id)
                    
VALUES             (strFactura
                   ,dblIMPORTE
                   ,datFEC
                   ,2
                   ,430
                   ,intCLI
                   ,965);




END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `gescartera_Estados` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `gescartera_Estados`(IN intAno INT,IN intMes INT,IN intDiasPerdidos INT)
BEGIN
DECLARE intCLI,intCLI2 INT DEFAULT 0;
DECLARE datFEC,datFEC2,auxdatFEC DATE DEFAULT '2001-01-01';
DECLARE lngTIC, lngTIC2 BIGINT DEFAULT 0;
DECLARE intDiferencia INT DEFAULT 0; # Variable donde se colocará la diferencia de días entre dos fechas.
DECLARE done,EsPerdido bit DEFAULT 0;
DECLARE intEstado TINYINT(2) DEFAULT 0;
DECLARE intNuevo INT DEFAULT 1;
DECLARE intPerdido INT DEFAULT 2;
DECLARE intRecuperado INT DEFAULT 3;


# Añado una fecha de fin para que no tenga en cuenta los tickets  del futuro. (and Fecha<=current_date())
/*
DECLARE cursor1 CURSOR FOR SELECT Id_Ticket,ti.Id_Cliente,date_format(Fecha,'%Y-%m-%d') AS FormatoFecha 
FROM vn2008.Tickets ti
WHERE DATE_FORMAT(Fecha,'%Y-%m-%d')>CAST(CONCAT(YEAR(CURDATE())-2,'-','01-01')AS DATE)
AND DATE_FORMAT(Fecha,'%Y-%m-%d')<=LAST_DAY(CAST(CONCAT(intAno, '-' , intMes,'-',01) AS DATE))
ORDER BY ti.Id_Cliente,Fecha;
*/
DECLARE cursor1 CURSOR FOR SELECT Id_Ticket,fac.Id_Cliente,date_format(Fecha,'%Y-%m-%d') AS FormatoFecha 
FROM Facturas fac
JOIN (SELECT Id_Ticket,Id_Cliente,Factura from Tickets ti where Factura is not null order by Fecha DESC,Id_Ticket DESC) sub1
on fac.Id_Factura=sub1.Factura
WHERE DATE_FORMAT(Fecha,'%Y-%m-%d')>CAST(CONCAT(YEAR(CURDATE())-2,'-','01-01')AS DATE)
AND DATE_FORMAT(Fecha,'%Y-%m-%d')<=LAST_DAY(CAST(CONCAT(intAno, '-' , intMes,'-',01) AS DATE))
group by Id_Cliente,Fecha
order by sub1.Id_Cliente,FormatoFecha;

DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;
DECLARE CONTINUE HANDLER FOR 1146 
BEGIN 

DROP TEMPORARY TABLE IF EXISTS GC;  

CREATE TEMPORARY TABLE GC (Id_Ticket BIGINT,Fecha DATE,Id_Cliente int,Estado SMALLINT) ENGINE=MEMORY;

OPEN cursor1;
    FETCH cursor1 INTO lngtIC,intCLI,datFEC;
     # el primero registro es un cliente nuevo.
    INSERT INTO GC(Id_Ticket, Fecha, Id_Cliente, Estado) VALUES(lngtIC,datFEC, intCLI,intNuevo);
	SET auxdatFEC=datFEC;  
    
    WHILE NOT DONE DO
        FETCH cursor1 INTO lngtIC2,intCLI2,datFEC2;
        CASE
            WHEN DONE THEN SET intDiferencia=DATEDIFF(CURRENT_DATE,datFEC2);
            WHEN intCLI=intCLI2 THEN
                SET intDiferencia=DATEDIFF(datFEC2,datFEC);
                IF ((intEstado=2)) THEN -- es recuperado despues de haberse perdido
                     INSERT INTO GC(Id_Ticket, Fecha, Id_Cliente, Estado) VALUES (lngtIC2,datFEC2, intCLI,intRecuperado);  # RECUPERADO
                     SET intEstado=1;
					 SET auxdatFEC=datFEC2; 
				ELSE
					 IF (intDiferencia >= intDiasPerdidos)  THEN
						--  IF (DATE_FORMAT(datFEC2,'%Y-%m')<>DATE_FORMAT(DATE_ADD(datFEC,INTERVAL intDiasPerdidos DAY),'%Y-%m')) AND (intEstado<2) THEN		
							INSERT INTO GC(Id_Ticket, Fecha, Id_Cliente, Estado) VALUES (0,DATE_ADD(auxdatFEC,INTERVAL intDiasPerdidos DAY), intCLI,intPerdido);  
							INSERT INTO GC(Id_Ticket, Fecha, Id_Cliente, Estado) VALUES (lngtIC2,datFEC2, intCLI,intRecuperado);  # RECUPERADO
							SET intEstado=1,auxdatFEC=datFEC2;
						 -- ELSE
						 -- INSERT INTO GC(Id_Ticket, Fecha, Id_Cliente, Estado) VALUES (lngtIC2,datFEC2, intCLI,intPerdido);  # PERDIDO
						 -- SET intEstado=2; # Lo marcamos como perdido	
						 --  END IF;
						 		
                     END IF;
                END IF;
            WHEN intCLI<>intCLI2 THEN 
				SET intEstado=0;
                SET intDiferencia=DATEDIFF(CURRENT_DATE,datFEC);
                INSERT INTO GC(Id_Ticket, Fecha, Id_Cliente, Estado) VALUES(lngtIC2,datFEC2, intCLI2,intNuevo);  # NUEVO	
				SET auxdatFEC=datFEC2;  
        END CASE;
        SET datFEC=datFEC2;
        SET intCLI=intCLI2;
        SET lngTIC = lngTIC2,auxdatFEC=datFEC2;
        
    END WHILE;

    CLOSE cursor1;
    
    
    # inserto los registros de clientes sin ticket (Estado 4)
    INSERT GC 
    SELECT 0,'2000-01-01',Id_Cliente,4 
    FROM vn2008.Clientes 
    WHERE Id_Cliente NOT IN
            (select distinct Id_Cliente 
            FROM vn2008.Tickets order by id_cliente);
            
    SELECT Id_Ticket, Fecha, Id_Cliente, CASE ESTADO 
    WHEN 1 THEN 'NUEVO' 
    WHEN 2 THEN 'PERDIDO' 
    WHEN 3 THEN 'RECUPERADO' 
    ELSE 'SIN TICKET' END AS Estado,CodigoTrabajador
    FROM GC
    INNER JOIN vn2008.Clientes cli USING (Id_Cliente)
    INNER JOIN vn2008.Trabajadores trab USING (Id_Trabajador);        
            
END;

    IF EXISTS (SELECT * FROM GC LIMIT 1) THEN
    
    SELECT Id_Ticket, Fecha, Id_Cliente, CASE ESTADO 
    WHEN 1 THEN 'NUEVO' 
    WHEN 2 THEN 'PERDIDO' 
    WHEN 3 THEN 'RECUPERADO' 
    ELSE 'SIN TICKET' END AS Estado,CodigoTrabajador
    FROM GC
    INNER JOIN vn2008.Clientes cli USING (Id_Cliente)
    INNER JOIN vn2008.Trabajadores trab USING (Id_Trabajador);
    
    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 `get_barcodes_ticket` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `get_barcodes_ticket`(IN idT BIGINT)
BEGIN
	
	drop temporary  TABLE IF EXISTS articles_ticket;
	CREATE TEMPORARY TABLE IF NOT EXISTS articles_ticket
	(PRIMARY KEY (Id_Article))
	  ENGINE = MEMORY
	select distinct Id_Article from Movimientos where Id_Ticket = idT;

	drop temporary  TABLE IF EXISTS articles_ticket2;
	CREATE TEMPORARY TABLE IF NOT EXISTS articles_ticket2
	(PRIMARY KEY (Id_Article))
	  ENGINE = MEMORY
	select * from articles_ticket;
	
	drop temporary  TABLE IF EXISTS articles_buys;
	CREATE TEMPORARY TABLE IF NOT EXISTS articles_buys AS 
	select Id_Compra, a.Id_Article from v_compres c JOIN articles_ticket a ON a.Id_Article = c.Id_Article
	 where landing >= DATE_SUB(CURDATE(), INTERVAL 14 DAY);

	SELECT distinct
		code, a.Id_Article
	FROM
		barcodes b
			inner join
		articles_ticket a ON a.Id_Article = b.Id_Article 
	union 
	SELECT 
		Id_Compra as code, a.Id_Article
	FROM
		articles_buys c
			inner join
		articles_ticket2 a ON a.Id_Article = c.Id_Article;
	
	drop temporary  TABLE IF EXISTS articles_ticket;
	drop temporary  TABLE IF EXISTS articles_ticket2;
	drop temporary  TABLE IF EXISTS articles_buys;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `historico` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `historico`(IN idART INT, IN wh INT, IN v_virtual INT)
BEGIN
-- DEPRECATED use vn.itemDiary
DECLARE datFEC DATETIME;

SELECT Fechainventario INTO datFEC FROM tblContadores;
SET @a = 0;
SELECT DATE(Fecha) AS Fecha,
		Entrada,
		Salida,
		OK,
		Alias,
		Referencia,
		id,
		@a := @a + IFNULL(Entrada,0) - IFNULL(Salida,0) as acumulado,
		F5,
		v_virtual,
		Calidad,CodigoTrabajador
FROM

    ( SELECT TR.landing as Fecha,
			C.Cantidad as Entrada,
			NULL as Salida,
			(TR.received != FALSE) as OK,
			P.Proveedor as Alias,
			E.Referencia as Referencia,
			E.Id_Entrada as id,
			TR.delivered as F5,
			0 as Calidad, tra.CodigoTrabajador
      FROM Compres C
		JOIN Entradas E USING (Id_Entrada)
		JOIN travel TR ON TR.id = E.travel_id
		JOIN Proveedores P USING (Id_Proveedor)
		LEFT JOIN Articles a ON a.Id_Article = C.Id_Article
		LEFT JOIN Tipos ti ON ti.Id_Tipo = a.tipo_id
		LEFT JOIN Trabajadores tra ON tra.Id_Trabajador = ti.Id_Trabajador
      WHERE TR.landing >= datFEC
      AND wh IN (TR.warehouse_id , 0)
      AND C.Id_Article = idART
      AND E.Inventario = 0

    UNION ALL

      SELECT TR.shipment as Fecha,
             NULL as Entrada,
             C.Cantidad as Salida,
             TR.delivered as OK,
             P.Proveedor as Alias,
             E.Referencia as Referencia,
             E.Id_Entrada as id,
			TR.delivered as F5,
			0 as Calidad, tra.CodigoTrabajador

	FROM Compres C
		JOIN Entradas E USING (Id_Entrada)
		JOIN travel TR ON TR.id = E.travel_id
		JOIN warehouse ON warehouse.id = TR.warehouse_id_out
		JOIN Proveedores P USING (Id_Proveedor)
		LEFT JOIN Articles a ON a.Id_Article = C.Id_Article
		LEFT JOIN Tipos ti ON ti.Id_Tipo = a.tipo_id
		LEFT JOIN Trabajadores tra ON tra.Id_Trabajador = ti.Id_Trabajador
      WHERE TR.shipment >= datFEC
      AND wh IN (TR.warehouse_id_out,0)
      AND Id_Proveedor <> 4
      AND C.Id_Article = idART
      AND E.Inventario = 0
      AND fuente = 0

    UNION ALL

	SELECT T.Fecha as Fecha,
		NULL as Entrada,
		M.Cantidad as Salida,
		(IFNULL(ts.alertLevel,0) > 1 OR ok )  as OK,
		T.Alias as Alias,
		T.Localizacion as Referencia,
		T.Id_Ticket as id,
		FALSE EtiquetasEmitidas,
		C.Calidad, tr.CodigoTrabajador

		FROM Movimientos M
			JOIN Tickets T USING (Id_Ticket)
            LEFT JOIN vn.ticketState ts ON ts.ticket = T.Id_Ticket
			JOIN Clientes C ON C.Id_Cliente = T.Id_Cliente
			LEFT JOIN Trabajadores tr ON tr.Id_Trabajador = C.Id_Trabajador
			WHERE T.Fecha >= datFEC
			AND M.Id_Article = idART
			AND wh IN (T.warehouse_id , 0)

     ) AS Historico
ORDER BY Fecha, OK DESC, Entrada 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 `historicoprecio` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `historicoprecio`( id_art INT, id_wh INT,id_datestart DATE,id_dateend DATE)
BEGIN 

    
    SET @@max_sp_recursion_depth = 100 ;
   DROP TEMPORARY TABLE IF EXISTS historicoprecio;
    
    CREATE TEMPORARY TABLE historicoprecio
    (
        date_start DATE,
        rate_0 DOUBLE,
        rate_1 DOUBLE,
        rate_2 DOUBLE,
        rate_3 DOUBLE,
        PRIMARY KEY (date_start)
    )
    ENGINE = MEMORY;

        
    CALL historicoprecio2 (id_art,id_wh,id_datestart,id_dateend);
    

    SET @a:= @b:= @c:= @d:= @e:= @f := @g:= @h:=0.0;
    SELECT * FROM 
    (SELECT d.`date` landing,if(rate_0 IS NULL,@a,@a:=rate_0) Costefijo,if(rate_1 IS NULL,@b,@b:=rate_1) rate_1,
        if(rate_2 IS NULL,@c,@c:=rate_2) rate_2,if(rate_3 IS NULL,@d,@d:=rate_3) rate_3,'PF' tipo FROM `time` d 
        LEFT JOIN historicoprecio hp ON d.`date` = hp.date_start WHERE d.`date` BETWEEN id_datestart AND id_dateend
    UNION ALL
        SELECT DISTINCT d.`date` ,if(Costefijo IS NULL,@e,@e:=Costefijo) Costefijo,if(Tarifa1 IS NULL,@f,@f:=Tarifa1),
			if(Tarifa2 IS NULL,@g,@g:=Tarifa2),if(Tarifa3 IS NULL,@h,@h:=Tarifa3),'C' 
        FROM `time` d 
			LEFT JOIN travel t ON t.landing = d.`date` 
			LEFT JOIN Entradas e ON e.travel_id = t.id 
			LEFT JOIN Compres c ON c.Id_Entrada = e.Id_Entrada AND id_wh IN (0,warehouse_id) AND c.Id_Article = id_art AND NoVincular = FALSE 
        WHERE d.`date` BETWEEN id_datestart AND id_dateend
    ) 
    t ORDER BY landing 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 `historicoprecio2` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `historicoprecio2`( id_art INT, id_wh INT,id_datestart DATE,id_dateend DATE)
BEGIN 
    DECLARE done BIT DEFAULT 0;
    DECLARE datini,datfin,datiniaux,datfinaux DATE;
    DECLARE dblrate0,dblrate0aux,dblrate1,dblrate1aux,dblrate2,dblrate2aux,dblrate3,dblrate3aux DOUBLE DEFAULT 0;
    DECLARE boolBeforeStart TINYINT DEFAULT 1;
    -- selecciona el primer bloque apartir de la mínima fecha que esta dentro del rango y la fecha de finalizar es posterior
    SET datiniaux = NULL;
    SET datfinaux = NULL;
    -- guarda en dblrate0aux el valor del valor del  periode, a lo millor falla si no trau cap linea
    SELECT IFNULL(rate_0,0), IFNULL(rate_1,0), IFNULL(rate_2,0), IFNULL(rate_3,0) 
        INTO dblrate0aux,dblrate1aux,dblrate2aux,dblrate3aux FROM price_fixed 
            WHERE date_start = id_datestart AND warehouse_id IN (0,id_wh) AND item_id = id_art;
 
    REPEAT

        SET datini = NULL;
        SET datfin = NULL;
        SET dblrate0 = NULL;
        SET dblrate1 = NULL;
        SET dblrate2 = NULL;
        SET dblrate3 = NULL;
        SELECT date_start,date_end,rate_0,rate_1,rate_2,rate_3 INTO datini,datfin,dblrate0,dblrate1,dblrate2,dblrate3 FROM price_fixed
            WHERE item_id = id_art AND warehouse_id IN (0,id_wh) AND date_end < id_dateend
            AND date_end >= IFNULL(datfinaux,id_datestart) AND date_start = (SELECT MIN(date_start) FROM price_fixed 
            WHERE date_start >= IFNULL(datiniaux,TIMESTAMPADD(DAY,1,id_datestart)) AND  item_id = id_art AND warehouse_id IN (0,id_wh) ) 
            ORDER BY date_start LIMIT 1;
      
        IF datini IS NOT NULL THEN
            -- Inserta un registre(dia -1) 
            IF boolBeforeStart THEN
                INSERT INTO historicoprecio(date_start,rate_0,rate_1,rate_2,rate_3) 
                    VALUES(TIMESTAMPADD(DAY,-1,datini),dblrate0aux,dblrate1aux,dblrate2aux,dblrate3aux);
                SET boolBeforeStart = TRUE;
            END IF;
            -- reiniciem els valors de les variables
            SET datiniaux = NULL;
            SET datfinaux = NULL;
            -- seleccionem el dia fins al qual dura el periode eliminant els dies que queden solapats
            SELECT MIN(date_start) INTO datfinaux FROM price_fixed WHERE date_start > datini AND date_start < datfin AND date_end >= datfin 
                     AND warehouse_id IN (0,id_wh) AND item_id = id_art;
            
            -- cridada recursiva per al periode(retallat si cal) inclós
            CALL historicoprecio2 (id_art,id_wh,datini,IFNULL(datfinaux,datfin));
            -- anyadeix el valor que ha d'agafar el dia seguent d'acabar el periode actual.
            IF datfinaux IS NULL THEN
                INSERT INTO historicoprecio(date_start,rate_0,rate_1,rate_2,rate_3) 
                    VALUES(TIMESTAMPADD(DAY,1,datfin),dblrate0aux,dblrate1aux,dblrate2aux,dblrate3aux),
                          (datfin,dblrate0,dblrate1,dblrate2,dblrate3);
            ELSE
                INSERT INTO historicoprecio(date_start,rate_0,rate_1,rate_2,rate_3) 
                    VALUES(TIMESTAMPADD(DAY,-1,datfinaux),dblrate0,dblrate1,dblrate2,dblrate3);
                SET boolBeforeStart = FALSE;
            END IF;
            SET datiniaux=TIMESTAMPADD(DAY,1,datini);
            SET datfinaux=datfin;
          
        END IF;
    UNTIL datini IS NULL END REPEAT;
        -- inserta linea caso base
    INSERT INTO historicoprecio(date_start,rate_0,rate_1,rate_2,rate_3) VALUES(id_datestart,dblrate0aux,dblrate1aux,dblrate2aux,dblrate3aux) 
        ON DUPLICATE KEY UPDATE rate_0 = dblrate0,rate_1 = dblrate1,rate_2 = dblrate2,rate_3 = dblrate3;    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `historico_absoluto` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `historico_absoluto`(IN idART INT, IN wh INT, IN datfecha DATETIME)
BEGIN

DECLARE inv_calculado INT;
DECLARE inv INT;
DECLARE today DATETIME;
DECLARE fecha_inv DATETIME;
SET today = curdate();

	DROP TEMPORARY TABLE IF EXISTS historico_pasado;
  CREATE TEMPORARY TABLE historico_pasado
    SELECT *
	FROM (
	  SELECT TR.landing as Fecha,
             C.Cantidad as Entrada,
             NULL as Salida,
             (TR.received != FALSE) as OK,
             P.Proveedor as Alias,
             E.Referencia as Referencia,
             E.Id_Entrada as id,
             TR.delivered as F5, 0 as Calidad
      		FROM Compres C -- mirar perque no entra en received
      		INNER JOIN Entradas E USING (Id_Entrada)
      		INNER JOIN travel TR ON TR.id = E.travel_id
      		INNER JOIN Proveedores P USING (Id_Proveedor)
      		WHERE TR.landing >= '2001-01-01'
	 		  AND Id_proveedor <> 4
      			AND wh IN (TR.warehouse_id , 0)
     			AND C.Id_Article = idART
      			AND E.Inventario = 0

    	UNION ALL

      SELECT TR.shipment as Fecha,
             NULL as Entrada,
             C.Cantidad as Salida,
             TR.delivered as OK,
             P.Proveedor as Alias,
             E.Referencia as Referencia,
             E.Id_Entrada as id,
             TR.delivered as F5, 0 as Calidad
      FROM Compres C
      INNER JOIN Entradas E USING (Id_Entrada)
      INNER JOIN travel TR ON TR.id = E.travel_id
      INNER JOIN Proveedores P USING (Id_Proveedor)

      WHERE TR.shipment >= '2001-01-01'
      AND wh = TR.warehouse_id_out
      AND Id_Proveedor <> 4
      AND C.Id_Article = idART
      AND E.Inventario = 0

    UNION ALL

      SELECT T.Fecha as Fecha,
			NULL as Entrada,
			M.Cantidad as Salida,
			(M.OK <> 0 OR T.Etiquetasemitidas <> 0 OR T.Factura IS NOT NULL)  as OK,
			T.Alias as Alias,
			T.Factura as Referencia,
			T.Id_Ticket,T.PedidoImpreso,
			C.Calidad
		FROM Movimientos M
		INNER JOIN Tickets T USING (Id_Ticket)
        JOIN Clientes C ON C.Id_Cliente = T.Id_Cliente
		WHERE T.Fecha >= '2001-01-01'
		AND M.Id_Article = idART
		AND wh IN (T.warehouse_id , 0)
     ) as t1 ORDER BY Fecha, Entrada DESC, OK DESC;

	SELECT sum(Entrada) - sum(Salida) INTO inv_calculado
  FROM historico_pasado
  WHERE Fecha < datfecha;
  
	-- WHERE historico_pasado.Fecha < fecha_inv ;


SELECT p1.*, NULL as v_virtual FROM(
	SELECT datfecha as Fecha,inv_calculado as Entrada, NULL as Salida,1 as OK,
	'Inventario calculado' as Alias, '' as Referencia, 0 as id, 1 as F5, 0 as Calidad
	UNION ALL
	SELECT * FROM historico_pasado WHERE Fecha >= datfecha
	)as p1;


DROP TEMPORARY TABLE historico_pasado;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `historico_joined` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `historico_joined`(IN idART INT, IN wh_joined INT, IN v_virtual INT)
BEGIN
DECLARE datFEC DATETIME;

SELECT Fechainventario INTO datFEC FROM tblContadores;
SET @a = 0;
SELECT DATE(Fecha) AS Fecha,
		Entrada,
		Salida,
		OK,
		Alias,
		Referencia,
		id,
		@a := @a + IFNULL(Entrada,0) - IFNULL(Salida,0) as acumulado,
		F5,
		v_virtual,
		Calidad,CodigoTrabajador
FROM

    ( SELECT TR.landing as Fecha,
			C.Cantidad as Entrada,
			NULL as Salida,
			(TR.received != FALSE) as OK,
			P.Proveedor as Alias,
			E.Referencia as Referencia,
			E.Id_Entrada as id,
			TR.delivered as F5,
			0 as Calidad, tra.CodigoTrabajador
      FROM Compres C
		JOIN Entradas E USING (Id_Entrada)
		JOIN travel TR ON TR.id = E.travel_id
		JOIN Proveedores P USING (Id_Proveedor)
		LEFT JOIN Articles a ON a.Id_Article = C.Id_Article
		LEFT JOIN Tipos ti ON ti.Id_Tipo = a.tipo_id
		LEFT JOIN Trabajadores tra ON tra.Id_Trabajador = ti.Id_Trabajador
		LEFT JOIN warehouse_joined wj ON wj.warehouse_id = TR.warehouse_id
      WHERE TR.landing >= datFEC
      AND wh_joined IN (wj.warehouse_alias_id , 0)
      AND C.Id_Article = idART
      AND E.Inventario = 0

    UNION ALL

      SELECT TR.shipment as Fecha,
             NULL as Entrada,
             C.Cantidad as Salida,
             TR.delivered as OK,
             P.Proveedor as Alias,
             E.Referencia as Referencia,
             E.Id_Entrada as id,
			TR.delivered as F5,
			0 as Calidad, tra.CodigoTrabajador

	FROM Compres C
		JOIN Entradas E USING (Id_Entrada)
		JOIN travel TR ON TR.id = E.travel_id
		JOIN Proveedores P USING (Id_Proveedor)
		LEFT JOIN Articles a ON a.Id_Article = C.Id_Article
		LEFT JOIN Tipos ti ON ti.Id_Tipo = a.tipo_id
		LEFT JOIN Trabajadores tra ON tra.Id_Trabajador = ti.Id_Trabajador
		LEFT JOIN warehouse_joined wj ON wj.warehouse_id = TR.warehouse_id_out
      WHERE TR.shipment >= datFEC
      AND wh_joined IN (wj.warehouse_alias_id,0)
      AND Id_Proveedor <> 4
      AND C.Id_Article = idART
      AND E.Inventario = 0

    UNION ALL

	SELECT T.Fecha as Fecha,
		NULL as Entrada,
		M.Cantidad as Salida,
		(M.OK <> 0 OR T.Etiquetasemitidas <> 0 OR T.Factura IS NOT NULL)  as OK,
		T.Alias as Alias,
		T.Localizacion as Referencia,
		T.Id_Ticket as id,
		T.PedidoImpreso EtiquetasEmitidas,
		C.Calidad, tr.CodigoTrabajador

		FROM Movimientos M
			JOIN Tickets T USING (Id_Ticket)
			JOIN Clientes C ON C.Id_Cliente = T.Id_Cliente
			LEFT JOIN Trabajadores tr ON tr.Id_Trabajador = C.Id_Trabajador
			LEFT JOIN warehouse_joined wj ON wj.warehouse_id = T.warehouse_id
			WHERE T.Fecha >= datFEC
			AND M.Id_Article = idART
			AND wh_joined IN (wj.warehouse_alias_id , 0)

     ) AS Historico
ORDER BY Fecha, Entrada DESC, OK 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 `historico_multiple` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `historico_multiple`(IN idART INT)
BEGIN

DECLARE datFEC DATETIME;

SELECT Fechainventario INTO datFEC FROM tblContadores;

SET @a = 0;

DROP TEMPORARY TABLE IF EXISTS hm1;

CREATE TEMPORARY TABLE hm1
SELECT DATE(Fecha) as Fecha,
       Entrada,
       Salida,
       OK,
       Referencia,
       Historia.id,
       
       wh,
       
       `name` as wh_name

FROM

    ( SELECT TR.landing as Fecha,
             C.Cantidad as Entrada,
             NULL as Salida,
             
             IF(warehouse_id = 44, 1, warehouse_id) as wh,
             (TR.received != FALSE) as OK,
             E.Referencia as Referencia,
             E.Id_Entrada as id
             
            

      FROM Compres C
      INNER JOIN Entradas E USING (Id_Entrada)
      INNER JOIN travel TR ON TR.id = E.travel_id
      WHERE TR.landing >= datFEC
      AND C.Id_Article = idART
      AND E.Redada = 0
      
      AND C.Cantidad <> 0
      
    UNION ALL

      SELECT TR.shipment as Fecha,
             NULL as Entrada,
             C.Cantidad as Salida,
             
             
             IF(warehouse_id_out = 44, 1, warehouse_id_out) as wh,
             TR.delivered as OK,
             
             E.Referencia as Referencia,
             E.Id_Entrada as id

      FROM Compres C
      INNER JOIN Entradas E USING (Id_Entrada)
      INNER JOIN travel TR ON TR.id = E.travel_id
      WHERE TR.shipment >= datFEC
      AND C.Id_Article = idART
      
      AND E.Redada = 0
      
      AND C.Cantidad <> 0

    UNION ALL

      SELECT T.Fecha as Fecha,
             NULL as Entrada,
             M.Cantidad as Salida,
             IF(warehouse_id = 44, 1, warehouse_id) as wh,
             
             (M.OK <> 0 OR T.Etiquetasemitidas <> 0 OR T.Factura IS NOT NULL)  as OK,
             T.Factura as Referencia,
             T.Id_Ticket as id

		FROM Movimientos M
		INNER JOIN Tickets T USING (Id_Ticket)
		WHERE T.Fecha >= datFEC
			AND M.Id_Article = idART

     ) AS Historia
     
     INNER JOIN warehouse ON warehouse.id = Historia.wh
ORDER BY Fecha, Entrada DESC, OK DESC;


DROP TEMPORARY TABLE IF EXISTS hm2;
DROP TEMPORARY TABLE IF EXISTS hm3;
DROP TEMPORARY TABLE IF EXISTS hm4;
DROP TEMPORARY TABLE IF EXISTS hm5;
DROP TEMPORARY TABLE IF EXISTS hm6;
DROP TEMPORARY TABLE IF EXISTS hm7;
DROP TEMPORARY TABLE IF EXISTS hm8;
CREATE TEMPORARY TABLE hm2 SELECT * FROM hm1 WHERE wh = 19;
CREATE TEMPORARY TABLE hm3 SELECT * FROM hm1 WHERE wh = 7;
CREATE TEMPORARY TABLE hm4 SELECT * FROM hm1 WHERE wh = 1 or wh = 44;
CREATE TEMPORARY TABLE hm5 SELECT * FROM hm1 WHERE wh = 5;
CREATE TEMPORARY TABLE hm6 SELECT * FROM hm1 WHERE wh = 17;
CREATE TEMPORARY TABLE hm7 SELECT * FROM hm1 WHERE wh = 37;
CREATE TEMPORARY TABLE hm8 SELECT * FROM hm1 WHERE wh = 55;

SELECT * FROM

(

SELECT Fecha, Entrada as BOGEntrada, Salida as BOGSalida, OK as BOGOK, Referencia as BOGReferencia, id as BOGid,

       NULL AS VNHEntrada, NULL AS VNHSalida, NULL AS VNHOK, NULL AS VNHReferencia, NULL AS VNHid,
       
       NULL AS SILEntrada, NULL AS SILSalida, NULL AS SILOK, NULL AS SILReferencia, NULL AS SILid,
       
       NULL AS MADEntrada, NULL AS MADSalida, NULL AS MADOK, NULL AS MADReferencia, NULL AS MADid,
       
       NULL AS MCFEntrada, NULL AS MCFSalida, NULL AS MCFOK, NULL AS MCFReferencia, NULL AS MCFid,

	   NULL AS VILEntrada, NULL AS VILSalida, NULL AS VILOK, NULL AS VILReferencia, NULL AS VILid,
       
	   NULL AS BAREntrada, NULL AS BARSalida, NULL AS BAROK, NULL AS BARReferencia, NULL AS BARid

FROM hm2 


UNION ALL

SELECT Fecha
     , NULL, NULL, NULL, NULL, NULL
     ,Entrada, Salida, OK, Referencia, id
     , NULL, NULL, NULL, NULL, NULL
     , NULL, NULL, NULL, NULL, NULL
     , NULL, NULL, NULL, NULL, NULL
     , NULL, NULL, NULL, NULL, NULL
     , NULL, NULL, NULL, NULL, NULL
FROM hm3



UNION ALL

SELECT Fecha
     , NULL, NULL, NULL, NULL, NULL
     , NULL, NULL, NULL, NULL, NULL
     ,  Entrada, Salida, OK, Referencia, id
     , NULL, NULL, NULL, NULL, NULL
     , NULL, NULL, NULL, NULL, NULL
	 , NULL, NULL, NULL, NULL, NULL
     , NULL, NULL, NULL, NULL, NULL
FROM hm4

UNION ALL

SELECT Fecha
     , NULL, NULL, NULL, NULL, NULL
     , NULL, NULL, NULL, NULL, NULL
     , NULL, NULL, NULL, NULL, NULL
     ,  Entrada, Salida, OK, Referencia, id
     , NULL, NULL, NULL, NULL, NULL
	 , NULL, NULL, NULL, NULL, NULL
     , NULL, NULL, NULL, NULL, NULL
FROM hm5

UNION ALL

SELECT Fecha
     , NULL, NULL, NULL, NULL, NULL
     , NULL, NULL, NULL, NULL, NULL
     , NULL, NULL, NULL, NULL, NULL
     , NULL, NULL, NULL, NULL, NULL
     ,  Entrada, Salida, OK, Referencia, id
	, NULL, NULL, NULL, NULL, NULL
    , NULL, NULL, NULL, NULL, NULL
FROM hm6

UNION ALL

SELECT Fecha
	, NULL, NULL, NULL, NULL, NULL
	, NULL, NULL, NULL, NULL, NULL
	, NULL, NULL, NULL, NULL, NULL
	, NULL, NULL, NULL, NULL, NULL
	, NULL, NULL, NULL, NULL, NULL
	,  Entrada, Salida, OK, Referencia, id
    , NULL, NULL, NULL, NULL, NULL
    
     
FROM hm7

UNION ALL

SELECT Fecha
	, NULL, NULL, NULL, NULL, NULL
	, NULL, NULL, NULL, NULL, NULL
	, NULL, NULL, NULL, NULL, NULL
	, NULL, NULL, NULL, NULL, NULL
	, NULL, NULL, NULL, NULL, NULL
    , NULL, NULL, NULL, NULL, NULL
	,  Entrada, Salida, OK, Referencia, id
     
FROM hm8

) sub

ORDER BY Fecha, BOGEntrada IS NULL, VNHEntrada IS NULL, SILEntrada IS NULL, MADEntrada IS NULL, MCFEntrada IS NULL, VILEntrada IS NULL, BAREntrada 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 `ImporteSantos` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ImporteSantos`(IN dat_from date,IN dat_to date)
BEGIN

select codigotrabajador,Id_Cliente,Cliente,cast(sum(ImporteAnt) as decimal(10,0)) ImporteAnt,cast(sum(ImporteActual) as decimal(10,0)) ImporteActual
from (
	select codigotrabajador,cli.Id_Cliente Id_Cliente,Cliente,sum(amount) ImporteAnt,0 ImporteActual
	from bi.ticket ti
	inner join Clientes cli on ti.Id_Cliente=cli.Id_Cliente
	inner join vn2008.Trabajadores on cli.Id_Trabajador=Trabajadores.Id_Trabajador
	where  (date between date_add(dat_from,interval -1 year) and date_add(dat_to,interval -1 year))
    -- and cli.invoice
	group by CodigoTrabajador,ti.Id_Cliente
	
	union all 
select CodigoTrabajador,cli.Id_Cliente,Cliente,0 ImporteAnt,
     IFNULL(round(sum(cantidad * Costfixat),2),2) ImporteActual
    from Tickets ti
    inner join Movimientos m using (Id_Ticket)
    INNER JOIN vn2008.Articles a USING(Id_Article)
    INNER JOIN Tipos tp ON tp.tipo_id = a.tipo_id
	LEFT JOIN reinos r ON r.id = tp.reino_id
	INNER JOIN vn2008.Consignatarios c USING(Id_Consigna)
    inner join Clientes cli on c.Id_Cliente=cli.Id_cliente
    inner join vn2008.Trabajadores on cli.Id_Trabajador=Trabajadores.Id_Trabajador
    inner join vn2008.Permisos perm on cli.Id_Trabajador=perm.Id_Trabajador
    inner join vn2008.Grupos grup  on perm.Id_Grupo=grup.Id
    where ti.Fecha between dat_from and DAYEND(dat_to)
    -- and cli.invoice
    AND r.display <> 0
    and (grup.Id in (6) or cli.Id_Trabajador in (20))
    group by CodigoTrabajador,c.Id_Cliente,year(Fecha) 
)sub1
group by CodigoTrabajador,Id_Cliente
having (ImporteAnt<>0 or ImporteActual<>0)
order by CodigoTrabajador,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 `InsertarEspionaje` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `InsertarEspionaje`(intIdTrabajador INT(11),intIdEquipo int)
BEGIN

DECLARE intNReg TINYINT DEFAULT 0;

SELECT Count(*) AS NReg
INTO intNReg
FROM Espionajes
WHERE Fecha=Current_date
AND Id_Trabajador=intIdTrabajador;

IF (intNReg=0) THEN
    INSERT INTO Espionajes (Id_Trabajador,Fecha,HoraEntrada,Id_Equipo)
    VALUES (intIdTrabajador,CURRENT_DATE,CURRENT_TIME,intIdEquipo);
ELSE 
    UPDATE Espionajes
    SET HoraSalida=CURRENT_TIME
    WHERE Id_Trabajador=intIdTrabajador
    AND Fecha=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 `insert_producer_plantpassport` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `insert_producer_plantpassport`(vBuyFk INT)
BEGIN
	DECLARE last_insert INTEGER;
    
	INSERT IGNORE INTO producer(`name`)
		SELECT es.company_name
			FROM Compres c
				JOIN buy_edi be ON be.id = c.buy_edi_id
				JOIN edi.supplier es ON es.supplier_id = be.pro
			WHERE c.Id_Compra = vBuyFk;
    
   --  SELECT LAST_INSERT_ID() INTO last_insert;
  
	/*
    IF last_insert > 0 THEN
		UPDATE Articles a JOIN Compres c 
			ON a.Id_Article = c.Id_Article SET a.producer_id = last_insert WHERE c.Id_Compra = vBuyFk;
	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 `inventario_margen` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `inventario_margen`(IN d_START DATETIME,  IN d_END DATETIME, IN i_tipo INT, IN i_filtro INT, IN i_wh INT)
BEGIN

    DECLARE d_INV DATETIME;
	DECLARE bolREVERSE BOOLEAN DEFAULT 0;
    DECLARE d_FEC2 DATETIME;
    DECLARE d_FEC DATETIME;
    DECLARE i_SECTOR INT DEFAULT 0;
    DECLARE strFILTRO VARCHAR(255) DEFAULT 'TRUE';
    DECLARE dblPORTE_m3 DOUBLE DEFAULT 45;
    DECLARE intCASE INTEGER;
    DECLARE ID_CLIENTE_COMPLEMENTOS INT DEFAULT 1927;
    DECLARE ID_REINO_OTROS INT DEFAULT 6;
    DECLARE ID_PROVEEDOR_INVENTARIO INT DEFAULT 4;
    DECLARE ID_TRABAJADOR_MARIBEL INT DEFAULT 133;

    IF i_filtro THEN
        SELECT `sql` INTO strFILTRO FROM filtros WHERE id = i_filtro;
    END IF;

   

-- PREVIO:  Crear una tabla para filtrar los articulos que interesan

    DROP TEMPORARY TABLE IF EXISTS article_selection;
	
	SET strFILTRO = REPLACE(strFILTRO, 'Id_Article','A.Id_Article');

    CALL util.exec (sql_printf(
        'CREATE TEMPORARY TABLE vn2008.article_selection 
		ENGINE = MEMORY
        SELECT A.Id_Article  
                FROM vn2008.Articles A
                LEFT JOIN vn2008.Tipos t USING(tipo_id)
				LEFT JOIN vn2008.Trabajadores TR ON TR.Id_Trabajador = t.Id_Trabajador
                LEFT JOIN vn2008.Tintas tn ON A.color = tn.Id_Tinta
                LEFT JOIN vn2008.Origen o ON o.id = A.id_origen
                WHERE  %s AND %s  AND reino_id != %v'
        ,IF(i_tipo, CONCAT('tipo_id = ', i_tipo), 'TRUE')
        ,strFILTRO
        ,ID_REINO_OTROS
    ));            


ALTER TABLE article_selection ADD PRIMARY KEY(Id_Article);


-- PRIMER PASO: Cálculo del inventario inicial, valorado
	
-- Averiguamos la fecha del inventario inmediatemente anterior a la fecha de inicio

    SELECT landing INTO d_INV
    FROM travel TR
    INNER JOIN Entradas E ON E.travel_id = TR.id
    WHERE landing <= d_START
    AND E.Id_Proveedor = ID_PROVEEDOR_INVENTARIO
	AND i_wh IN (0,TR.warehouse_id)
    ORDER BY landing DESC
    LIMIT 1;

	IF d_INV is null THEN
    
		SELECT landing INTO d_INV
		FROM travel TR
		INNER JOIN Entradas E ON E.travel_id = TR.id
		WHERE landing > d_START
		AND E.Id_Proveedor = ID_PROVEEDOR_INVENTARIO
		AND i_wh IN (0,TR.warehouse_id)
		ORDER BY landing ASC
		LIMIT 1;

	END IF;


-- Ubicamos la fecha de inventario segun su posición relativa a la de inicio y a la de fin

IF d_INV <= d_START THEN

		SET intCASE = 1;  

ELSE

		IF d_INV > d_END THEN

			SET intCASE = 3;

		ELSE

			SET intCASE = 2;

		END IF;

END IF;

DROP TEMPORARY TABLE IF EXISTS inv;

-- Preparamos la tabla temporal que va a almacenar el valor y cantidad de productos

CREATE TEMPORARY TABLE inv 
	(w_id SMALLINT,
	 Id_Article BIGINT,
	 Unidades INT,	
     Valor DOUBLE,
     Sector INT DEFAULT 0 ) ENGINE = MEMORY;

  
ALTER TABLE inv ADD PRIMARY KEY USING HASH (w_id, Id_Article, Sector);

/************************** SECTOR INICIAL: 0 *****************************/

CASE intCASE

			WHEN 1 THEN

						SET d_FEC = TIMESTAMP(d_INV,'00:00:00');
						SET d_FEC2 = TIMESTAMP(TIMESTAMPADD(DAY,-1,d_START) ,'23:59:59');
						SET bolREVERSE = FALSE;
						
			ELSE

						SET d_FEC = TIMESTAMP(d_START,'00:00:00');
						SET d_FEC2 = TIMESTAMP(TIMESTAMPADD(DAY,-1,d_INV) ,'23:59:59');
						SET bolREVERSE = TRUE;


END CASE;


-- Inicializamos el inventario

	
	INSERT INTO inv(w_id, Id_Article, Unidades,Valor)
	SELECT TR.warehouse_id, C.Id_Article, sum(C.Cantidad), ifnull(C.Costefijo,0) + IFNULL(C.Embalajefijo,0) + IFNULL(C.Portefijo,0) + IFNULL(C.Comisionfija,0)
	FROM Compres C
	INNER JOIN Articles A USING(Id_Article)
	INNER JOIN Tipos TP USING(tipo_id)
	INNER JOIN Entradas E USING (Id_Entrada)
	INNER JOIN travel TR ON TR.id = E.travel_id
	INNER JOIN warehouse w ON w.id = warehouse_id
	JOIN article_selection USING(Id_Article)
	WHERE landing = d_INV
    AND w.comisionantes
	AND i_wh IN (0,TR.warehouse_id)
	AND E.Id_Proveedor = ID_PROVEEDOR_INVENTARIO
	AND reino_id != ID_REINO_OTROS
	AND TR.warehouse_id != TR.warehouse_id_out
    GROUP BY TR.warehouse_id, C.Id_Article;

-- Se insertan las compras que llegan entre la fecha del inventario y la fecha inicial

	INSERT INTO inv(w_id, Id_Article, Unidades, Valor)
	SELECT TR.warehouse_id, C.Id_Article, C.Cantidad * IF(bolREVERSE,-1,1),  ifnull(C.Costefijo,0) + IFNULL(C.Embalajefijo,0) + IFNULL(C.Portefijo,0) + IFNULL(C.Comisionfija,0)
	FROM Compres C
	INNER JOIN Articles A USING(Id_Article)
	INNER JOIN Tipos TP USING(tipo_id)
	INNER JOIN Entradas E USING (Id_Entrada)
	INNER JOIN travel TR ON TR.id = E.travel_id
	INNER JOIN warehouse w ON w.id = warehouse_id
    JOIN article_selection USING(Id_Article)
	WHERE landing BETWEEN d_FEC AND d_FEC2
	AND i_wh IN (0,TR.warehouse_id)
    AND w.comisionantes
	AND NOT redada
	AND reino_id != ID_REINO_OTROS
    AND  E.Id_Proveedor != ID_PROVEEDOR_INVENTARIO 
	AND TR.warehouse_id != TR.warehouse_id_out
    ORDER BY landing DESC
	ON DUPLICATE KEY UPDATE inv.Unidades = inv.Unidades + (C.Cantidad * IF(bolREVERSE,-1,1))
    , Valor = IF(Costefijo > 0,ifnull(C.Costefijo,0) + IFNULL(C.Embalajefijo,0) + IFNULL(C.Portefijo,0) + IFNULL(C.Comisionfija,0),Valor);

-- Se sacan las que salen

	INSERT INTO inv(w_id, Id_Article, Unidades)
	SELECT TR.warehouse_id_out, C.Id_Article, C.Cantidad * IF(bolREVERSE,1,-1)
	FROM Compres C
	INNER JOIN Articles A USING(Id_Article)
	INNER JOIN Tipos TP USING(tipo_id)
	INNER JOIN Entradas E USING (Id_Entrada)
	INNER JOIN travel TR ON TR.id = E.travel_id
	INNER JOIN warehouse w ON w.id = warehouse_id_out
    JOIN article_selection USING(Id_Article)
	WHERE shipment BETWEEN d_FEC AND d_FEC2
	AND i_wh IN (0,TR.warehouse_id_out)
    AND w.comisionantes
	AND NOT redada
	AND reino_id != ID_REINO_OTROS
	AND E.Id_Proveedor != ID_PROVEEDOR_INVENTARIO
	AND TR.warehouse_id != TR.warehouse_id_out
	ON DUPLICATE KEY UPDATE inv.Unidades = inv.Unidades + (C.Cantidad * IF(bolREVERSE,1,-1));

-- Ahora las ventas
				  
	INSERT INTO inv(w_id, Id_Article, Unidades)
	SELECT w.id, M.Id_Article, M.Cantidad  * IF(bolREVERSE,1,-1)
	FROM Movimientos M
	INNER JOIN Tickets T USING (Id_Ticket)
	INNER JOIN Articles A USING(Id_Article)
    INNER JOIN Tipos TP USING(tipo_id)
	INNER JOIN warehouse w ON w.id = T.warehouse_id
    INNER JOIN article_selection USING(Id_Article)
	WHERE T.Fecha BETWEEN d_FEC AND d_FEC2
	AND i_wh IN (0,T.warehouse_id)
    AND w.comisionantes
	AND reino_id != ID_REINO_OTROS
	ON DUPLICATE KEY UPDATE inv.Unidades = inv.Unidades + (M.Cantidad * IF(bolREVERSE,1,-1));


UPDATE inv SET Valor = inv.Unidades * Valor;


/************************** SECTOR ENTRADAS: 1 *****************************/

SET i_SECTOR = 1;


						SET d_FEC = TIMESTAMP(d_START,'00:00:00');
						SET d_FEC2 = TIMESTAMP(d_END ,'23:59:59');
				


-- Ahora vamos a incrementar en unidades y valor el producto recibido en el rango de fechas del procedimiento

    INSERT INTO inv(Sector, w_id, Id_Article, Unidades, Valor)
	SELECT i_SECTOR, TR.warehouse_id, C.Id_Article, sum(C.Cantidad )
                                                            , sum(C.Cantidad * (nz(Costefijo)+nz(Embalajefijo)+nz(Portefijo)+nz(Comisionfija)) )
	FROM Compres C
	INNER JOIN Articles A USING(Id_Article)
    INNER JOIN Tipos TP USING(tipo_id)
	INNER JOIN Entradas E USING (Id_Entrada)
	INNER JOIN travel TR ON TR.id = E.travel_id
	INNER JOIN warehouse w ON w.id = warehouse_id
    JOIN article_selection USING(Id_Article)
	WHERE landing BETWEEN d_FEC AND d_FEC2
	AND i_wh IN (0,TR.warehouse_id)
    AND w.comisionantes
	AND NOT redada
	AND E.Id_Proveedor != ID_PROVEEDOR_INVENTARIO
	AND reino_id != ID_REINO_OTROS
	AND TR.warehouse_id != TR.warehouse_id_out
	GROUP BY TR.warehouse_id, C.Id_Article;




/************************** SECTOR SALIDAS: 2 *****************************/

SET i_SECTOR = 2;

-- Ahora vamos a restar en unidades y valor el producto que sale de los almacenes en el rango de fechas del procedimiento

    INSERT INTO inv(Sector, w_id, Id_Article, Unidades, Valor)
	SELECT i_SECTOR, TR.warehouse_id_out, C.Id_Article, sum( -1 * C.Cantidad )
                                                                                       , sum( -1 * C.Cantidad * (nz(Costefijo) + nz(Embalajefijo) ))
	FROM Compres C
	INNER JOIN Articles A USING(Id_Article)
    INNER JOIN Tipos TP USING(tipo_id)
	INNER JOIN Entradas E USING (Id_Entrada)
	INNER JOIN travel TR ON TR.id = E.travel_id
	INNER JOIN warehouse w ON w.id = warehouse_id_out
    JOIN article_selection USING(Id_Article)
	WHERE shipment BETWEEN d_FEC AND d_FEC2
	AND i_wh IN (0,TR.warehouse_id_out)
    AND w.comisionantes
	AND NOT redada
    AND E.Id_Proveedor != ID_PROVEEDOR_INVENTARIO
	AND reino_id != ID_REINO_OTROS
	AND TR.warehouse_id != TR.warehouse_id_out
	GROUP BY TR.warehouse_id_out, C.Id_Article ;



/********************  SECTOR VENTAS: 3 **************************************/

SET i_SECTOR = 3;


DROP TEMPORARY TABLE IF EXISTS Cub;
	CREATE TEMPORARY TABLE Cub
	SELECT * FROM (SELECT * FROM bi.last_Id_Cubo order by Id_Compra desc) sub group by Id_Article, warehouse_id;

	ALTER TABLE Cub ADD PRIMARY KEY USING HASH (Id_Article, warehouse_id);




IF d_START >= '2015-10-01' THEN

	INSERT INTO inv(Sector, w_id, Id_Article, Unidades, Valor)
		
		
	    SELECT i_SECTOR
             , w.id
             , M.Id_Article
             , sum(-1 * M.Cantidad  ) as Unidades
             , sum(-1 * IF(T.Id_Cliente IN (200,400),0,1) * IFNULL(bsv.importe,0)) as Valor
		FROM Movimientos M
        LEFT JOIN bs.ventas bsv on bsv.Id_Movimiento = M.Id_Movimiento
		INNER JOIN Tickets T USING (Id_Ticket)
		INNER JOIN Articles A ON A.Id_Article = M.Id_Article
		INNER JOIN Tipos TP on TP.tipo_id = A.tipo_id
		INNER JOIN warehouse w ON w.id = T.warehouse_id
		JOIN article_selection `AS` ON `AS`.Id_Article = M.Id_Article
		WHERE T.Fecha BETWEEN d_FEC AND d_FEC2
		AND i_wh IN (0,T.warehouse_id)
		AND w.comisionantes
		AND reino_id != ID_REINO_OTROS
        /*
        AND (	
			T.Id_Cliente != ID_CLIENTE_COMPLEMENTOS 
			OR 
			TP.Id_Trabajador != ID_TRABAJADOR_MARIBEL
			)
		*/
		GROUP BY T.warehouse_id, Id_Article;
        
        
	

ELSE

	
					  
		INSERT INTO inv(Sector, w_id, Id_Article, Unidades, Valor)
		
		
	 SELECT i_SECTOR, w.id, M.Id_Article, sum(-1 * M.Cantidad  )
																 ,

						sum( -1 
							 * M.Cantidad  
							 * IF(CS.Id_Cliente IN (200,400),0,1)  
							 * IF(
								  T.Fecha >= '2015-10-01'
								  , M.CostFixat
								  ,   (
									   ( M.Preu 
										* (100 - M.Descuento)
										/ 100
									   )     
									   -    IF(C.Descuento = 1 and T.Bultos > 0 and Fecha > '2013-07-01',  
											  IFNULL(   dblPORTE_m3 * (cm3_2(CB.Id_Cubo, CB.Id_Article) / 1000000) / CB.Packing ,0 )          
											  ,0)       
									  ) 
								 )

							) as Preu

		FROM Movimientos M
		INNER JOIN Tickets T USING (Id_Ticket)
		LEFT JOIN Cub CB ON CB.Id_Article = M.Id_Article AND T.warehouse_id = CB.warehouse_id
		INNER JOIN Consignatarios CS USING(Id_Consigna)
		INNER JOIN Clientes C ON C.Id_Cliente = CS.Id_Cliente
		INNER JOIN Articles A ON A.Id_Article = M.Id_Article
		INNER JOIN Tipos TP USING(tipo_id)
		INNER JOIN warehouse w ON w.id = T.warehouse_id
		JOIN article_selection `AS` ON `AS`.Id_Article = M.Id_Article
		WHERE T.Fecha BETWEEN d_FEC AND d_FEC2
		AND i_wh IN (0,T.warehouse_id)
		AND w.comisionantes
		AND reino_id != ID_REINO_OTROS
         /*
        AND (	
			T.Id_Cliente != ID_CLIENTE_COMPLEMENTOS 
			OR 
			TP.Id_Trabajador != ID_TRABAJADOR_MARIBEL
			)
		*/
		GROUP BY T.warehouse_id, Id_Article;


END IF;

	-- Ventas del año anterior

	   DROP TEMPORARY TABLE IF EXISTS Ventas_Lastyear;

	   CREATE TEMPORARY TABLE Ventas_Lastyear
	   SELECT CodigoTrabajador, TP.Id_Tipo, 
							
							sum(M.Cantidad  
							 * IF(CS.Id_Cliente IN (200,400),0,1)  
							 * IF(
								   T.Fecha >= '2015-10-01'
								  , M.CostFixat
								  ,   (
										  ( M.Preu 
											* (100 - M.Descuento)
											/ 100
									  )     
										-    IF(C.Descuento = 1 and T.Bultos > 0 and Fecha > '2013-07-01',  
											  IFNULL(   dblPORTE_m3 * (cm3_2(CB.Id_Cubo, CB.Id_Article) / 1000000) / CB.Packing ,0 )          
											  ,0)       
									) 
								 )

							) as Importe
		FROM Movimientos M
		INNER JOIN Tickets T USING (Id_Ticket)
		LEFT JOIN Cub CB ON CB.Id_Article = M.Id_Article AND T.warehouse_id = CB.warehouse_id
		INNER JOIN Consignatarios CS USING(Id_Consigna)
		INNER JOIN Clientes C ON C.Id_Cliente = CS.Id_Cliente
		INNER JOIN Articles A ON A.Id_Article = M.Id_Article
		INNER JOIN Tipos TP USING(tipo_id)
		INNER JOIN Trabajadores TR ON TP.Id_Trabajador = TR.Id_Trabajador
		INNER JOIN warehouse w ON w.id = T.warehouse_id
		JOIN article_selection `AS` ON `AS`.Id_Article = M.Id_Article
		WHERE T.Fecha BETWEEN TIMESTAMPADD(YEAR,-1,d_FEC) AND TIMESTAMPADD(YEAR,-1,d_FEC2)
		AND i_wh IN (0,T.warehouse_id)
		AND w.comisionantes
		AND reino_id != ID_REINO_OTROS
          /*
        AND (	
			T.Id_Cliente != ID_CLIENTE_COMPLEMENTOS 
			OR 
			TP.Id_Trabajador != ID_TRABAJADOR_MARIBEL
			)
		*/
		GROUP BY CodigoTrabajador, Id_Tipo;


        



/********************  SECTOR FINAL: 4 **************************************/

SET i_SECTOR = 4;


CASE intCASE

							
			WHEN  3 THEN

						SET d_FEC = TIMESTAMP(TIMESTAMPADD(DAY,1,d_END),'00:00:00');
						SET d_FEC2 = TIMESTAMP(TIMESTAMPADD(DAY,-1,d_INV),'23:59:59');
						SET bolREVERSE = TRUE;
						
			ELSE

						SET d_FEC = TIMESTAMP(d_INV,'00:00:00');
						SET d_FEC2 = TIMESTAMP(d_END ,'23:59:59');
						SET bolREVERSE = FALSE;


END CASE;

-- Ahora repetimos el proceso de inventario, para contabilizar el stock remanente.

-- Inicializamos el inventario

	
	INSERT INTO inv(Sector, w_id, Id_Article, Unidades, Valor)
	SELECT i_SECTOR, TR.warehouse_id, C.Id_Article, sum(C.Cantidad),  nz(Costefijo) + nz(Portefijo) + nz(Embalajefijo) + nz(Comisionfija)
	FROM Compres C
	INNER JOIN Articles A USING(Id_Article)
	INNER JOIN Tipos TP USING(tipo_id)
	INNER JOIN Entradas E USING (Id_Entrada)
	INNER JOIN travel TR ON TR.id = E.travel_id
	INNER JOIN warehouse w ON w.id = warehouse_id
	JOIN article_selection USING(Id_Article)
	WHERE landing = d_INV
	AND i_wh IN (0,TR.warehouse_id)
	AND E.Id_Proveedor = ID_PROVEEDOR_INVENTARIO
	AND reino_id != ID_REINO_OTROS
	AND w.comisionantes
	AND TR.warehouse_id != TR.warehouse_id_out
    GROUP BY TR.warehouse_id, C.Id_Article;






-- Se insertan las compras que llegan entre la fecha del inventario y la fecha inicial

	INSERT INTO inv(Sector, w_id, Id_Article, Unidades, Valor)
	SELECT i_SECTOR, TR.warehouse_id, C.Id_Article, C.Cantidad * IF(bolREVERSE,-1,1),  nz(Costefijo) + nz(Portefijo) + nz(Embalajefijo) + nz(Comisionfija)
	FROM Compres C
	INNER JOIN Articles A USING(Id_Article)
    INNER JOIN Tipos TP USING(tipo_id)
	INNER JOIN Entradas E USING (Id_Entrada)
	INNER JOIN travel TR ON TR.id = E.travel_id
	INNER JOIN warehouse w ON w.id = warehouse_id
    JOIN article_selection USING(Id_Article)
	WHERE landing BETWEEN d_FEC AND d_FEC2
	AND i_wh IN (0,TR.warehouse_id)
	AND NOT redada
	AND w.comisionantes
	AND E.Id_Proveedor != 4
	AND reino_id != ID_REINO_OTROS
	AND TR.warehouse_id != TR.warehouse_id_out
	ORDER BY landing DESC
	ON DUPLICATE KEY UPDATE inv.Unidades = inv.Unidades + (C.Cantidad * IF(bolREVERSE,-1,1))
    , Valor = IF( nz(Costefijo) > 0,nz(Costefijo) + nz(Portefijo) + nz(Embalajefijo) + nz(Comisionfija),Valor);

-- Se sacan las que salen

	INSERT INTO inv(Sector, w_id, Id_Article, Unidades)
	SELECT i_SECTOR, TR.warehouse_id_out, C.Id_Article, C.Cantidad * IF(bolREVERSE,1,-1)
	FROM Compres C
	INNER JOIN Articles A USING(Id_Article)
    INNER JOIN Tipos TP USING(tipo_id)
	INNER JOIN Entradas E USING (Id_Entrada)
	INNER JOIN travel TR ON TR.id = E.travel_id
	INNER JOIN warehouse w ON w.id = warehouse_id_out
    JOIN article_selection USING(Id_Article)
	WHERE shipment BETWEEN d_FEC AND d_FEC2
	AND i_wh IN (0,TR.warehouse_id_out)
	AND NOT redada
	AND w.comisionantes
	AND E.Id_Proveedor != 4
	AND reino_id != ID_REINO_OTROS
    
	ON DUPLICATE KEY UPDATE inv.Unidades = inv.Unidades + (C.Cantidad * IF(bolREVERSE,1,-1));


-- Ahora las ventas
	
	INSERT INTO inv(Sector, w_id, Id_Article, Unidades)
	SELECT i_SECTOR, w.id, M.Id_Article, M.Cantidad  * IF(bolREVERSE,1,-1)
	FROM Movimientos M
	INNER JOIN Tickets T USING (Id_Ticket)
	INNER JOIN Articles A USING(Id_Article)
    INNER JOIN Tipos TP USING(tipo_id)
	INNER JOIN warehouse w ON w.id = T.warehouse_id
    JOIN article_selection USING(Id_Article)
	WHERE T.Fecha BETWEEN d_FEC AND d_FEC2
	AND i_wh IN (0,T.warehouse_id)
	AND w.comisionantes
	AND reino_id != ID_REINO_OTROS
    ON DUPLICATE KEY UPDATE inv.Unidades = inv.Unidades + (M.Cantidad * IF(bolREVERSE,1,-1));

-- Valoramos el inventario final


UPDATE inv SET Valor = inv.Unidades * Valor WHERE Sector =4;


-- Resultado

DROP TEMPORARY TABLE IF EXISTS Margen_Desglose;

CREATE TEMPORARY TABLE Margen_Desglose

SELECT CASE Sector 
				WHEN 0 THEN 'Inventario Inicial' 
				WHEN 1 THEN 'Entradas' 
				WHEN 2 THEN 'Salidas' 
				WHEN 3 THEN 'Ventas' 
				WHEN 4 THEN 'Inventario Final' END  AS Seccion
            , w.name as Almacen, r.reino as Reino,  Id_Article, Article, Medida, Unidades,Id_Tipo, round(Valor,0) as Valor , round(Valor/Unidades,3) as Precio, Sector
FROM inv 
JOIN Articles USING(Id_Article)
JOIN Tipos TP USING(tipo_id)
JOIN warehouse w ON w.id = w_id
JOIN reinos r ON r.id = TP.reino_id
WHERE Unidades != 0
ORDER BY Almacen, Sector
;





DROP TEMPORARY TABLE IF EXISTS Margen_Bruto;

CREATE TEMPORARY TABLE Margen_Bruto

SELECT Unidades_Vendidas, Coste, Venta,1 - round(coste / venta,2) as Margen
FROM (
SELECT w.name as Almacen, r.reino as Reino,  Id_Article, Article, Medida, sum(IF(Sector = 3, -1,0) * Unidades) as Unidades_Vendidas
               , @coste:= round(sum(  IF(Sector != 3,  Valor * IF(Sector = 4,-1,1), 0)    ) ,0) as Coste
               , @venta:= round(sum(  IF(Sector = 3,  - Valor, 0 )   ),0) as Venta
FROM inv 
JOIN Articles USING(Id_Article)
JOIN Tipos TP USING(tipo_id)
JOIN warehouse w ON w.id = w_id
JOIN reinos r ON r.id = TP.reino_id
WHERE Unidades != 0 

) sub;



END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `inventario_multiple` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `inventario_multiple`(IN wh TINYINT(2), IN date_ticket DATETIME)
BEGIN
-- DEPRECATED USAR cache.available_refresh
	DECLARE date_order DATETIME;
	DECLARE date_end DATETIME DEFAULT CURDATE();
	DECLARE date_aux DATE;
	DECLARE date_start DATETIME;
	DECLARE date_yesterday DATETIME;
	DECLARE date_tomorrow DATETIME;
	DECLARE strWH VARCHAR(2);

	SET strWH = IF(wh,wh,'%');
	SET date_end = TIMESTAMPADD(DAY, 7, date_ticket);

	CALL article ();

	ALTER TABLE `article_inventory`
		ADD `available`	FLOAT(7,2) NOT NULL,
		ADD `inventory`	FLOAT(7,2) NOT NULL,
		ADD `visible`	FLOAT(7,2) NOT NULL;

	-- JGF 2015-02-19 Falla, el valor @camp es cero y falla Campanya
	/* 
	SELECT
		IF(@camp := DATEDIFF(campaign, date_ticket) BETWEEN 0 AND campaign_life,
			TIMESTAMPADD(DAY, -campaign_life, campaign),
			FechaInventario),
		IF(@camp BETWEEN 0 AND campaign_life,
			TIMESTAMP(campaign, '23:59:59'),
			TIMESTAMP(TIMESTAMPADD(DAY, 15, date_ticket),'23:59:59'))
	INTO date_start, date_end
	FROM tblContadores;*/

	SELECT
		FechaInventario,TIMESTAMP(TIMESTAMPADD(DAY, 15, date_ticket),'23:59:59')
	INTO date_start, date_end
	FROM tblContadores;


	SET date_order = TIMESTAMP(DATE(date_ticket), '00:00:00');
	SET date_tomorrow = TIMESTAMPADD(DAY, 1, date_order);

-- Inventario hasta dia antes del ticket
	CALL item_stock(wh,date_ticket,NULL);

	INSERT INTO article_inventory (article_id,inventory,visible,available)
	SELECT item_id, stock, visible, available
		FROM tmp_item;
        
	DROP TEMPORARY TABLE IF EXISTS tmp_item;
		
-- Inventario ventas durante el dia del ticket
	INSERT INTO article_inventory(article_id,visible)

	SELECT Id_Article, SUM(amount) AS Subtotal

		FROM (

			SELECT Id_Article, -Cantidad AS amount

				FROM Movimientos M INNER JOIN Tickets T USING (Id_Ticket)

					WHERE Fecha >= date_order

					AND Fecha < date_tomorrow

					AND (M.OK != FALSE

					OR T.Etiquetasemitidas != FALSE

					OR T.Factura IS NOT NULL)

					AND T.warehouse_id = wh

			UNION ALL

			SELECT Id_Article, Cantidad

				FROM Compres C INNER JOIN Entradas E USING (Id_Entrada)

				LEFT JOIN travel TR ON E.travel_id = TR.id

					WHERE TR.landing >= date_order

					AND TR.landing < date_tomorrow

					AND TR.received != FALSE

					AND TR.warehouse_id = wh

					AND E.Inventario = FALSE
					
			AND E.Redada = FALSE

			UNION ALL

			SELECT Id_Article, -Cantidad

				FROM Compres C INNER JOIN Entradas E USING (Id_Entrada)

				LEFT JOIN travel TR ON E.travel_id = TR.id

					WHERE TR.shipment >= date_order

					AND TR.shipment < date_tomorrow

					AND TR.delivered != FALSE

					AND TR.warehouse_id_out = wh

					AND E.Inventario = FALSE
					
			AND E.Redada = FALSE

		) AS T1

		GROUP BY Id_Article

			ON DUPLICATE KEY UPDATE

			visible = inventory + VALUES(visible); 


	-- Disponible en el futuro
	CALL item_travel (wh, date_order);

	SET date_aux = DATE(date_order);

	INSERT INTO article_inventory(article_id,available)

	SELECT Tic3.Id_Article, minacum(dat, amount, date_aux) AS sd

		FROM (

			SELECT Tic2.Id_Article, DATE(Fecha) AS dat, SUM(amount) AS amount

				FROM (

					SELECT Id_Article, Fecha, -Cantidad AS amount

						FROM Movimientos M

						INNER JOIN Tickets T USING (Id_Ticket)

							WHERE Fecha BETWEEN date_order AND date_end

							AND T.warehouse_id = wh

					UNION ALL

					SELECT Id_Article, TR.landing, Cantidad

						FROM Compres C INNER JOIN Entradas E USING (Id_Entrada)

						LEFT JOIN travel TR ON E.travel_id = TR.id

							WHERE TR.landing BETWEEN date_order AND date_end

							AND TR.warehouse_id = wh

							AND E.Inventario = FALSE
							
				AND E.Redada = FALSE

					UNION ALL

					SELECT Id_Article, TR.shipment, -Cantidad

						FROM Compres C INNER JOIN Entradas E USING (Id_Entrada)

						LEFT JOIN travel TR ON E.travel_id = TR.id

							WHERE TR.shipment BETWEEN date_order AND date_end

							AND TR.warehouse_id_out = wh

							AND E.Inventario = FALSE
							
				AND E.Redada = FALSE

				) AS Tic2

				GROUP BY Tic2.Id_Article, dat

		) Tic3

		LEFT JOIN Articles A ON Tic3.Id_Article = A.Id_Article

		LEFT JOIN Origen O ON O.id = A.id_origen

		LEFT JOIN item_travel t ON t.wh = O.warehouse_id

			WHERE dat < IFNULL(t.landing, date_end)

			GROUP BY Tic3.Id_Article

				ON DUPLICATE KEY UPDATE

					available = IFNULL(inventory,0) + VALUES(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 `inventario_multiple_2` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `inventario_multiple_2`(
	date_ticket DATETIME
	,wh TINYINT
	,days_max TINYINT
)
proc: BEGIN
	DECLARE date_end DATETIME DEFAULT CURDATE();
	DECLARE date_start DATETIME;
	DECLARE date_top DATETIME;
	DECLARE date_tomorrow DATETIME;

	SET date_ticket = DATE(date_ticket); -- PAK

	ALTER TABLE `article_inventory`
		ADD `avalaible` INT NOT NULL,
		ADD `sd` INT NOT NULL,
		ADD `rest` INT NOT NULL,
		ADD `expected` INT NOT NULL,
		ADD `inventory` INT NOT NULL,
		ADD `visible` INT NOT NULL,
		ADD `life` TINYINT NOT NULL DEFAULT '0';

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

	SELECT FechaInventario INTO date_start FROM tblContadores;

	SET date_end = TIMESTAMP(TIMESTAMPADD(DAY, IF(days_max >= 0, days_max,15), date_ticket),'23:59:59');
	SET date_tomorrow = TIMESTAMPADD(DAY, 1,date_ticket);
	SET date_top = TIMESTAMPADD(DAY, 1,date_end);

	-- Calculo del inventario dia D a las 24:00 zulu

	UPDATE article_inventory AI INNER JOIN

	(

	SELECT Id_Article, SUM(amount) as Subtotal FROM

		(

		SELECT Id_Article, -Cantidad AS amount

		FROM Movimientos M 		
		JOIN Tickets T USING (Id_Ticket)
		JOIN warehouse W ON W.id = T.warehouse_id  
		WHERE DATE(Fecha) BETWEEN date_start AND date_ticket
		AND IF(wh = 0, W.is_comparative, wh =T.warehouse_id)
        
		UNION ALL

		SELECT Id_Article,  Cantidad
		FROM Compres C INNER JOIN Entradas E USING (Id_Entrada)
		LEFT JOIN travel TR ON E.travel_id = TR.id
		JOIN warehouse W ON W.id = TR.warehouse_id  -- PAK
		WHERE TR.landing BETWEEN date_start AND date_ticket
		AND IF(wh = 0, W.is_comparative, wh =TR.warehouse_id)
		AND E.Inventario = 0
		AND E.Redada = 0

		UNION ALL

		SELECT Id_Article,  -Cantidad
		FROM Compres C 
		JOIN Entradas E USING (Id_Entrada)
		JOIN travel TR ON E.travel_id = TR.id
		JOIN warehouse W ON W.id = TR.warehouse_id_out  
		WHERE TR.shipment BETWEEN date_start AND date_ticket
		AND IF(wh = 0, W.is_comparative, wh =TR.warehouse_id_out)
		AND E.Inventario = 0
		AND E.Redada = 0
        
		) AS T1

	  GROUP BY Id_Article

		) AS T2

	  ON AI.article_id = T2.Id_Article

	 SET AI.inventory = T2.Subtotal,

		 AI.visible = T2.Subtotal,

		 AI.avalaible = T2.Subtotal,

		 AI.sd = T2.Subtotal;

	-- Calculo del visible

	UPDATE article_inventory AI INNER JOIN
	(
	  SELECT Id_Article, SUM(amount) as Subtotal FROM
		(
		SELECT Id_Article, Cantidad AS amount
		FROM Movimientos M 
		JOIN Tickets T USING (Id_Ticket)
		JOIN warehouse W ON W.id = T.warehouse_id  -- PAK
		WHERE Fecha >= date_ticket AND Fecha < date_tomorrow -- PAK
		AND (M.OK = 0 AND T.Etiquetasemitidas = 0 AND T.Factura IS NULL)
		AND IF(wh = 0, W.is_comparative, wh =T.warehouse_id)
        
		UNION ALL
        
		SELECT Id_Article,  -Cantidad
		FROM Compres C
		JOIN Entradas E USING (Id_Entrada)
		JOIN travel TR ON E.travel_id = TR.id
		JOIN warehouse W ON W.id = TR.warehouse_id  -- PAK
		WHERE TR.landing = date_ticket
    	AND TR.received = 0
		AND E.Inventario = 0
		AND E.Redada = 0
		AND IF(wh = 0, W.is_comparative, wh =TR.warehouse_id)
        
		UNION ALL

		SELECT Id_Article,  Cantidad
		FROM Compres C INNER JOIN Entradas E USING (Id_Entrada)
		LEFT JOIN travel TR ON E.travel_id = TR.id
		INNER JOIN warehouse W ON W.id = TR.warehouse_id_out
		WHERE TR.shipment = date_ticket
		AND TR.delivered = 0
		AND E.Inventario = 0
		AND E.Redada = 0
		AND IF(wh = 0, W.is_comparative, wh =TR.warehouse_id_out)
        
		) AS T1

		  GROUP BY Id_Article

	  ) AS T2

	  ON AI.article_id = T2.Id_Article

	 SET AI.visible = AI.visible + T2.Subtotal;

	-- Calculo del disponible

	CALL item_travel (wh, date_ticket);

	UPDATE article_inventory AI INNER JOIN
		 (
				   SELECT Tic3.Id_Article, SUM(amount) AS sd, minacum(Fecha, amount, date_ticket) as smd FROM
				   (

				   SELECT Tic2.Id_Article, Fecha, SUM(amount) AS amount FROM
					 (
						  SELECT Id_Article, DATE(Fecha) as Fecha, -Cantidad AS amount
						  FROM Movimientos M 
						  JOIN Tickets T USING (Id_Ticket)
						  JOIN warehouse W ON W.id = T.warehouse_id  
						  WHERE Fecha BETWEEN date_tomorrow AND date_end
						  AND IF(wh = 0, W.is_comparative, wh =T.warehouse_id)
						  
                          UNION ALL
                          
                          SELECT Id_Article, landing as Fecha, Cantidad
						  FROM Compres C 
						  JOIN Entradas E USING (Id_Entrada)
						  JOIN travel TR ON E.travel_id = TR.id
						  JOIN warehouse W ON W.id = TR.warehouse_id  -- PAK
						  WHERE TR.landing BETWEEN date_tomorrow AND date_end
						  AND IF(wh = 0, W.is_comparative, wh =TR.warehouse_id)
						  AND E.Inventario = 0
						  AND E.Redada = 0
                          
						  UNION ALL
                          
                          SELECT Id_Article, shipment as Fecha, -Cantidad
						  FROM Compres C 
						  JOIN Entradas E USING (Id_Entrada)
						  JOIN travel TR ON E.travel_id = TR.id
						  JOIN warehouse W ON W.id = TR.warehouse_id_out
						  WHERE TR.shipment BETWEEN date_tomorrow AND date_end
						  AND IF(wh = 0, W.is_comparative, wh =TR.warehouse_id_out)
						  AND E.Inventario = 0
						  AND E.Redada = 0
                          
					 ) AS Tic2

					 GROUP BY Tic2.Id_Article, Fecha
					) Tic3

				   LEFT JOIN Articles A ON Tic3.Id_Article = A.Id_Article
					 LEFT JOIN Origen O ON O.id = A.id_origen
					  LEFT JOIN item_travel t ON t.wh = O.warehouse_id

				  WHERE Fecha < IF(days_max < 0 AND t.landing IS NOT NULL,
								   t.landing,
								   date_top)

					 GROUP BY Tic3.Id_Article


		 ) AS Tic5

	ON Tic5.Id_Article = AI.article_id
	SET AI.avalaible =  IF(Tic5.smd > 0, AI.avalaible, AI.avalaible + Tic5.smd),
		AI.sd = AI.inventory + Tic5.sd;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `inventario_multiple_inventarios` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `inventario_multiple_inventarios`(wh SMALLINT, date_ticket DATETIME)
BEGIN
	DECLARE date_order DATETIME;
	DECLARE date_end DATETIME DEFAULT CURDATE();
	DECLARE date_start DATETIME;

	CALL article ();

	ALTER TABLE article_inventory
		ADD visible FLOAT(7,2) NOT NULL;

	-- Campaña

	SELECT
			IF(@camp := DATEDIFF(campaign, date_ticket) BETWEEN 0 AND campaign_life ,
			TIMESTAMPADD(DAY, -campaign_life, campaign) ,
			FechaInventario),
			IF(@camp BETWEEN 0 AND campaign_life,
			TIMESTAMP(campaign, '23:59:59'),
			TIMESTAMP(TIMESTAMPADD(DAY, 15, date_ticket),'23:59:59'))
		INTO date_start, date_end
		FROM tblContadores;

	SET date_order = TIMESTAMP(DATE(date_ticket), '00:00:00');

	INSERT INTO article_inventory (article_id, visible)
		SELECT Id_Article, SUM(amount) 
		FROM (
			SELECT Id_Article, -Cantidad AS amount
				FROM Movimientos M INNER JOIN Tickets T USING (Id_Ticket)
				WHERE Fecha >= date_start
					AND Fecha < date_order
					AND T.warehouse_id = wh
			UNION ALL
			SELECT Id_Article, Cantidad
				FROM Compres C INNER JOIN Entradas E USING (Id_Entrada)
					LEFT JOIN travel TR ON E.travel_id = TR.id
				WHERE TR.landing >= date_start
					AND TR.landing < date_order
					AND TR.warehouse_id = wh
					AND E.Inventario = FALSE
			UNION ALL
			SELECT Id_Article, -Cantidad
				FROM Compres C INNER JOIN Entradas E USING (Id_Entrada)
					LEFT JOIN travel TR ON E.travel_id = TR.id
				WHERE TR.shipment >= date_start
					AND TR.shipment < date_order
					AND TR.warehouse_id_out = wh
					AND E.Inventario = FALSE
		) AS T1
		GROUP BY Id_Article;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `inventario_multiple_joined` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `inventario_multiple_joined`(
	date_ticket DATETIME
	,wh_joined TINYINT
	,days_max TINYINT
)
proc: BEGIN
	DECLARE date_end DATETIME DEFAULT CURDATE();
	DECLARE date_start DATETIME;
	DECLARE date_top DATETIME;
	DECLARE date_tomorrow DATETIME;
	DECLARE i_avalaible INTEGER;
	DECLARE wh INTEGER;

	SET date_ticket = DATE(date_ticket); -- PAK

	ALTER TABLE `article_inventory`
		ADD `avalaible` INT NOT NULL,
		ADD `sd` INT NOT NULL,
		ADD `rest` INT NOT NULL,
		ADD `expected` INT NOT NULL,
		ADD `inventory` INT NOT NULL,
		ADD `visible` INT NOT NULL,
		ADD `life` TINYINT NOT NULL DEFAULT '0';

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

	SELECT FechaInventario INTO date_start FROM tblContadores;

	SET date_end = TIMESTAMP(TIMESTAMPADD(DAY, IF(days_max >= 0, days_max,15), date_ticket),'23:59:59');
	SET date_tomorrow = TIMESTAMPADD(DAY, 1,date_ticket);
	SET date_top = TIMESTAMPADD(DAY, 1,date_end);

	-- Calculo del inventario dia D a las 24:00 zulu

	UPDATE article_inventory AI INNER JOIN

	(

	SELECT Id_Article, SUM(amount) as Subtotal FROM

		(

		SELECT Id_Article, -Cantidad AS amount

		FROM Movimientos M 
		
		JOIN Tickets T USING (Id_Ticket)
		JOIN warehouse_joined wj ON T.warehouse_id = wj.warehouse_id -- JGF 15/12/14
		WHERE DATE(Fecha) BETWEEN date_start AND date_ticket
		AND wh_joined IN (wj.warehouse_alias_id, 0)
		UNION ALL

		SELECT Id_Article,  Cantidad

		FROM Compres C INNER JOIN Entradas E USING (Id_Entrada)

		LEFT JOIN travel TR ON E.travel_id = TR.id
		JOIN warehouse_joined wj ON TR.warehouse_id = wj.warehouse_id -- JGF 15/12/14
		WHERE TR.landing BETWEEN date_start AND date_ticket
		AND wh_joined IN (wj.warehouse_alias_id, 0)
		
		AND E.Inventario = 0
		AND E.Redada = 0

		UNION ALL

		SELECT Id_Article,  -Cantidad
		FROM Compres C 
		
		JOIN Entradas E USING (Id_Entrada)
		JOIN travel TR ON E.travel_id = TR.id
		JOIN warehouse_joined wj ON TR.warehouse_id_out = wj.warehouse_id -- JGF 15/12/14
		WHERE TR.shipment BETWEEN date_start AND date_ticket
		AND wh_joined IN (wj.warehouse_alias_id,0)
		AND E.Inventario = 0
		AND E.Redada = 0
		) AS T1

	  GROUP BY Id_Article

		) AS T2

	  ON AI.article_id = T2.Id_Article

	 SET AI.inventory = T2.Subtotal,

		 AI.visible = T2.Subtotal,

		 AI.avalaible = T2.Subtotal,

		 AI.sd = T2.Subtotal;

	SELECT avalaible INTO i_avalaible FROM article_inventory WHERE article_id = 21012;

	-- Calculo del visible

	UPDATE article_inventory AI INNER JOIN
	(
	  SELECT Id_Article, SUM(amount) as Subtotal FROM
		(
		SELECT Id_Article, Cantidad AS amount
		FROM Movimientos M 
		
		JOIN Tickets T USING (Id_Ticket)
		JOIN warehouse_joined wj ON T.warehouse_id = wj.warehouse_id -- JGF 15/12/14
		WHERE Fecha >= date_ticket AND Fecha < date_tomorrow -- PAK
			AND (M.OK = 0 AND T.Etiquetasemitidas = 0 AND T.Factura IS NULL)
			AND wh_joined IN (wj.warehouse_alias_id, 0)
		UNION ALL
		SELECT Id_Article,  -Cantidad
		FROM Compres C
		
		JOIN Entradas E USING (Id_Entrada)
		JOIN travel TR ON E.travel_id = TR.id
		
		JOIN warehouse_joined wj ON TR.warehouse_id = wj.warehouse_id -- JGF 15/12/14
		WHERE TR.landing = date_ticket
				
		AND TR.received = 0
		AND E.Inventario = 0
		AND E.Redada = 0
		AND wh_joined IN (wj.warehouse_alias_id, 0)

		UNION ALL

		SELECT Id_Article,  Cantidad
		FROM Compres C INNER JOIN Entradas E USING (Id_Entrada)
		LEFT JOIN travel TR ON E.travel_id = TR.id
		JOIN warehouse_joined wj ON TR.warehouse_id_out = wj.warehouse_id -- JGF 15/12/14
		WHERE TR.shipment = date_ticket
		AND TR.delivered = 0
		AND E.Inventario = 0
		AND E.Redada = 0
		AND wh_joined IN (wj.warehouse_alias_id,0)
		) AS T1

		  GROUP BY Id_Article

	  ) AS T2

	  ON AI.article_id = T2.Id_Article

	 SET AI.visible = AI.visible + T2.Subtotal;

	-- Calculo del disponible
	SELECT IF(COUNT(warehouse_id),0,warehouse_id) INTO wh FROM warehouse_joined WHERE warehouse_alias_id = wh_joined;

	CALL item_travel (wh, date_ticket);

	UPDATE article_inventory AI INNER JOIN
		 (
				   SELECT Tic3.Id_Article, SUM(amount) AS sd, minacum(Fecha, amount, date_ticket) as smd FROM
				   (

				   SELECT Tic2.Id_Article, Fecha, SUM(amount) AS amount FROM
					 (
								SELECT Id_Article, DATE(Fecha) as Fecha, -Cantidad AS amount
								  FROM Movimientos M 
								  
						  JOIN Tickets T USING (Id_Ticket)
						  
						  JOIN warehouse_joined wj ON T.warehouse_id = wj.warehouse_id -- JGF 15/12/14
						  WHERE Fecha BETWEEN date_tomorrow AND date_end
						  AND wh_joined IN (wj.warehouse_alias_id, 0)
						  
							  UNION ALL
								  SELECT Id_Article, landing as Fecha, Cantidad
									FROM Compres C 
									
						  JOIN Entradas E USING (Id_Entrada)
									JOIN travel TR ON E.travel_id = TR.id
									
						  JOIN warehouse_joined wj ON TR.warehouse_id = wj.warehouse_id -- JGF 15/12/14
									  WHERE TR.landing BETWEEN date_tomorrow AND date_end
									  AND wh_joined IN (wj.warehouse_alias_id, 0)
									  
						  AND E.Inventario = 0
						  AND E.Redada = 0
						UNION ALL
								  SELECT Id_Article, shipment as Fecha, -Cantidad
									FROM Compres C 
									
						  JOIN Entradas E USING (Id_Entrada)
									JOIN travel TR ON E.travel_id = TR.id
						  JOIN warehouse_joined wj ON TR.warehouse_id_out = wj.warehouse_id -- JGF 15/12/14
									  WHERE TR.shipment BETWEEN date_tomorrow AND date_end
									  AND wh_joined IN (wj.warehouse_alias_id,0)
						  AND E.Inventario = 0
						  AND E.Redada = 0
					 ) AS Tic2

					 GROUP BY Tic2.Id_Article, Fecha
					) Tic3

				   LEFT JOIN Articles A ON Tic3.Id_Article = A.Id_Article
					 LEFT JOIN Origen O ON O.id = A.id_origen
					  LEFT JOIN item_travel t ON t.wh = O.warehouse_id

				  WHERE Fecha < IF(days_max < 0 AND t.landing IS NOT NULL,
								   t.landing,
								   date_top)

					 GROUP BY Tic3.Id_Article


		 ) AS Tic5

	ON Tic5.Id_Article = AI.article_id
	SET AI.avalaible =  IF(Tic5.smd > 0, AI.avalaible, AI.avalaible + Tic5.smd),
		AI.sd = AI.inventory + Tic5.sd;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `inventario_multiple_reservas` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `inventario_multiple_reservas`(date_ticket DATETIME, wh INT, days_max INT)
BEGIN
	DECLARE date_end DATETIME DEFAULT CURDATE();
	DECLARE date_start DATETIME;
	DECLARE i_avalaible INTEGER;

	SET date_ticket = DATE(date_ticket);

	CALL article ();

	INSERT INTO article_inventory (article_id)
		SELECT a.Id_Article
		FROM Articles a
			JOIN Tipos tp ON tp.tipo_id = a.tipo_id
			LEFT JOIN reinos r ON r.id = tp.reino_id
		WHERE r.display <> 0;

	ALTER TABLE `article_inventory`
		ADD `avalaible` INT(11) NOT NULL,
		ADD `sd` INT(11) NOT NULL,
		ADD `rest` INT(11) NOT NULL,
		ADD `expected` INT(11) NOT NULL,
		ADD `inventory` INT(11) NOT NULL,
		ADD `visible` INT(11) NOT NULL,
		ADD `life` TINYINT(1) NOT NULL DEFAULT '0';

	SELECT FechaInventario INTO date_start FROM tblContadores;

	SET date_end = TIMESTAMP(TIMESTAMPADD(DAY, -1, date_ticket),'23:59:59');

	-- Utilizo el valor clave 4848 para days_max para aprovechar el procedimiento para el frmCamiones de eti

	IF days_max = 4848 THEN 
		  set date_ticket = date_end;
	END IF;

	-- Calculo del inventario dia D a las 24:00

	UPDATE article_inventory AI INNER JOIN
	(
		SELECT Id_Article, SUM(amount) as Subtotal FROM (
			SELECT Id_Article, -Cantidad AS amount
				FROM Movimientos M 
					JOIN Tickets T USING (Id_Ticket)
					JOIN warehouse W ON W.id = T.warehouse_id
				WHERE Fecha BETWEEN date_start AND date_end
					AND wh IN (T.warehouse_id, 0)
					AND NOT W.fuente
			UNION ALL
			SELECT Id_Article,  Cantidad
				FROM Compres C 
					JOIN Entradas E USING (Id_Entrada)
					LEFT JOIN travel TR ON E.travel_id = TR.id
					JOIN warehouse W ON W.id = TR.warehouse_id
				WHERE TR.landing BETWEEN date_start AND date_ticket
					AND wh IN (TR.warehouse_id, 0)
					AND NOT W.fuente
					AND E.Inventario = 0
					AND E.Redada = 0
			UNION ALL
			SELECT Id_Article,  -Cantidad
				FROM Compres C 
					JOIN Entradas E USING (Id_Entrada)
					JOIN travel TR ON E.travel_id = TR.id
					JOIN warehouse W ON W.id = TR.warehouse_id_out
				WHERE TR.shipment BETWEEN date_start AND date_end
					AND wh IN (TR.warehouse_id_out,0)
					AND NOT W.fuente
					AND E.Inventario = 0
					AND E.Redada = 0
		) AS T1
		GROUP BY Id_Article
	) AS T2
	ON AI.article_id = T2.Id_Article
	SET AI.inventory = T2.Subtotal,
		AI.visible = T2.Subtotal,
		AI.avalaible = T2.Subtotal,
        AI.sd = T2.Subtotal;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `inventario_valorado` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `inventario_valorado`(IN d_FEC DATE, IN bol_DESGLOSE BOOLEAN)
BEGIN

    DECLARE d_INV DATE;
	DECLARE bolREVERSE BOOLEAN DEFAULT 0;
    DECLARE d_INV2 DATE;

    SELECT landing INTO d_INV
    FROM travel TR
		INNER JOIN Entradas E ON E.travel_id = TR.id
    WHERE landing <= d_FEC
		AND E.Id_Proveedor = 4
    ORDER BY landing DESC
    LIMIT 1;

	SET bolREVERSE = IF (d_INV is null, 1, 0);

	
	IF bolREVERSE THEN

		SELECT landing INTO d_INV2
		FROM travel TR
			INNER JOIN Entradas E ON E.travel_id = TR.id
		WHERE landing >= d_FEC
			AND E.Id_Proveedor = 4
		ORDER BY landing ASC
		LIMIT 1;

		SET d_INV = TIMESTAMPADD(DAY,1,d_FEC);
		SET d_FEC = d_INV2;



	END IF;

	DROP TEMPORARY TABLE IF EXISTS inv;

	CREATE TEMPORARY TABLE inv 
		(w_id SMALLINT,
		 Id_Article BIGINT,
		 cantidad INT,	
		 coste DOUBLE DEFAULT 0,
		 total DOUBLE DEFAULT 0) ENGINE = MEMORY;

  
	ALTER TABLE inv ADD PRIMARY KEY USING HASH (w_id, Id_Article);



	IF bolREVERSE = 1 THEN

		INSERT INTO inv(w_id, Id_Article, cantidad)
			SELECT TR.warehouse_id, C.Id_Article, SUM(C.Cantidad)
			FROM Compres C
				INNER JOIN Articles A USING(Id_Article)
				INNER JOIN Entradas E USING (Id_Entrada)
				INNER JOIN travel TR ON TR.id = E.travel_id
				INNER JOIN Tipos t USING(tipo_id)
				INNER JOIN warehouse w ON w.id = warehouse_id
			WHERE landing = d_FEC
				AND E.Id_Proveedor = 4
				AND w.valuatedInventory
				AND t.inventory
				AND reino_id NOT IN (7)
			GROUP BY TR.warehouse_id, C.Id_Article;

	END IF;

		INSERT INTO inv(w_id, Id_Article, cantidad)
		SELECT TR.warehouse_id, C.Id_Article, C.Cantidad * IF(bolREVERSE,-1,1)
		FROM Compres C
		INNER JOIN Articles A USING(Id_Article)
		INNER JOIN Entradas E USING (Id_Entrada)
		INNER JOIN travel TR ON TR.id = E.travel_id
		INNER JOIN Tipos t USING(tipo_id)
		INNER JOIN warehouse w ON w.id = TR.warehouse_id
		WHERE landing BETWEEN d_INV AND TIMESTAMPADD(DAY, IF(bolREVERSE,-1,0) ,d_FEC)
        AND IF(landing = CURDATE(), TR.received, TRUE)
		AND NOT redada
		AND w.valuatedInventory
		AND reino_id NOT IN (7)
		AND t.inventory
		ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + (C.Cantidad * IF(bolREVERSE,-1,1));

		INSERT INTO inv(w_id, Id_Article, cantidad)
		SELECT TR.warehouse_id_out, C.Id_Article, C.Cantidad * IF(bolREVERSE,1,-1)
		FROM Compres C
		INNER JOIN Articles A USING(Id_Article)
		INNER JOIN Entradas E USING (Id_Entrada)
		INNER JOIN travel TR ON TR.id = E.travel_id
		INNER JOIN Tipos t USING(tipo_id)
		INNER JOIN warehouse w ON w.id = warehouse_id_out
		WHERE shipment BETWEEN d_INV AND TIMESTAMPADD(DAY, IF(bolREVERSE,-1,0) ,d_FEC)
		AND NOT redada
		AND w.valuatedInventory
		AND reino_id NOT IN (7)
		AND t.inventory
		ON DUPLICATE KEY UPDATE  inv.cantidad = inv.cantidad + (C.Cantidad * IF(bolREVERSE,1,-1));
				  
		INSERT INTO inv(w_id, Id_Article, cantidad)
		SELECT w.id, M.Id_Article, M.Cantidad  * IF(bolREVERSE,1,-1)
		FROM Movimientos M
		INNER JOIN Tickets T USING (Id_Ticket)
		INNER JOIN Clientes C USING(Id_Cliente)
		INNER JOIN Articles A USING(Id_Article)
		INNER JOIN Tipos t USING(tipo_id)
		INNER JOIN warehouse w ON w.id = warehouse_id
		WHERE T.Fecha BETWEEN d_INV AND TIMESTAMPADD(DAY, -1 ,d_FEC)
		AND w.valuatedInventory
		AND reino_id NOT IN (7)
		AND t.inventory
		ON DUPLICATE KEY UPDATE  inv.cantidad = inv.cantidad + M.Cantidad * IF(bolREVERSE,1,-1);


		INSERT INTO inv(w_id, Id_Article, cantidad)
		SELECT w.id, M.Id_Article, M.Cantidad  * IF(bolREVERSE,0,-1)
		FROM Movimientos M
		INNER JOIN Tickets T USING (Id_Ticket)
		INNER JOIN Clientes C USING(Id_Cliente)
		INNER JOIN Articles A USING(Id_Article)
		INNER JOIN Tipos t USING(tipo_id)
		INNER JOIN warehouse w ON w.id = warehouse_id
		WHERE date(T.Fecha) = d_FEC
		AND  (d_FEC <> CURDATE()  or (M.OK <> 0 or T.Etiquetasemitidas <> 0 ))
		AND w.valuatedInventory
		AND reino_id NOT IN (7)
		AND t.inventory
		ON DUPLICATE KEY UPDATE  inv.cantidad = inv.cantidad + M.Cantidad * IF(bolREVERSE,0,-1);

	CALL item_last_buy_(NULL,d_FEC);
    
	UPDATE inv 
	JOIN t_item_last_buy lb ON w_id = lb.warehouse_id AND inv.Id_Article = lb.item_id
	JOIN Compres C ON C.Id_Compra = lb.buy_id
	SET total = inv.cantidad * (ifnull(C.Costefijo,0) + IFNULL(C.Embalajefijo,0) + IFNULL(C.Portefijo,0) + IFNULL(C.Comisionfija,0)),
	coste = ifnull(C.Costefijo,0) + IFNULL(C.Embalajefijo,0) + IFNULL(C.Portefijo,0) + IFNULL(C.Comisionfija,0)
	WHERE inv.cantidad <> 0;

	DELETE FROM inv WHERE Cantidad IS NULL or Cantidad = 0;

	IF bol_DESGLOSE THEN

		SELECT inv.w_id, a.Id_Article, a.Article, a.Medida, inv.Cantidad, tp.Id_Tipo,
			tp.reino_id, inv.coste, cast(inv.total as decimal(10,2)) total, an.nicho
		FROM inv 
			JOIN warehouse w on w.id = w_id
			JOIN Articles a ON a.Id_Article = inv.Id_Article
			JOIN Tipos tp ON tp.tipo_id = a.tipo_id
			JOIN Articles_nicho an ON an.Id_Article = a.Id_Article AND an.warehouse_id = w.id
		where w.valuatedInventory
		and inv.total > 0
		order by inv.total desc;

	ELSE

		SELECT w.name as Almacen, r.reino as Reino, cast(total as decimal) as Euros, tr.CodigoTrabajador as Comprador
		FROM inv
		JOIN warehouse w ON w.id = w_id
		JOIN Articles A USING(Id_Article)
		JOIN Tipos t USING(tipo_id)
        LEFT JOIN Trabajadores tr ON tr.Id_Trabajador = t.Id_Trabajador
		JOIN reinos r ON r.id = t.reino_id
		where w.valuatedInventory;

	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 `itemTagArrangedUpdateKk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemTagArrangedUpdateKk`(IN vItem BIGINT)
BEGIN
/**
 *  DEPRECATED
 **/
	CALL vn.itemTagArrangedUpdate(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 */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemTagArrangedUpdate_launcherKk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_launcherKk`()
BEGIN

	call vn2008.itemTagArrangedUpdate(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 `item_buy` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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_buy`(IN v_wh TINYINT, IN v_date DATETIME)
BEGIN
	DECLARE date_inv DATE;
	ALTER TABLE item
		ADD buy_id INT UNSIGNED;
	
	IF v_date < (SELECT date_inv()) THEN
		SELECT MIN(landing) INTO date_inv FROM travel t INNER JOIN Entradas e ON e.travel_id = t.id 
			WHERE warehouse_id_out = 13 AND landing <= v_date;
	ELSE
		SET date_inv = date_inv();
	END IF;
	UPDATE item i INNER JOIN (
		SELECT * FROM (
			SELECT c.Id_Article item_id, c.Id_Compra id
				FROM Compres c INNER JOIN Entradas e USING(Id_Entrada)
      				INNER JOIN travel t ON t.id = e.travel_id
					WHERE t.landing BETWEEN date_inv AND v_date
					AND c.Novincular = FALSE
					AND c.Tarifa2 >= 0
					ORDER BY  v_wh = t.warehouse_id DESC, t.landing DESC
		) t
		GROUP BY item_id
	) t
	ON i.id = t.item_id
		SET i.buy_id = t.id;

	CREATE INDEX buy USING HASH ON item (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 `item_buy_price` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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_buy_price`(IN v_customer INT,IN date_ DATE,IN v_wh TINYINT)
BEGIN
  ALTER TABLE item
		ADD price DOUBLE,
        ADD discount INT;


	-- Lo primero, el precio normal, la ultima entrada para ese almacen

	UPDATE item i 
    JOIN Compres b ON i.buy_id = b.Id_Compra
    JOIN Clientes c ON c.Id_cliente = v_customer
	SET i.price = CASE c.Descuento
    
				  WHEN 0 THEN b.PVP	
				  WHEN 1 THEN b.Tarifa1
				  WHEN 2 THEN b.Tarifa2
				  WHEN 3 THEN b.Tarifa3
				  ELSE IF(c.Descuento BETWEEN 4 AND 100, b.Tarifa2, round(b.Tarifa3 * (200 - c.Descuento) / 100  ,2) )
                  END,
		i.discount =  IF(c.Descuento BETWEEN 4 AND 100, c.Descuento, 0);

	-- Precios fijados

	UPDATE item i 
	INNER JOIN Clientes c ON c.Id_cliente = v_customer
	JOIN v_price_fixed_group fp ON i.id = fp.item_id
	SET i.price = CASE c.Descuento
				  WHEN 0 THEN fp.rate_0
				  WHEN 1 THEN fp.rate_1
				  WHEN 2 THEN fp.rate_2
				  WHEN 3 THEN fp.rate_3
				  ELSE fp.rate_3
                  END,
        i.discount = 0 
	WHERE fp.warehouse_id IN (0,v_wh) 
    AND date_ BETWEEN fp.date_start AND fp.date_end;

    -- Precios especiales

	UPDATE item i 
	JOIN Clientes c ON c.Id_cliente = v_customer
	JOIN PreciosEspeciales p ON i.id = p.Id_Article AND p.Id_Cliente = v_customer
	 SET i.price = p.PrecioEspecial,
	 i.discount = 0;
   
    -- Precio mínimo

	UPDATE item i 
	JOIN Articles a ON a.Id_Article = i.id
    JOIN Clientes c ON c.Id_cliente = v_customer
	 SET i.price = IF(a.`Min` AND i.price < a.PVP, a.PVP,i.price);
   
-- pak 14/9/14 provisional

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_express` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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_express`(IN intWH INT, IN datFEC DATE)
BEGIN

DECLARE datINV DATE;



SELECT FechaInventario INTO datINV FROM tblContadores LIMIT 1;


SELECT sub1.Id_Article, Visible, Tarifa2
FROM
(SELECT Id_Article, SUM(Cantidad) as Visible
FROM Compres C
JOIN Entradas E USING(Id_Entrada)
JOIN travel T ON T.id = E.travel_id
WHERE shipment >= datINV
AND landing <= datFEC
AND Redada = 0
AND warehouse_id = intWH
GROUP BY Id_Article) sub1
JOIN
(
SELECT * FROM
(
SELECT Id_Article, Tarifa2
FROM Compres C
JOIN Entradas E USING(Id_Entrada)
JOIN travel T ON T.id = E.travel_id
WHERE shipment >= datINV
AND landing <= datFEC
AND Redada = 0
AND Novincular = 0
AND warehouse_id = intWH
ORDER BY landing DESC) sub
GROUP BY Id_Article) sub2 USING(Id_Article);


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_last_buy_` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_last_buy_`(v_wh SMALLINT, v_date DATE)
BEGIN

-- DEPRECATED USE vn.buyUltimate
	-- Ultima compra hasta hoy

	CALL cache.last_buy_refresh (FALSE);


	DROP TEMPORARY TABLE IF EXISTS t_item_last_buy;
	CREATE TEMPORARY TABLE t_item_last_buy
		(PRIMARY KEY (item_id,warehouse_id))
		ENGINE = MEMORY 
		SELECT item_id, buy_id, warehouse_id
			FROM cache.last_buy
            WHERE v_wh = warehouse_id OR v_wh IS NULL;


	-- Ultima compra hasta @v_date


	-- CALL item_last_buy_from_interval (v_wh, CURDATE(), TIMESTAMPADD(DAY, 1, v_date)); JGF 2016-06-08 fallo: cogia un dia mas de lo solicitado	
	CALL item_last_buy_from_interval (v_wh, CURDATE(), v_date);

	REPLACE INTO t_item_last_buy 
		SELECT item_id, buy_id, warehouse_id
			FROM tmp.item_last_buy_from_interval
            WHERE v_wh = warehouse_id OR v_wh IS NULL;


	DROP TEMPORARY TABLE tmp.item_last_buy_from_interval;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_last_buy_from_interval` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_last_buy_from_interval`(v_wh SMALLINT, v_date_ini DATE, v_date_end DATE)
BEGIN
/**
 * DEPRECATED USE vn.buyUltimateFromInterval
 * Obtiene la ultima compra a partir de un intervalo
 * de fechas dado.
 *
 * @param v_wh Id de almacen %NULL para todos los almacenes
 * @param v_date_ini Fecha inicial
 * @param v_date_end Fecha final
 * @table tmp.item_last_buy_from_interval
 **/
    IF v_date_end IS NULL
    THEN
        SET v_date_end = v_date_ini;
    END IF;
    
 
    IF v_date_end < v_date_ini THEN
		SET v_date_ini = TIMESTAMPADD(MONTH,-1,v_date_end);
    END IF;

	DROP TEMPORARY TABLE  IF EXISTS tmp.item_last_buy_from_interval;
	CREATE TEMPORARY TABLE tmp.item_last_buy_from_interval
		ENGINE = MEMORY
		SELECT c.Id_Article item_id, t.warehouse_id, multimax(t.landing, c.Id_Compra) buy_id, MAX(t.landing) landing
			FROM Compres c
				JOIN Entradas e USING (Id_Entrada)
				JOIN travel t ON t.id = e.travel_id
			WHERE t.landing BETWEEN v_date_ini AND v_date_end
				AND (v_wh IS NULL OR t.warehouse_id = v_wh)
				AND c.Tarifa2 > 0
				AND NOT c.Novincular
			GROUP BY item_id, 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 `item_new` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `item_new`()
BEGIN
    CREATE TEMPORARY TABLE item
    (
        item_id INT UNSIGNED NOT NULL,
        UNIQUE KEY USING HASH (item_id)
    )
    ENGINE = MEMORY;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_stock` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_stock`(v_wh SMALLINT, v_date DATETIME, v_item INT)
BEGIN
/**
 * Calcula el stock del v_wh desde FechaInventario hasta v_date	
 **/

	DECLARE n TINYINT;
	DECLARE v_diff TIME;
	DECLARE v_inv DATETIME;
	DECLARE v_camp DATETIME;
	DECLARE v_curdate DATETIME DEFAULT CURDATE();

	SET v_date = TIMESTAMP(DATE(v_date), '00:00:00');

	SELECT FechaInventario, TIMESTAMPADD(DAY, -campaign_life, campaign)
		INTO v_inv, v_camp FROM tblContadores LIMIT 1;
    
	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) stock, SUM(amount) visible, SUM(amount) available FROM (
				SELECT item_id, amount FROM item_out
					WHERE dat >= v_curdate AND dat < v_date
						AND warehouse_id = v_wh
                        AND (v_item IS NULL OR item_id = v_item)
				UNION ALL
				SELECT item_id, amount FROM item_entry_in
					WHERE dat >= v_curdate AND dat < v_date
						AND warehouse_id = v_wh
                        AND (v_item IS NULL OR item_id = v_item)
				UNION ALL
				SELECT item_id, amount FROM item_entry_out
					WHERE dat >= v_curdate AND dat < v_date
						AND warehouse_id = v_wh
                        AND (v_item IS NULL OR item_id = v_item)
			) t
			GROUP BY item_id HAVING stock != 0;

    CALL `cache`.stock_refresh (FALSE);

	INSERT INTO tmp_item (item_id,stock,visible,available)
	SELECT item_id,amount,amount,amount FROM `cache`.stock
		WHERE warehouse_id = v_wh AND (v_item IS NULL OR v_item = item_id)
		ON DUPLICATE KEY UPDATE
			stock = stock + VALUES(stock),
			visible = visible + VALUES(visible),
			available = available + VALUES(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_stock_visible` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_stock_visible`(v_wh SMALLINT, v_item INT)
BEGIN
	DECLARE v_curdate DATETIME DEFAULT TIMESTAMP(CURDATE(), '00:00:00');
	DECLARE v_tomorrow DATETIME DEFAULT TIMESTAMPADD(HOUR, 24, CURDATE());

	INSERT INTO tmp_item (item_id, visible)
		SELECT item_id, SUM(amount) amount 
        FROM (
			SELECT item_id, amount 
				FROM item_out i
					LEFT JOIN vn.ticketState ts ON ts.ticketFk = i.ticketFk 
					LEFT JOIN `vn`.`saleTracking` `stPrevious` 
						ON `stPrevious`.`saleFk` = i.saleFk
                        AND `stPrevious`.`stateFk` = 26
					LEFT JOIN `vn`.`saleTracking` `stPrepared` 
						ON `stPrepared`.`saleFk` = i.saleFk
						AND `stPrepared`.`stateFk` = 14
					LEFT JOIN `vn`.`saleTracking` `stControled` 
						ON `stControled`.`saleFk` = i.saleFk
						AND `stControled`.`stateFk` = 8
				WHERE warehouse_id = v_wh
					AND i.dat >= v_curdate 
					AND (		
							((	
							stPrevious.isChecked 
							OR stPrepared.isChecked 
							OR stControled.isChecked
							OR ts.alertLevel > 1
							OR i.invoice IS NOT NULL
							) 
						AND dat < v_tomorrow)
					OR i.Reservado) 
			UNION ALL
			SELECT item_id, amount 
				FROM item_entry_in iei
					LEFT JOIN vn.itemPlacement ip ON ip.itemFk = iei.item_id AND ip.warehouseFk = v_wh
				WHERE (iei.received != FALSE OR ip.modificationDate > CURDATE())
					AND iei.dat >= v_curdate AND iei.dat < v_tomorrow
					AND iei.warehouse_id = v_wh
					AND (v_item IS NULL OR iei.item_id = v_item)
                    AND iei.isVirtualStock is FALSE
			UNION ALL
			SELECT item_id, amount FROM item_entry_out
				WHERE delivered != FALSE
					AND dat >= v_curdate AND dat < v_tomorrow
					AND warehouse_id = v_wh
					AND (v_item IS NULL OR item_id = v_item)
			UNION ALL -- PAK 20/4/2019
            SELECT iei.item_id, sub.shelved 
				FROM item_entry_in iei
					LEFT JOIN vn.itemPlacement ip ON ip.itemFk = iei.item_id
					JOIN (
							 SELECT itemFk, sum(visible) as shelved
								FROM vn.itemShelving ish 
									JOIN vn.shelving sh ON sh.code = ish.shelvingFk
									JOIN vn.parking pk ON pk.id = sh.parkingFk
									JOIN vn.sector sc ON sc.id = pk.sectorFk
								WHERE ish.created >= CURDATE()
									AND warehouseFk = v_wh
                                    AND (v_item IS NULL OR ish.itemFk = v_item)
								GROUP BY itemFk
						) sub ON sub.itemFk = iei.item_id
				WHERE (iei.received = FALSE AND IFNULL(ip.modificationDate,CURDATE()) < CURDATE())
					AND iei.dat >= v_curdate AND iei.dat < v_tomorrow
					AND iei.warehouse_id = v_wh
					AND (v_item IS NULL OR iei.item_id = v_item)
                    AND iei.isVirtualStock is FALSE
           
		) t
		GROUP BY item_id
		ON DUPLICATE KEY UPDATE
		visible = IFNULL(stock,0) + VALUES(visible);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_travel` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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_travel`(v_wh TINYINT, v_date DATETIME)
BEGIN
	DECLARE v_travel INT;
	DECLARE v_wh_out INT;
	DECLARE v_shipment DATETIME;
	DECLARE v_campaign DATETIME;
	DECLARE v_date_start DATETIME;

	DROP TEMPORARY TABLE IF EXISTS travel_top;
	DROP TEMPORARY TABLE IF EXISTS item_travel;

    -- Crea una taula buida travel_top

	CREATE TEMPORARY TABLE travel_top
	(PRIMARY KEY (wh_in,wh_out,landing,shipment)) -- 28/1/15 JGF & PAK cuelgue dia 26
		ENGINE = MEMORY
		SELECT 0 id, v_wh wh_in, v_wh wh_out, FALSE ok, v_date landing, v_date shipment;

	REPEAT
		SET v_travel = NULL;
    
		-- Va seleccionant registres un a un

		SELECT id, wh_out, shipment, landing
			INTO v_travel, v_wh_out, v_shipment, v_date_start
			FROM travel_top WHERE ok = FALSE LIMIT 1;
            
		-- Marca el registre per a saber que esta revistat

		UPDATE travel_top SET ok = TRUE WHERE id = v_travel;

		-- Concatena travels


		INSERT IGNORE INTO travel_top
        SELECT id, v_wh, warehouse_id_out, FALSE, IF(v_travel, v_date_start, landing), shipment
            FROM travel
                WHERE warehouse_id = v_wh_out
					-- Canvia Javi 08/04/13 error que pasaba a les 06:00 del mati
					-- AND IF(v_travel, landing <= v_shipment, landing > v_shipment)
					AND IF(v_travel, landing <= v_shipment, landing >= v_shipment)
                    AND shipment >= CURDATE()
					AND delivered = FALSE;

	UNTIL v_travel IS NULL 
	END REPEAT;/*
	select max_count;
		SELECT * FROM travel_top;*/

	DELETE FROM travel_top WHERE id = 0;
/*
	SELECT TIMESTAMPADD(DAY, -campaign_life, campaign), campaign
		INTO v_date_start, v_campaign FROM tblContadores;*/

    -- Agafa el travel que arriva primer per a cada warehouse

	CREATE TEMPORARY TABLE item_travel
	(KEY (wh))
	ENGINE = MEMORY
	SELECT * FROM (
		SELECT wh_out wh,/* IF(
			v_date BETWEEN v_date_start AND v_campaign
			AND landing BETWEEN v_date_start AND v_campaign
			,TIMESTAMPADD(DAY, 1, v_campaign)
			,landing
		) */ landing
			FROM travel_top
				WHERE wh_out <> v_wh
				ORDER BY landing
	) t
	GROUP BY wh;
-- SELECT * FROM item_travel;
	DROP TEMPORARY TABLE travel_top;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_travel_fixed` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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_travel_fixed`(v_wh TINYINT, v_date DATETIME)
BEGIN
	DECLARE v_travel INT;
	DECLARE v_wh_out INT;
	DECLARE v_shipment DATETIME;
	DECLARE v_campaign DATETIME;
	DECLARE v_date_start DATETIME;

	DROP TEMPORARY TABLE IF EXISTS travel_top;
	DROP TEMPORARY TABLE IF EXISTS item_travel_fixed;

	CREATE TEMPORARY TABLE travel_top
	(KEY (id))
	ENGINE = MEMORY
		SELECT 0 id, v_wh wh_out, v_date shipment;

	REPEAT
		SET v_travel = NULL;
		
		SELECT t.id, wh_out, shipment
			INTO v_travel, v_wh_out, v_shipment
			FROM travel_top t 
			JOIN warehouse w ON w.id = wh_out AND fuente = 0
				LIMIT 1;

		INSERT INTO travel_top 
		SELECT t.id, warehouse_id_out, shipment/*, FALSE*/
			FROM travel t
			WHERE warehouse_id = v_wh_out
				AND landing <= v_shipment 
				AND shipment >= CURDATE()
				AND NOT delivered;

		DELETE t
			FROM travel_top t
			JOIN warehouse w ON w.id = wh_out 
				WHERE t.id = v_travel AND fuente = 0;
	UNTIL v_travel IS NULL 
	END REPEAT;


	SELECT TIMESTAMPADD(DAY, -campaign_life, campaign), campaign
		INTO v_date_start, v_campaign FROM tblContadores;

	CREATE TEMPORARY TABLE item_travel_fixed
	(KEY (wh))
	ENGINE = MEMORY
	SELECT * FROM
	(
		SELECT wh_out wh
			FROM travel_top
				WHERE wh_out <> v_wh
	) t
	GROUP BY wh;

	DROP TEMPORARY TABLE travel_top;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_travel_select` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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_travel_select`(v_wh TINYINT, v_date DATETIME)
BEGIN
	DECLARE v_travel INT;
	DECLARE v_wh_out INT;
	DECLARE v_shipment DATETIME;
	DECLARE v_campaign DATETIME;
	DECLARE v_date_start DATETIME;
	
	DROP TEMPORARY TABLE IF EXISTS travel_top;
	DROP TEMPORARY TABLE IF EXISTS item_travel;

    -- Crea una taula buida travel_top

	CREATE TEMPORARY TABLE travel_top
	(PRIMARY KEY (id))
	ENGINE = MEMORY
		SELECT 0 id, v_wh wh_in, v_wh wh_out, FALSE ok, v_date landing, v_date shipment;

	REPEAT
		SET v_travel = NULL;
    
		-- Va seleccionant registres un a un

		SELECT id, wh_out, shipment, landing
			INTO v_travel, v_wh_out, v_shipment, v_date_start
			FROM travel_top WHERE ok = FALSE LIMIT 1;
            
		-- Marca el registre per a saber que esta revistat

		UPDATE travel_top SET ok = TRUE WHERE id = v_travel;

		-- Concatena travels cap al pasat

		INSERT IGNORE INTO travel_top 
        SELECT id, v_wh, warehouse_id_out, FALSE, IF(v_travel, v_date_start, landing), shipment
            FROM travel
                WHERE warehouse_id = v_wh_out
                    AND IF(v_travel, landing <= v_shipment, landing > v_shipment)
                    AND shipment >= CURDATE() 
					AND delivered = FALSE;

	UNTIL v_travel IS NULL
	END REPEAT;

	DELETE FROM travel_top WHERE id = 0;

	SELECT TIMESTAMPADD(DAY, -campaign_life, campaign), campaign
		INTO v_date_start, v_campaign FROM tblContadores;

    -- Agafa el travel que arriva primer per a cada warehouse

	CREATE TEMPORARY TABLE item_travel
	(KEY (wh))
	ENGINE = MEMORY
	SELECT * FROM (
		SELECT wh_out wh, IF(
			v_date BETWEEN v_date_start AND v_campaign
			AND landing BETWEEN v_date_start AND v_campaign
			,TIMESTAMPADD(DAY, 1, v_campaign)
			,landing
		) landing
			FROM travel_top
				WHERE wh_out <> v_wh
				ORDER BY landing
	) t
	GROUP BY wh;

	SELECT * FROM item_travel;
	DROP TEMPORARY TABLE travel_top;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_travel_testing` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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_travel_testing`(v_wh TINYINT, v_date DATETIME)
BEGIN
	DECLARE v_travel INT;
	DECLARE v_wh_out INT;
	DECLARE v_shipment DATETIME;
	DECLARE v_campaign DATETIME;
	DECLARE v_date_start DATETIME;
   
   

	DROP TEMPORARY TABLE IF EXISTS travel_top;
	DROP TEMPORARY TABLE IF EXISTS item_travel;

    -- Crea una taula buida travel_top
	
    drop temporary table if exists travels_list;
    create temporary table travels_list
    (id integer, shipment date, landing date, warehouse_id int, warehouse_id_out int);
    
	CREATE TEMPORARY TABLE travel_top
	-- (PRIMARY KEY (wh_in,wh_out,landing,shipment)    )
	ENGINE = MEMORY
		SELECT 0 RODA, 0 ORDRE, 0 son_id, 0 id, v_wh wh_in, v_wh wh_out, FALSE ok, v_date landing, v_date shipment;

	SET @rodaeta:= 0;

	REPEAT
		SET v_travel = -1;
        
    
		-- Va seleccionant registres un a un

		SELECT id, wh_out, shipment, landing
			INTO v_travel, v_wh_out, v_shipment, v_date_start
			FROM travel_top WHERE ok = FALSE 
            LIMIT 1;
            
		-- Marca el registre per a saber que esta revistat

		UPDATE travel_top SET ok = TRUE WHERE id = v_travel;

		-- Concatena travels
		SET @ordre := 0;

		INSERT INTO travel_top
        SELECT -7 , @ordre:= @ordre + 1 , v_travel ,id, v_wh, warehouse_id_out, FALSE, IF(v_travel>0, v_date_start, landing), shipment
            FROM travel
                WHERE warehouse_id = v_wh_out
					AND IF(v_travel>0, landing <= v_shipment, landing >= v_shipment)
                    AND shipment >= '2005-01-26' and shipment < '2005-02-28'
					AND delivered = FALSE;
		
		IF (SELECT Count(*) FROM travel_top WHERE RODA = -7) THEN
         SET @rodaeta:= @rodaeta + 1;
         update travel_top set RODA = @rodaeta where RODA = -7;
        end if;
        
        INSERT INTO travels_list 
        SELECT id, shipment, landing, warehouse_id, warehouse_id_out 
        FROM travel 
        WHERE warehouse_id = v_wh_out
					AND IF(v_travel>0, landing <= v_shipment, landing >= v_shipment)
                    AND shipment >= '2005-01-26' and shipment < '2005-02-28'
					AND delivered = FALSE;
		
        
UNTIL v_travel = -1 END REPEAT;
        
        
        
        /*
	select max_count;
		SELECT * FROM travel_top;*/

	/*DELETE FROM travel_top WHERE id = 0;*/
/*
	SELECT TIMESTAMPADD(DAY, -campaign_life, campaign), campaign
		INTO v_date_start, v_campaign FROM tblContadores;*/

    -- Agafa el travel que arriva primer per a cada warehouse

	CREATE TEMPORARY TABLE item_travel
	(KEY (wh))
	ENGINE = MEMORY
	SELECT * FROM (
		SELECT wh_out wh,/* IF(
			v_date BETWEEN v_date_start AND v_campaign
			AND landing BETWEEN v_date_start AND v_campaign
			,TIMESTAMPADD(DAY, 1, v_campaign)
			,landing
		) */ landing
			FROM travel_top
				WHERE wh_out <> v_wh
				ORDER BY landing
	) t
	GROUP BY wh;
    
SELECT * FROM item_travel;
SELECT * FROM travel_top order by RODA, ORDRE;

	DROP TEMPORARY TABLE travel_top;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ListaTicketsEncajados` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ListaTicketsEncajados`(IN intId_Trabajador int)
BEGIN 

SELECT Agencia,Consignatario, ti.Id_Ticket, ts.worker Id_Trabajador,IFNULL(ncajas,0) AS ncajas,
IFNULL(nbultos,0) AS nbultos,IFNULL(notros,0) AS notros,code AS Estado
FROM Tickets ti
INNER JOIN Consignatarios ON ti.Id_Consigna = Consignatarios.Id_consigna
INNER JOIN Agencias ON ti.Id_Agencia = Agencias.Id_Agencia
LEFT JOIN (select Ticket_Id,count(*) as ncajas  from expeditions where Id_Article=94 group by ticket_id) sub1 on ti.Id_Ticket=sub1.Ticket_Id
LEFT JOIN (select Ticket_Id,count(*) as nbultos  from expeditions where Id_Article is null group by ticket_id) sub2 on ti.Id_Ticket=sub2.Ticket_Id
LEFT JOIN (select Ticket_Id,count(*) as notros  from expeditions where Id_Article >0 group by ticket_id) sub3 on ti.Id_Ticket=sub3.Ticket_Id
INNER JOIN vn.ticketState ts ON ti.Id_ticket = ts.ticket
WHERE  ti.Fecha=curdate() and
ts.worker=intId_Trabajador
group by ti.Id_Ticket;

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

set @cliente := 0;
set @saldo := 0;

Select Id_Cliente, Cliente from
Clientes
join
(select distinct Id_Cliente
from Facturas
where Fecha > '2015-01-01') cli using(Id_Cliente)
left join
(
select distinct Id_Cliente 
from
(
select Fecha
	, @saldo := IF(@cliente = Id_Cliente,  @saldo + Importe, Importe) Saldo
	, @cliente := Id_Cliente as Id_Cliente
from
(
select Id_Cliente, Fecha, Importe from

(
select Id_Cliente, -1 *  Importe Importe, Fecha
from Facturas
union all
select Id_Cliente, Entregado, Fechacobro
from Recibos
) sub
order by Id_Cliente, Fecha
) sub2
) sub3
where Saldo > -1
and Fecha > '2015-01-01'

) sub4 using(Id_Cliente)
where sub4.Id_Cliente 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 `manaByClient` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `manaByClient`()
BEGIN

	DECLARE vLastDated DATE;
    DECLARE vLastDatedDayAfter DATE;
    
    SELECT MAX(dated), TIMESTAMPADD(DAY,1,MAX(dated)) 
		INTO vLastDated, vLastDatedDayAfter
        FROM bs.manaCustomer;
    
    SELECT t.CodigoTrabajador, c.Id_Cliente, c.Cliente, CAST(sum(m.mana) AS DECIMAL(10,2)) AS Mana
		FROM vn2008.Clientes c
			JOIN bs.mana_spellers ms ON ms.Id_Trabajador = c.Id_Trabajador
			JOIN vn2008.Trabajadores t ON t.Id_Trabajador = c.Id_Trabajador
			JOIN
            (
				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 (37, 39)
						AND date(t.Fecha) BETWEEN vLastDatedDayAfter AND CURDATE()
						
				UNION ALL

				SELECT  r.Id_Cliente, - Entregado
					FROM vn2008.Recibos r
					WHERE Id_Banco = 66
						AND Fechacobro BETWEEN vLastDatedDayAfter AND CURDATE()
								
				UNION ALL
								
				SELECT g.Id_Cliente, g.Importe
					FROM vn2008.Greuges g
					WHERE Greuges_type_id = 3
						AND Fecha BETWEEN vLastDatedDayAfter AND CURDATE()
				
				UNION ALL

				 SELECT Id_Cliente, mana
					FROM bs.manaCustomer mc
					WHERE dated = vLastDated
                    
			) m ON m.Id_Cliente = c.Id_Cliente
            GROUP BY c.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 `manaEraser` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `manaEraser`(vTicket INT)
BEGIN

	DECLARE vComponentOld INT;
    DECLARE vComponentNew INT;

	SELECT Id_Componente
			INTO vComponentOld
        FROM tarifa_componentes
        WHERE Componente = 'maná';

	SELECT Id_Componente
			INTO vComponentNew
        FROM tarifa_componentes
        WHERE Componente = 'rebaja manual';
        
	UPDATE Movimientos_componentes mc
			JOIN Movimientos m using(Id_Movimiento)
		SET mc.Id_Componente = vComponentNew
		WHERE mc.Id_Componente = vComponentOld
			AND m.Id_Ticket = 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 `manaRequery` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `manaRequery`(worker INTEGER)
BEGIN

	DECLARE workerIsExcluded BOOLEAN;
	DECLARE MyFechaDesde DATE;

	SELECT COUNT(*) INTO workerIsExcluded
		FROM bs.mana_spellers_excluded
		WHERE Id_Trabajador = worker;
    
	IF NOT workerIsExcluded THEN

		SELECT max(dated) INTO MyFechaDesde 
			FROM bs.manaCustomer;

		REPLACE bs.mana_spellers (Id_Trabajador, used)
			SELECT worker, sum(mana) FROM 
			(
				SELECT Cantidad * Valor as mana
					FROM vn2008.Tickets t
						JOIN Consignatarios cs using(Id_Consigna)
						JOIN Clientes c on c.Id_Cliente = cs.Id_Cliente
						JOIN Movimientos m using(Id_Ticket)
						JOIN Movimientos_componentes mc using(Id_Movimiento)
					WHERE c.Id_Trabajador =  worker AND Id_Componente IN (39, 37) -- maná auto y maná
						AND Fecha > MyFechaDesde and Fecha <= CURDATE()

				UNION ALL

				SELECT  - Entregado
					FROM Recibos r
						JOIN Clientes c using(Id_Cliente)
					WHERE c.Id_Trabajador = worker AND Id_Banco = 66
						AND Fechacobro > MyFechaDesde
				
				UNION ALL
				
				SELECT g.Importe
					FROM Greuges g
						JOIN Clientes c using(Id_Cliente)
					WHERE c.Id_Trabajador = worker AND Greuges_type_id = 3 -- Maná
						AND Fecha > MyFechaDesde and Fecha < CURDATE()
				
				UNION ALL
				
				SELECT mana
					FROM bs.manaCustomer mc
						JOIN vn2008.Clientes c ON c.Id_Cliente = mc.Id_Cliente
					WHERE c.Id_Trabajador = worker AND dated = MyFechaDesde
			) sub;

	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 `mana_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 `mana_list`(IN str VARCHAR(3))
BEGIN

DECLARE idT INT;

IF ASCII(str) between 48 and 57 THEN  -- el chr(48) es el 0 y el chr(57) es el 9. De ese modo se comprueba si es un numero o un carácter de texto

	SET idT = cast(str as signed);
    
ELSE

	SELECT Id_Trabajador INTO idT
    FROM Trabajadores 
    WHERE CodigoTrabajador = str;
    
END IF;


SELECT * FROM 
(
SELECT Id_Ticket
     , Alias
     , t.Fecha as FechaTicket
     , m.odbc_date as FechaAccion
     , Id_Article
     , CONCAT(IF(Id_Componente = 39, 'Auto: ',''),Concepte) Concepte
     , Cantidad
     , round(Valor,2) as Valor
     , round(Cantidad * Valor,2) as MANA 
              FROM Movimientos_componentes mc 
              JOIN Movimientos m using(Id_Movimiento)
              JOIN Tickets t using(Id_Ticket) 
              JOIN Consignatarios cs using(Id_Consigna) 
              JOIN Clientes c on c.Id_Cliente = cs.Id_Cliente 
              WHERE c.Id_Trabajador = idT 
				AND Id_Componente  IN (39, 37) 
                and t.Fecha > TIMESTAMPADD(WEEK,-1,CURDATE())
              
              UNION ALL
              
SELECT NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
              
              UNION ALL
              
SELECT c.Id_Cliente, Cliente, r.FechaCobro, r.odbc_date, NULL, 'cobro', NULL, NULL, - Entregado
			  FROM Recibos r
              JOIN Clientes c using(Id_Cliente)
              WHERE Id_Banco = 66 -- Caja de maná
              AND c.Id_Trabajador = idT
              
              UNION ALL
              
SELECT NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
              
              UNION ALL            
              
SELECT c.Id_Cliente, Cliente, g.Fecha, g.odbc_date, NULL, Comentario, NULL, NULL, g.Importe
        FROM Greuges g
        JOIN Clientes c using(Id_Cliente)
        WHERE Greuges_type_id = 3 -- Maná
        AND c.Id_Trabajador = idT
        ) t1
ORDER BY FechaAccion 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 `mana_requery` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_requery`()
BEGIN

DECLARE MyFechaDesde DATE;
DECLARE LastDated DATE;

SELECT TIMESTAMPADD(DAY,1,max(dated)), max(dated) INTO MyFechaDesde, LastDated
FROM bs.manaCustomer;

UPDATE bs.mana_spellers

LEFT JOIN

(
	SELECT Id_Trabajador, sum(mana) as mana FROM 

	(
		SELECT c.Id_Trabajador, Cantidad * Valor as mana
			FROM Tickets t
				JOIN Consignatarios cs using(Id_Consigna)
				JOIN Clientes c on c.Id_Cliente = cs.Id_Cliente
				JOIN Movimientos m using(Id_Ticket)
				JOIN Movimientos_componentes mc using(Id_Movimiento)
			WHERE Id_Componente IN (39, 37) -- maná auto y maná
				AND Fecha between MyFechaDesde and CURDATE()

		UNION ALL

		SELECT c.Id_Trabajador, - Entregado
			FROM Recibos r
				JOIN Clientes c using(Id_Cliente)
			WHERE Id_Banco = 66
				AND Fechacobro between MyFechaDesde and CURDATE()
        
        UNION ALL
        
        SELECT c.Id_Trabajador, g.Importe
			FROM Greuges g
				JOIN Clientes c using(Id_Cliente)
			WHERE Greuges_type_id = 3 -- Maná
				AND Fecha between MyFechaDesde and CURDATE()
        
		UNION ALL
        
        SELECT c.Id_Trabajador, mana
			FROM bs.manaCustomer mc
				JOIN vn2008.Clientes c ON c.Id_Cliente = mc.Id_Cliente
			WHERE dated = LastDated
	) sub

	GROUP BY Id_Trabajador

) m using(Id_Trabajador)

SET used = IFNULL(m.mana,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 `massiveTicket` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `massiveTicket`(
	IN dateFrom DATE, IN dateTo DATE, IN customerId INT, OUT newTicketId INT)
BEGIN
/**
 * Genera un nuevo ticket con los movimientos correspondientes a los parámetros
 *
 * @param dateFrom Fecha mínima para los tickets
 * @param dateTo Fecha máxima para los tickets
 * @param customerId Cliente
 * 
 * @return newTicketId Nuevo numero de ticket
 **/

	DECLARE inventoryWarehouse INT DEFAULT 13;
	DECLARE defaultCompany INT DEFAULT 442;
	DECLARE defaultWorker INT DEFAULT 20;

	CALL vn.ticketCreate ( customerId
				, CURDATE()
                , inventoryWarehouse
                , defaultCompany
                , NULL
                , NULL
                , NULL
                , CURDATE()
                , newTicketId);

	INSERT INTO Movimientos( Id_Ticket
						   , Id_Article
						   , Concepte
						   , Preu
						   , Descuento
						   , Cantidad)
						   
		SELECT newTicketId
				 , Id_Article
				 , Concepte
				 , Preu
				 , Descuento
				 , Cantidad
			FROM Movimientos m
			JOIN Tickets t ON m.Id_Ticket = t.Id_Ticket
			WHERE Id_Cliente = customerId
				AND t.Fecha BETWEEN dateFROM AND DAYEND(dateTO);
					
	SELECT newTicketId;

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

/*DECLARE lngLASTID BIGINT;*/

-- Caso sencillo

INSERT INTO Mensajes(Mensaje, Fecha, Remitente, Destinatario)
VALUES(strMSG, NOW(), idREM, idDES);

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

SELECT Id_Trabajador, AVG(billsec) as Duracion, days.Fecha, Hora, SUM(Recibidas) as Entrantes, SUM(Emitidas) as Salientes
FROM
(
SELECT Id_Trabajador, billsec, 1 as Recibidas, NULL as Emitidas, date(calldate) as Fecha, hour(calldate) as Hora
FROM Trabajadores T
INNER JOIN cdr C ON C.dstchannel LIKE CONCAT('%', T.extension, '%')
LEFT JOIN v_phonebook A ON A.Telefono = C.src 
WHERE calldate >= datFEC
UNION ALL
SELECT Id_Trabajador, billsec, NULL as Recibidas, 1 as Emitidas, date(calldate), hour(calldate)
FROM Trabajadores T
INNER JOIN cdr C ON C.src = T.extension
LEFT JOIN v_phonebook A ON A.Telefono = C.dst
WHERE calldate >= datFEC
) llamadas 
INNER JOIN Permisos USING(Id_Trabajador)
INNER JOIN
(
SELECT DISTINCT Fecha FROM Tickets WHERE Fecha >= datFEC
) days USING(Fecha)
WHERE Id_Grupo = 6
GROUP BY Id_Trabajador, Fecha, Hora;

/*
SELECT Id_Trabajador, SUM(dur_in) dur_in, SUM(dur_out) dur_out, llamadas.Fecha,YEAR(llamadas.Fecha) `year`, 
MONTH(llamadas.Fecha) `month`,WEEK(llamadas.Fecha,7) `week`, Hora, SUM(Recibidas) as Entrantes, SUM(Emitidas) as Salientes
FROM
(
SELECT Id_Trabajador, billsec dur_in, NULL dur_out, 1 as Recibidas, NULL as Emitidas, date(calldate) as Fecha, hour(calldate) as Hora
FROM Trabajadores T
INNER JOIN cdr C ON C.dstchannel LIKE CONCAT('%', T.extension, '%')
WHERE calldate >= CURDATE()
UNION ALL
SELECT Id_Trabajador,NULL dur_in, billsec dur_out, NULL as Recibidas, 1 as Emitidas, date(calldate), hour(calldate)
FROM Trabajadores T
INNER JOIN cdr C ON C.src = T.extension
WHERE calldate >= CURDATE()
) llamadas 
INNER JOIN Permisos USING(Id_Trabajador)
WHERE Id_Grupo = 6
GROUP BY Id_Trabajador, Fecha, Hora;
*/
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `msg` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `msg`(IN memTXT VARCHAR(255), IN idREM INTEGER, idDES INTEGER)
BEGIN
  DECLARE last_ID INTEGER;
  DECLARE codDES CHAR(3);
  
  SELECT CodigoTrabajador INTO codDES FROM Trabajadores WHERE Id_Trabajador = idDES;

  INSERT INTO Mensajes(Mensaje,Fecha,Remitente,Destinatario)
             VALUES(memTXT, NOW(),idREM, idDES);
             
  SELECT LAST_INSERT_ID() INTO last_ID;
    
   
  INSERT INTO Incidencias(Incidencia,Id_Trabajador,Destino,Fecha,Fecha_Mod) 
              VALUES (CONCAT('@@ ',last_ID),idREM,codDES,NOW(),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 `nest_brother_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 `nest_brother_add`(
	 vTable VARCHAR(45)
	,vNewBrother VARCHAR(45)
	,vOldBrotherId INT
)
BEGIN
	DECLARE vMyRight INT;
    DECLARE vSchema VARCHAR(255) DEFAULT SCHEMA();

	DROP TEMPORARY TABLE IF EXISTS aux;
	CREATE TEMPORARY TABLE aux
		SELECT 0 as rgt;

	CALL util.exec (sql_printf (
		'UPDATE vn2008.aux SET rgt = (SELECT rgt FROM %t.%t WHERE id = %v)'
		,vSchema
		,vTable
		,vOldBrotherId
	));

	SELECT rgt INTO vMyRight FROM aux;

	DROP TEMPORARY TABLE aux;

	CALL util.exec (sql_printf (
		'UPDATE %t.%t SET rgt = rgt + 2 WHERE rgt > %v ORDER BY rgt DESC'
        ,vSchema
        ,vTable
        ,vMyRight
	));

	CALL util.exec (sql_printf (
		'UPDATE %t.%t SET lft = lft + 2 WHERE lft > %v ORDER BY lft DESC'
        ,vSchema
        ,vTable
        ,vMyRight
	));              

	CALL util.exec (sql_printf (
		'INSERT INTO %t.%t (name, lft, rgt) VALUES(%v, %v + 1, %v + 2)'
        ,vSchema
		,vTable
		,vNewBrother
		,vMyRight
		,vMyRight
	));
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `nest_child_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 `nest_child_add`(
	 vTable VARCHAR(45)
	,vChild VARCHAR(45)
	,vFatherId INT
)
BEGIN
	DECLARE vMyLeft INT;
    DECLARE vSchema VARCHAR(255) DEFAULT SCHEMA();

	DROP TEMPORARY TABLE IF EXISTS aux;
	CREATE TEMPORARY TABLE aux
		SELECT 0 as lft;

	CALL util.exec (sql_printf (
		'UPDATE vn2008.aux SET lft = (SELECT lft FROM %t.%t WHERE id = %v)'
        ,vSchema
		,vTable
		,vFatherId
	));

	SELECT lft INTO vMyLeft FROM aux;

	DROP TEMPORARY TABLE aux;

	CALL util.exec (sql_printf (
		'UPDATE %t.%t SET rgt = rgt + 2 WHERE rgt > %v ORDER BY rgt DESC'
        ,vSchema
		,vTable
		,vMyLeft
	));

	CALL util.exec (sql_printf (
		'UPDATE %t.%t SET lft = lft + 2 WHERE lft > %v ORDER BY lft DESC'
        ,vSchema
        ,vTable
        ,vMyLeft
	));               

	CALL util.exec (sql_printf (
		'INSERT INTO %t.%t(name, lft, rgt) VALUES(%v, %v + 1, %v + 2)'
        ,vSchema
		,vTable
		,vChild
		,vMyLeft
		,vMyLeft
	));
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `nest_delete` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nest_delete`(
	 vTable VARCHAR(45)
    ,vNodeId INT
)
BEGIN
	DECLARE vMyRight INT;
	DECLARE vMyLeft INT;
	DECLARE vMyWidth INT;
    DECLARE vSchema VARCHAR(255) DEFAULT SCHEMA();

	DROP TEMPORARY TABLE IF EXISTS aux;
	CREATE TEMPORARY TABLE aux
		SELECT 0 AS rgt, 0 AS lft, 0 AS wdt;

	CALL util.exec (sql_printf (
		'UPDATE vn2008.aux a JOIN %t.%t t SET a.rgt = t.rgt, a.lft = t.lft, a.wdt = t.rgt - t.lft + 1 WHERE t.id = %v'
        ,vSchema
		,vTable
		,vNodeId
	));

	SELECT rgt, lft, wdt INTO vMyRight, vMyLeft, vMyWidth FROM aux;

	DROP TEMPORARY TABLE aux;

	CALL util.exec (sql_printf (
		'DELETE FROM %t.%t WHERE lft BETWEEN %v AND %v'
        ,vSchema
		,vTable
		,vMyLeft
		,vMyRight
	));

	CALL util.exec (sql_printf (
		'UPDATE %t.%t SET rgt = rgt - %v WHERE rgt > %v ORDER BY rgt'
        ,vSchema
		,vTable
		,vMyWidth
		,vMyRight
	));

	CALL util.exec (sql_printf (
		'UPDATE %t.%t SET lft = lft - %v WHERE lft > %v ORDER BY lft'
        ,vSchema
		,vTable
		,vMyWidth
		,vMyRight
	));
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `nest_leaves` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nest_leaves`(
	 vTable VARCHAR(20)
    ,vLinesTable VARCHAR(40)
    ,vNestId VARCHAR(40)
    ,vGap INT
    ,vShouldShow BOOL
)
BEGIN
    DECLARE vSchema VARCHAR(255) DEFAULT SCHEMA();

	DROP TEMPORARY TABLE IF EXISTS tmp.nest;

	-- Se llama al procedimiento que genera el arbol
    
	CALL nest_tree(vTable, vGap, FALSE);

	-- Se añade un campo para el conteo de hojas
    
	ALTER TABLE tmp.nest
		ADD leaves INT,
		ADD time DATETIME;

	-- Añadimos la hora

	CALL util.exec (sql_printf (
		'UPDATE tmp.nest n
			JOIN  %t.%t s using(id)
			SET n.time = s.odbc_date'
        ,vSchema
        ,vTable
	));

	-- Actualizamos el campo leaves para los nodos que tienen asociados

	CALL util.exec (sql_printf (
		'update tmp.nest n
		join 
		(
			 select %t as id, count(*) as leaves
			 from %t.%t
			 group by %t
		) s using(id)
		set n.leaves = s.leaves'
        ,vNestId
        ,vSchema
		,vLinesTable
		,vNestId
	));

	-- Actualizamos todos los nodos con la suma de las hojas de los hijos

	drop temporary table if exists tmp.nest2;

	create temporary table tmp.nest2
		select * from tmp.nest;

	drop temporary table if exists tmp.nest3;

	create temporary table tmp.nest3
		select * from tmp.nest;

	update tmp.nest
		join
		(
			select n.id, sum(n2.leaves) leaves
				from tmp.nest3 n
					join tmp.nest2 n2 on n2.lft between n.lft and n.rgt
				group by n.id
		) sub on sub.id = nest.id
		set nest.leaves = ifnull(sub.leaves,0);

	drop temporary table tmp.nest2;

	IF vShouldShow THEN
		SELECT * FROM tmp.nest;
	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 `nest_move` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nest_move`(
	 strTABLE VARCHAR(45)
	,idNODE INT
	,idFATHER INT
)
BEGIN
	DECLARE myRight INT;
	DECLARE myLeft INT;
	DECLARE myWidth INT;
	DECLARE fatherRight INT;
	DECLARE fatherLeft INT;
	DECLARE gap INT;
    DECLARE vSchema VARCHAR(255) DEFAULT SCHEMA();

	DROP TEMPORARY TABLE IF EXISTS aux;
	CREATE TEMPORARY TABLE aux
		SELECT 0 as rgt, 0 as lft, 0 as wdt, 0 as frg, 0 as flf;

	-- Averiguamos el ancho de la rama

	CALL util.exec (sql_printf (
		'UPDATE vn2008.aux a JOIN %t.%t t SET  a.wdt = t.rgt - t.lft +1
		WHERE t.id = %v'
        ,vSchema
        ,strTABLE
		,idNODE
	));

	-- Averiguamos la posicion del nuevo padre

	CALL util.exec (sql_printf (
		'UPDATE vn2008.aux a JOIN %t.%t t SET a.frg = t.rgt, a.flf = t.lft WHERE t.id = %v'
        ,vSchema
		,strTABLE
		,idFATHER
	));

	SELECT wdt, frg, flf INTO  myWidth, fatherRight, fatherLeft FROM aux;

	-- 1º Incrementamos los valores de todos los nodos a la derecha del punto de inserción (fatherRight) , para hacer sitio

	CALL util.exec (sql_printf (
		'UPDATE %t.%t SET rgt = rgt + %v WHERE rgt >= %v ORDER BY rgt DESC'
        ,vSchema
		,strTABLE
		,myWidth
		,fatherRight
	));  

	CALL util.exec (sql_printf (
		'UPDATE %t.%t SET lft = lft + %v WHERE lft >= %v ORDER BY lft DESC'
		,vSchema
		,strTABLE
		,myWidth
		,fatherRight
	));  

	-- Es preciso recalcular los valores del nodo en el caso de que estuviera a la derecha del nuevo padre

	CALL util.exec (sql_printf (
		'UPDATE vn2008.aux a JOIN %t.%t t SET a.rgt = t.rgt, a.lft = t.lft WHERE t.id = %v'
		,vSchema
		,strTABLE
		,idNODE
	));

	SELECT lft, rgt, frg - lft INTO  myLeft, myRight, gap FROM aux;

	-- 2º Incrementamos el valor de todos los nodos a trasladar hasta alcanzar su nueva posicion

	CALL util.exec (sql_printf (
		'UPDATE %t.%t SET lft = lft + %v WHERE lft BETWEEN %v AND %v ORDER BY lft DESC'
		,vSchema
		,strTABLE
		,gap 
		,myLeft
		,myRight
	));       

	CALL util.exec (sql_printf (
		'UPDATE %t.%t SET rgt = rgt + %v WHERE rgt BETWEEN %v AND %v ORDER BY rgt DESC'
		,vSchema
		,strTABLE
		,gap 
		,myLeft
		,myRight
	));

	-- 3º Restaremos a todos los nodos resultantes, a la derecha de la posicion arrancada el ancho de la rama escindida

	CALL util.exec (sql_printf (
		'UPDATE %t.%t SET lft = lft - %v WHERE lft > %v  ORDER BY lft'
		,vSchema
		,strTABLE
		,myWidth
		,myLeft
	));

	CALL util.exec (sql_printf (
		'UPDATE %t.%t SET rgt = rgt - %v WHERE rgt > %v ORDER BY rgt'
		,vSchema
		,strTABLE
		,myWidth
		,myRight
	));

	DROP TEMPORARY TABLE aux;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `nest_query` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nest_query`(strTABLE VARCHAR(45))
BEGIN
	DECLARE v_max_depth INT;
	DECLARE v_current_depth INT;
    DECLARE vSchema VARCHAR(255) DEFAULT SCHEMA();

	DROP TEMPORARY TABLE IF EXISTS tmp.nest_depth;
	DROP TEMPORARY TABLE IF EXISTS tmp.nest_depth_aux;

	-- Calculamos el nivel de profundidad para cada item

	CALL util.exec (sql_printf (
		'CREATE TEMPORARY TABLE tmp.nest_depth
			SELECT node.id node_id, COUNT(parent.id) - 1 as depth
				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'
        ,vSchema
		,strTABLE
        ,vSchema
        ,strTABLE
	));

	SELECT max(depth) FROM tmp.nest_depth INTO v_max_depth;
	SET v_current_depth = 2;

	CREATE TEMPORARY TABLE tmp.nest_depth_aux
	SELECT * FROM tmp.nest_depth;

	-- Vamos a hacer consultas anidadas para obtener una consulta de dos entradas

	DROP TEMPORARY TABLE IF EXISTS tmp.nest;
	DROP TEMPORARY TABLE IF EXISTS tmp.nest_aux;

	-- Primera tabla, con el nivel 0
	CALL util.exec (sql_printf (
		'CREATE TEMPORARY TABLE tmp.nest
			SELECT  child.id nest_id
				   ,child.lft
				   ,child.rgt
				   ,parent.id as ID0
				   ,parent.name as PARENT0
				   ,child.id as ID1
				   ,child.name as PARENT1
				FROM %t.%t AS parent
					JOIN tmp.nest_depth nd ON nd.node_id = parent.id AND nd.depth = 0,
					%t.%t AS child
					JOIN tmp.nest_depth_aux ndc ON ndc.node_id = child.id AND ndc.depth = 1
				WHERE child.lft BETWEEN parent.lft + 1 AND parent.rgt
				ORDER BY parent.lft'
        ,vSchema
		,strTABLE
        ,vSchema
		,strTABLE
	));

	CREATE TEMPORARY TABLE tmp.nest_aux 
		SELECT * FROM tmp.nest;

	WHILE v_current_depth <= v_max_depth
    DO
		DROP TEMPORARY TABLE IF EXISTS tmp.nest;

		CALL util.exec (sql_printf (
			'CREATE TEMPORARY TABLE tmp.nest
				SELECT parent.*
						,child.id as %v
						,child.name as %v
						,child.id as ID
					FROM tmp.nest_aux AS parent
						LEFT JOIN %t.%t AS child ON child.lft BETWEEN parent.lft + 1 AND parent.rgt 
						LEFT JOIN tmp.nest_depth_aux ndc ON ndc.node_id = child.id 
					WHERE IFNULL(ndc.depth,%v) = %v
					ORDER BY parent.lft'
			,CONCAT('ID',v_current_depth)
			,CONCAT('PARENT',v_current_depth)
			,vSchema
			,strTABLE                        
			,v_current_depth
			,v_current_depth
		));

		-- Actualizamos lft y rgt

		CALL util.exec (sql_printf (
			'UPDATE tmp.nest
				JOIN %t.%t AS child ON child.id = nest.ID
				SET nest.lft = child.lft, nest.rgt = child.rgt, nest_id = nest.ID'
			,vSchema
			,strTABLE                        
		));

		ALTER TABLE tmp.nest DROP COLUMN ID;

		DROP TEMPORARY TABLE IF EXISTS tmp.nest_aux;
		CREATE TEMPORARY TABLE tmp.nest_aux 
			SELECT * FROM tmp.nest;
		
		SET v_current_depth = v_current_depth + 1;
	END WHILE;

	-- Eliminamos los campos duplicados
	SET v_current_depth = 0;

	WHILE v_current_depth <= v_max_depth
    DO
		SET @id = 0;

		CALL util.exec (sql_printf (
			'UPDATE tmp.nest_aux
				SET %t = IF(@id = %t, NULL, %t), 							
				ID0 = IF(@id := %t, ID0, ID0),
				%t = IF(length(%t), %t,NULL)'
			,CONCAT('PARENT',v_current_depth)
			,CONCAT('ID',v_current_depth)
			,CONCAT('PARENT',v_current_depth)
			,CONCAT('ID',v_current_depth)
			,CONCAT('ID',v_current_depth)
			,CONCAT('PARENT',v_current_depth)
			,CONCAT('ID',v_current_depth)
		));

		SET v_current_depth = v_current_depth + 1;
	END WHILE;

	SELECT * FROM tmp.nest_aux;

	-- Limpieza

	DROP TEMPORARY TABLE IF EXISTS
		tmp.nest_aux,
        tmp.nest,
        tmp.nest_depth_aux,
        tmp.nest_depth;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `nest_sons_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 `nest_sons_list`(
	 vId INT
	,vTable VARCHAR(45)
    ,vShouldShow BOOLEAN
)
BEGIN
/**
 * Devuelve un recordset con los ID de todos los nodos que
 * cuelgan del nodo que se pasa como parámetro
 */
    DECLARE vSchema VARCHAR(255) DEFAULT SCHEMA();

	DROP TEMPORARY TABLE IF EXISTS tmp.nest_sons;
	CALL util.exec (sql_printf (
		'CREATE TEMPORARY TABLE tmp.nest_sons
			SELECT DISTINCT node.id node_id
				FROM %t.%t AS node
					JOIN %t.%t AS parent ON node.lft between parent.lft and parent.rgt
				WHERE parent.id = %v
				ORDER BY node.lft'
        ,vSchema
		,vTable
        ,vSchema
		,vTable
		,vId
	));
    
	IF vShouldShow THEN
		SELECT * FROM tmp.nest_sons;
	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 `nest_tree` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `nest_tree`(
	 vTable VARCHAR(20)
	,vGap INT
    ,vShouldShow BOOL
)
BEGIN
    DECLARE vSchema VARCHAR(255) DEFAULT SCHEMA();

	DROP TEMPORARY TABLE IF EXISTS tmp.nest;
	CALL util.exec (sql_printf (
		'CREATE TEMPORARY TABLE tmp.nest
			SELECT node.id
					,CONCAT( REPEAT(REPEAT(" ",%v), COUNT(parent.id) - 1), node.name) AS name
					,node.lft
					,node.rgt
					,COUNT(parent.id) - 1 as 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'
        ,vGap
        ,vSchema
		,vTable
        ,vSchema
		,vTable
	));

	IF vShouldShow THEN
		SELECT * FROM tmp.nest;
	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 `newItem` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `newItem`(IN vTicket INTEGER, IN vVolume INTEGER, IN vQuantity INTEGER)
BEGIN
	
	DECLARE vLandingWarehouse INT;
	DECLARE vLandingDate DATE;
    DECLARE vShipmentDate DATE;
    DECLARE vTravel INT;
    DECLARE vEntry INT;

	SELECT warehouse_id, Fecha, landing INTO vLandingWarehouse, vShipmentDate, vLandingDate FROM Tickets WHERE Id_Ticket = vTicket;

	-- seleccionamos travel
	SELECT id, Id_Entrada INTO vTravel, vEntry
		FROM travel t LEFT JOIN Entradas e ON t.id = e.travel_id
        WHERE t.landing = vLandingDate AND t.shipment = vShipmentDate AND t.warehouse_id_out = vLandingWarehouse AND t.warehouse_id = vWarehouse
			AND t.delivered = FALSE ; -- agency ??
	
    -- creamos el travel si es necesario
    IF NOT vTravel THEN
		INSERT INTO travel (shipment, landing, warehouse_id, warehouse_id_out, agency_id)
			VALUES (vShipmentDate, vLandingDate, vLandingWarehouse, vShipmentWarehouse, a);
		SELECT LAST_INSERT_ID() INTO vTravel;
    END IF;
    
    -- creamos la Entrada si es necesario
	IF NOT vEntry THEN
		INSERT INTO Entradas (Id_Proveedor, travel_id)
				VALUES (13, vTravel); -- proveedor 'MOVIMIENTO ALMACEN'
		SELECT LAST_INSERT_ID() INTO vEntry;
	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 `niching` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `niching`(IN i_ini INT, IN i_end INT
, IN i_bal INT, IN i_col INT )
BEGIN

DECLARE i INT(5);
DECLARE j INT(5);

DROP TEMPORARY TABLE IF EXISTS labels;

CREATE TEMPORARY TABLE `labels`
  (`label` VARCHAR(15) NULL)
ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

WHILE i_ini <= i_end DO

    SET i = i_bal;

    WHILE i > 0 DO



      SET j = i_col;
      IF j = 0 THEN
          INSERT INTO labels(label)
          VALUES (CONCAT(i_ini,IF(i=0,' ',char(64 + i))));
      ELSE

        WHILE j > 0 DO

          INSERT INTO labels(label)
          VALUES (CONCAT(i_ini,char(64 + i), j));

          SET j = j - 1;

       END WHILE;
    END IF;
    SET i = i - 1;

    END WHILE;

SET i_ini = i_ini + 1;

END WHILE;

SELECT CONCAT('*',label,'*') as label, label as id FROM labels;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `notify_passport` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `notify_passport`(
	IN vItemFk INT,
    IN vStickers SMALLINT,
    IN vPacking SMALLINT,
    IN vBuyFk INT
)
BEGIN
	INSERT INTO vn2008.mail(`subject`,`text`,`to`) 
		SELECT 'Solicitar pasaporte',
				CONCAT(
					'Etiquetas: ', IFNULL(vStickers, 0),
                    ', Packing: ', IFNULL(vPacking, 0),
                    ', Nombre: ', IFNULL(a.Article, 0),
                    ', buy_edi: ', IFNULL(be.id, 0),
                    ', Nombre botánico: ', IFNULL(g.latin_genus_name, ''), ' ', IFNULL(s.latin_species_name, ''),
                    ', Productor: ',IFNULL(es.company_name, IFNULL(p.`name`, ''))
				)
				,'ekt@verdnatura.es' 
			FROM Articles a
				LEFT JOIN Articles_botanical ab ON ab.Id_Article = a.Id_Article
				LEFT JOIN edi.genus g ON g.genus_id = ab.genus_id
				LEFT JOIN edi.specie s ON IFNULL(s.specie_id, ab.specie_id) = ab.specie_id
				LEFT JOIN producer p ON p.producer_id = a.producer_id
				LEFT JOIN Compres c ON c.Id_Compra = vBuyFk
				LEFT JOIN buy_edi be ON c.buy_edi_id = be.id
				LEFT JOIN edi.supplier es ON es.supplier_id = be.pro
			WHERE a.Id_Article = vItemFk; 
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `pay` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `pay`(IN datFEC DATE
                      , IN idPROV INT
                      , IN dblIMPORTE DOUBLE
                      , IN idMONEDA INT 
                      , IN dblDIVISA DOUBLE
                      , IN idCAJA INT
                      , IN idPAYMET INT
                      , IN dblGASTOS DOUBLE
                      , IN strCONCEPTO VARCHAR(40)
                      , IN idEMP INT)
BEGIN

               
-- Registro en la tabla Cajas
INSERT INTO Cajas ( Concepto
				  , Serie
                  , Numero
                  , Salida
                  , Cajafecha
                  , Partida
                  , Id_Banco
                  , Id_Trabajador
                  ,empresa_id 
                  ,conciliado) 
                  
SELECT		      CONCAT('n/pago a ', Proveedor) 
				 , 'R' 
                 , idPROV 
                 , dblIMPORTE 
                 , datFEC
                 , 1
                 , idCAJA
                 , 20
                 , idEMP
                 , 1
FROM Proveedores
WHERE Id_Proveedor = idPROV;


-- Registro en la tabla pago
INSERT INTO pago(fecha
               , id_proveedor
               , importe
               , id_moneda
               , divisa
               , id_banco
               , pay_met_id
               , g_bancarios
               , concepte
               , empresa_id)
               
         VALUES(datFEC
               , idPROV
               , dblIMPORTE
               , idMONEDA
               , IF(dblDIVISA = 0, NULL, dblDIVISA)
               , idCAJA
               , idPAYMET
               , dblGASTOS
               , strCONCEPTO
               , idEMP);
               
SELECT LAST_INSERT_ID() as pago_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 `percentil` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `percentil`()
BEGIN

DECLARE max_range INT;

DROP TEMPORARY TABLE IF EXISTS previa;

CREATE TEMPORARY TABLE previa
SELECT @posicion:= @posicion +1 as Posicion, Id_Cliente, Total FROM (
SELECT Id_Cliente, Total FROM (
SELECT Id_Cliente, SUM(Importe) as Total
FROM Facturas
INNER JOIN Clientes USING(Id_Cliente)
INNER JOIN (SELECT @posicion := 0) sub_pos
WHERE invoice
AND YEAR(Fecha) = YEAR(CURDATE())
GROUP BY Id_Cliente) sub
ORDER BY Total 
) sub2;

SELECT COUNT(*) INTO max_range FROM previa;

UPDATE Clientes SET percentil = 0;

UPDATE Clientes INNER JOIN previa USING(Id_Cliente) 
SET Clientes.percentil = ROUND(Posicion *100 / max_range,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 `precio` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `precio`( IN id_cli INT, id_art INT, id_wh INT )
BEGIN 
DECLARE tarifa,descompte, packin,groupin,caj,minimo, id_compra INT DEFAULT 0;
DECLARE importe_min, importe,bonus FLOAT DEFAULT NULL;

SELECT PrecioEspecial INTO importe FROM PreciosEspeciales WHERE Id_Cliente = id_cli AND Id_Article = id_art;

IF importe IS NULL THEN
    SELECT `Min`, PVP INTO minimo, importe_min FROM `Articles` WHERE Id_Article = id_art;
    SELECT Descuento
    INTO tarifa
    FROM Clientes
    WHERE Id_Cliente = id_cli;

    SELECT CASE
		WHEN tarifa =0 THEN IF(minimo AND IFNULL(fp.rate_0,C.PVP) < importe_min, importe_min, IFNULL(fp.rate_0,C.PVP))
        WHEN tarifa =1 THEN IF(minimo AND IFNULL(fp.rate_1,C.Tarifa1) < importe_min, importe_min, IFNULL(fp.rate_1,C.Tarifa1))
        WHEN tarifa =2 THEN IF(minimo AND IFNULL(fp.rate_2,C.Tarifa2) < importe_min, importe_min, IFNULL(fp.rate_2,C.Tarifa2))
        WHEN tarifa =3 THEN IF(minimo AND IFNULL(fp.rate_3,C.Tarifa3) < importe_min, importe_min, IFNULL(fp.rate_3,C.Tarifa3))
        WHEN tarifa BETWEEN 4 AND 100 THEN Tarifa1
        WHEN tarifa >100 THEN IF(minimo AND IFNULL(fp.rate_3,C.Tarifa3) * ( ( 200 - tarifa ) /100 ) < importe_min, importe_min,IFNULL(fp.rate_3,C.Tarifa3) * ( ( 200 - tarifa ) /100 )) 
    END, IFNULL(fp.Packing,C.Packing) Packing, C.Id_Compra,IFNULL(fp.`grouping`,C.`grouping`) `grouping`,IFNULL(fp.caja,C.caja) caja,fp.bonus INTO importe, packin, id_compra,groupin,caj,bonus
    FROM Compres C
        INNER JOIN Entradas E ON E.Id_Entrada = C.Id_Entrada
        INNER JOIN travel T ON T.id = E.travel_id
        LEFT JOIN price_fixed fp ON fp.item_id = id_art AND CURDATE() BETWEEN fp.date_start AND fp.date_end AND fp.warehouse_id IN (0,id_wh)
    WHERE Id_Article = id_art
        AND C.Novincular = FALSE
        AND T.landing BETWEEN date_inv() AND CURDATE( )
        AND T.warehouse_id = id_wh
    ORDER BY T.landing DESC
         LIMIT 1;

    IF tarifa BETWEEN 4 AND 100 THEN SET descompte = tarifa;
END IF;

IF minimo <> FALSE THEN
    IF importe < importe_min THEN
        SET importe = importe_min;
END IF;

END IF;

END IF;
SELECT importe, descompte, tarifa, packin, id_compra,groupin,caj,bonus
FROM DUAL;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `preOrdenarRuta` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `preOrdenarRuta`(IN vRutaId INT)
BEGIN
/* Usa los valores del ultimo año para adivinar el orden de los tickets en la ruta
 * vRutaId id ruta
 * DEPRECATED use vn.routeGressPriority
*/

UPDATE Tickets mt
JOIN (
	SELECT tt.Id_Consigna, round(ifnull(avg(t.Prioridad),0),0) as Prioridad
	from Tickets t
	JOIN Tickets tt on tt.Id_Consigna = t.Id_Consigna
	where t.Fecha > TIMESTAMPADD(YEAR,-1,CURDATE())
	AND tt.Id_Ruta = vRutaId
	GROUP BY Id_Consigna
    ) sub ON sub.Id_Consigna = mt.Id_Consigna
    SET mt.Prioridad = sub.Prioridad
    WHERE mt.Id_Ruta = vRutaId;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `prepare_client_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 `prepare_client_list`()
BEGIN
	DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
	CREATE TEMPORARY TABLE tmp.client_list
		(PRIMARY KEY (Id_Cliente))
		ENGINE = MEMORY
		SELECT DISTINCT Id_Cliente
			FROM tmp.ticket_list; 
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `prepare_ticket_list` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `prepare_ticket_list`(vStartingDate DATETIME, vEndingDate DATETIME)
BEGIN
	DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list;    
	CREATE TEMPORARY TABLE tmp.ticket_list
		(PRIMARY KEY (Id_Ticket))
		ENGINE = MEMORY
		SELECT t.Id_Ticket, c.Id_Cliente
			FROM Tickets t
				LEFT JOIN vn.ticketState ts ON ts.ticket = t.Id_Ticket
				JOIN Clientes c ON c.Id_Cliente = t.Id_Cliente
			WHERE c.typeFk IN ('normal','handMaking')
				AND (
					Fecha BETWEEN util.today() AND vEndingDate
					OR (
						ts.alertLevel < 3
						AND t.Fecha >= vStartingDate
						AND t.Fecha < util.today()
					)
				);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `price_detail` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `price_detail`(IN idART INT, IN datLanding DATE)
BEGIN
	CALL item_last_buy_(NULL,datLanding);
    
	SELECT 'Ultimas compras',NULL as Entrada, NULL as Almacen, NULL as Tarifa3, NULL as Tarifa2
		UNION ALL
	SELECT NULL, Id_Entrada, w.name, Tarifa3, Tarifa2 
	FROM Compres c 
	JOIN t_item_last_buy b ON c.Id_Compra = b.buy_id
	JOIN warehouse w on w.id = b.warehouse_id
	WHERE b.item_id = idART
		UNION all
	SELECT 'Precios fijados',NULL, NULL as Almacen, NULL as Tarifa3, NULL as Tarifa2
		UNION ALL
	SELECT NULL, CONCAT('de ', date_start, ' a ',date_end) , w.name, rate_3,rate_2
	FROM price_fixed
	JOIN warehouse w on w.id = warehouse_id
	WHERE item_id = idART
	AND datLanding BETWEEN date_start AND date_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 `proc_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  = latin1 */ ;
/*!50003 SET character_set_results = latin1 */ ;
/*!50003 SET collation_connection  = latin1_swedish_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `proc_end`()
BEGIN

UPDATE stat SET `end` = NOW()
WHERE id = (SELECT id FROM lastid);

DROP TEMPORARY TABLE IF EXISTS lastid;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `proc_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  = latin1 */ ;
/*!50003 SET character_set_results = latin1 */ ;
/*!50003 SET collation_connection  = latin1_swedish_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `proc_start`(IN v_proc_id INT)
BEGIN

INSERT INTO stat(proc_id) VALUES(v_proc_id);


DROP TEMPORARY TABLE IF EXISTS lastid;
CREATE TEMPORARY TABLE lastid
SELECT last_insert_id() 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 `productionState` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `productionState`(vWarehouse INT , vDate DATE)
BEGIN


SELECT IF(a.Vista= 2, z.alias, a.Agencia) Agencia, t.Id_Ruta,  count(*) Pedidos
FROM Tickets t
JOIN Consignatarios CS on CS.Id_Consigna = t.Id_Consigna
JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia
	LEFT JOIN Agencias_province ap on ap.province_id = CS.province_id AND ap.warehouse_id = t.warehouse_id AND ap.agency_id = a.agency_id
	LEFT JOIN Tickets_state tls on tls.Id_Ticket = t.Id_Ticket
	LEFT JOIN zoneNickname z ON z.warehouse_id = ap.warehouse_id and z.agency_id = ap.agency_id AND z.zona = ap.zona
    LEFT JOIN vncontrol.inter vni ON vni.inter_id = tls.inter_id
    LEFT JOIN state s ON s.id = vni.state_id
WHERE Fecha BETWEEN vDate AND util.dayend(vDate)
AND s.alert_level = 1
AND t.warehouse_id = vWarehouse
GROUP BY Agencia, Id_Ruta;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `production_buffer_problems` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_buffer_problems`()
BEGIN
/**
 * @deprecated Use vn.ticketGetProblems
 *  Necesita la tabla tmp.ticket_list 
 */
	DECLARE vToday DATETIME;
	DECLARE vTomorrowMidnight DATETIME ;
	DECLARE vWarehouse INT;
	DECLARE vDate DATE;
	DECLARE vAvailableCache INT;
	DECLARE vVisibleCache INT;
	DECLARE vDone BOOL;

	DECLARE vCursor CURSOR FOR 
		SELECT DISTINCT warehouse_id, DATE(Fecha) 
		FROM tmp.ticket_list tt
			JOIN Tickets t on tt.Id_Ticket = t.Id_Ticket
			AND DATE(t.Fecha) BETWEEN CURDATE() AND TIMESTAMPADD(DAY,1.9,CURDATE());   

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

	DROP TEMPORARY TABLE IF EXISTS tmp.buffer_problems;
	CREATE TEMPORARY TABLE tmp.buffer_problems (
		Id_Ticket INT(11),
		problem VARCHAR(50),
		INDEX (Id_Ticket)
	)
	ENGINE = MEMORY;

    SET vToday = CURDATE();
    SET vTomorrowMidnight = TIMESTAMP(TIMESTAMPADD(DAY, 1, CURDATE()), '23:59:59');

	OPEN vCursor;

	l: LOOP
		SET vDone = FALSE;
		FETCH vCursor INTO vWarehouse, vDate;

		IF vDone THEN
			LEAVE l;
		END IF;

		CALL cache.visible_refresh (vVisibleCache, FALSE, vWarehouse);
		CALL cache.available_refresh (vAvailableCache, FALSE, vWarehouse, vDate);

		--  El disponible es menor que 0

		INSERT INTO tmp.buffer_problems(Id_Ticket, problem)
			SELECT tt.Id_Ticket, Article
				FROM tmp.ticket_list tt
					JOIN Tickets t on t.Id_Ticket = tt.Id_Ticket
					LEFT JOIN vn2008.Movimientos M ON M.Id_Ticket = t.Id_Ticket
					JOIN vn2008.Articles A ON A.Id_Article = M.Id_Article
					JOIN vn2008.Tipos tp on tp.tipo_id = A.tipo_id
					LEFT JOIN cache.visible v ON A.Id_Article = v.item_id AND v.calc_id = vVisibleCache
					LEFT JOIN cache.available av ON av.item_id = A.Id_Article AND av.calc_id = vAvailableCache 
				WHERE date(t.Fecha) = vDate
					AND reino_id NOT IN (8,6)
					AND M.Cantidad > IFNULL(v.visible,0)
					AND M.Cantidad > 0
					AND IFNULL(av.available,0) < 0
					AND M.OK = FALSE 
					AND NOT generic 
					AND vWarehouse = t.warehouse_id;
			
		-- El disponible es mayor que cero y la cantidad supera el visible, estando aun sin preparar
		INSERT INTO tmp.buffer_problems(Id_Ticket, problem)
			SELECT tt.Id_Ticket, CONCAT('RETRASO (', A.Id_Article, ') ', Article)
				FROM tmp.ticket_list tt
					JOIN Tickets t on t.Id_Ticket = tt.Id_Ticket
					LEFT JOIN vn2008.Movimientos M ON M.Id_Ticket = t.Id_Ticket
                    LEFT JOIN `vn`.`saleTracking` `stPrevious` 
						ON `stPrevious`.`saleFk` = M.Id_Movimiento
                        AND `stPrevious`.`stateFk` = 26
					JOIN vn2008.Articles A ON A.Id_Article = M.Id_Article
					JOIN vn2008.Tipos tp on tp.tipo_id = A.tipo_id
					LEFT JOIN cache.visible v ON A.Id_Article = v.item_id AND v.calc_id = vVisibleCache
					LEFT JOIN (
						SELECT Id_Article FROM Articles_nicho 
						WHERE DATE(modificationDate) = CURDATE() AND warehouse_id = vWarehouse
					) nicho ON nicho.Id_Article = A.Id_Article
					LEFT JOIN cache.available av ON av.item_id = A.Id_Article AND av.calc_id = vAvailableCache 
				WHERE IFNULL(av.available,0) >= 0
					AND M.Cantidad > IFNULL(v.visible,0)
					AND M.OK = FALSE 
                    AND stPrevious.saleFk IS NULL
					AND M.Reservado = FALSE
					AND reino_id NOT IN (8,6)
					AND date(t.Fecha) = vDate
					AND NOT generic
					AND CURDATE()  = vDate 
					AND t.warehouse_id = vWarehouse
					AND nicho.Id_Article IS NULL;

                  
		-- La cantidad del movimiento es superior a la cantidad que hay en el nicho
		INSERT INTO tmp.buffer_problems(Id_Ticket, problem)
			SELECT tt.Id_Ticket, CONCAT('ALT (', CAST(M.Cantidad AS DECIMAL(10,0)), ') ',M.Id_Article, ' ', Concepte)
				FROM tmp.ticket_list tt
					JOIN Tickets t on t.Id_Ticket = tt.Id_Ticket
					JOIN vn.ticketStateToday tst ON tst.ticket = t.Id_Ticket
					JOIN vn2008.Movimientos M ON M.Id_Ticket = t.Id_Ticket
					JOIN cache.visible v ON M.Id_Article = v.item_id AND v.calc_id = vVisibleCache
					JOIN (  
							SELECT `ish`.`itemFk` AS `itemFk`,
									SUM(`ish`.`visible`) AS `visible`
								FROM
									vn.`itemShelving` `ish`
									JOIN vn.`shelving` `sh` ON `sh`.`code` = `ish`.`shelvingFk`
									JOIN vn.`parking` `p` ON `p`.`id` = `sh`.`parkingFk`
									JOIN vn.`sector` `s` ON `s`.`id` = `p`.`sectorFk`
								WHERE
									`s`.`warehouseFk` = vWarehouse
								GROUP BY itemFk
						 ) iss ON iss.itemFk = v.item_id
					WHERE v.visible - iss.visible < M.Cantidad
					AND M.OK = FALSE 
					AND M.Reservado = FALSE
					AND CURDATE() = vDate 
                    AND tst.productionOrder < 6
                    AND t.warehouse_id = vWarehouse
				;
                
	END LOOP;

	CLOSE vCursor;

	-- Código 100
   
   	 INSERT INTO tmp.buffer_problems(Id_Ticket, problem)
		SELECT DISTINCT tt.Id_Ticket, 'COD 100'
			FROM tmp.ticket_list tt
				JOIN vn.ticketRequest tr on tr.ticketFk = tt.Id_Ticket
			WHERE tr.isOK IS NULL;
                
                /*
	INSERT INTO tmp.buffer_problems(Id_Ticket, problem)
		SELECT DISTINCT tt.Id_Ticket, 'COD 100'
			FROM tmp.ticket_list tt
				JOIN Movimientos m on m.Id_Ticket = tt.Id_Ticket
			WHERE Id_Article = 100;
*/
	-- Congelado

	INSERT INTO tmp.buffer_problems(Id_Ticket, problem)
		SELECT DISTINCT tt.Id_Ticket, 'CONGELADO'
			FROM tmp.ticket_list tt
				JOIN Tickets t on t.Id_Ticket = tt.Id_Ticket
				JOIN Clientes c on c.Id_Cliente = t.Id_Cliente
			WHERE c.Congelado;
            
	-- Datos del cliente sin confirmar

	INSERT INTO tmp.buffer_problems(Id_Ticket, problem)
		SELECT DISTINCT tt.Id_Ticket, 'FICHA INCOMPLETA'
			FROM tmp.ticket_list tt
				JOIN Tickets t on t.Id_Ticket = tt.Id_Ticket
				JOIN Clientes c on c.Id_Cliente = t.Id_Cliente
			WHERE c.contabilizado = FALSE;

	-- Riesgo
	
    CALL risk_vs_client_list(CURDATE());

	 INSERT INTO tmp.buffer_problems(Id_Ticket, problem)
	  SELECT DISTINCT tt.Id_Ticket, 'RIESGO'
	   FROM tmp.ticket_list tt
		JOIN Tickets t on t.Id_Ticket = tt.Id_Ticket
		JOIN Agencias a on t.Id_Agencia = a.Id_Agencia
		JOIN tmp.risk r on r.Id_Cliente = t.Id_Cliente
		JOIN Clientes c on c.Id_Cliente = t.Id_Cliente
	   WHERE r.risk > c.Credito + 10
		AND (Vista != 3 OR t.Id_Agencia = 687);  -- para que las recogidas se preparen, salvo las de Madrid
    
    
     /*           
	-- Saldo vencido
    	INSERT INTO tmp.buffer_problems(Id_Ticket, problem)
		SELECT DISTINCT tt.Id_Ticket, 'SALDO VENCIDO'
			FROM tmp.ticket_list tt
				JOIN Tickets t on t.Id_Ticket = tt.Id_Ticket
					JOIN Agencias a on t.Id_Agencia = a.Id_Agencia
					JOIN bi.defaulters d ON d.client = t.Id_Cliente
			WHERE d.amount > 200 AND d.date = CURDATE()
				AND Vista != 3;  -- para que las recogidas se preparen
       */         
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `production_buffer_set_priority` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_buffer_set_priority`()
BEGIN

DECLARE currentDayOfWeek INT;

SET currentDayOfWeek = weekday(curdate());

-- Sin provincia ni dia de envio
UPDATE tmp.production_buffer pb
LEFT JOIN
(					
	SELECT agency_id
         , warehouse_id
         , max_hour
	FROM agency_hour ah
	WHERE subtract_day < 225
    AND week_day is null
    AND province_id is null
    			
) t  on    t.agency_id = pb.agency_id
	and t.warehouse_id = pb.warehouse_id

SET pb.Hora = IF(pb.Hora is null or pb.Hora = 0  or pb.Hora = 24,IFNULL(t.max_hour,24), pb.Hora)
   ,pb.Departure =IFNULL(t.max_hour,0);


-- Agencias sin provincia, machacan lo anterior si coinciden
UPDATE tmp.production_buffer pb
JOIN
(					
	SELECT agency_id
         , warehouse_id
         , shipmentDay(week_day, subtract_day) as shipmentDay
         , max_hour
	FROM agency_hour ah
	WHERE subtract_day < 225
    AND agency_id is not null
    AND week_day is not null
    AND max_hour is not null
    AND province_id is null
    HAVING shipmentDay = currentDayOfWeek
    			
) t  on    t.agency_id = pb.agency_id
	and t.warehouse_id = pb.warehouse_id

SET pb.Hora = IF(pb.Hora is null or pb.Hora = 0  or pb.Hora = 24,t.max_hour, pb.Hora)
,pb.Departure = t.max_hour
;


-- Agencias con provincia, se ejecuta para machacar lo anterior, si procede.
UPDATE tmp.production_buffer pb
JOIN
(					
	SELECT agency_id
         , warehouse_id
         , shipmentDay(week_day, subtract_day) as shipmentDay
         , max_hour
         , province_id
	FROM agency_hour ah
	WHERE subtract_day < 225
    AND agency_id is not null
    AND week_day is not null
    AND max_hour is not null
    AND province_id is not null
    HAVING shipmentDay = currentDayOfWeek
    			
) t  on    t.agency_id = pb.agency_id
	and t.warehouse_id = pb.warehouse_id
	and  t.province_id = pb.province_id

SET pb.Hora = IF(pb.Hora is null or pb.Hora = 0 or pb.Hora = 24,t.max_hour, pb.Hora)
,pb.Departure = t.max_hour
;

-- Pedidos del dia anterior son prioritarios
/*
UPDATE tmp.production_buffer pb
JOIN Tickets t ON t.Id_Ticket = pb.ticket
SET pb.Hora = 1
WHERE t.Fecha < 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 `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`(vWarehouseId INT, vScopeDays TINYINT)
BEGIN
	DECLARE vMidnight DATETIME DEFAULT TIMESTAMP(CURDATE(),'23:59:59');
	DECLARE vEndingDate DATETIME DEFAULT TIMESTAMPADD(DAY,vScopeDays,vMidnight);
	DECLARE SAFE_ALERT_LEVEL INT DEFAULT 3;
    DECLARE vLoadingDelay DECIMAL(5) DEFAULT 2;

	CALL prepare_ticket_list(TIMESTAMPADD(DAY,0,CURDATE()-1), vEndingDate);
	CALL prepare_client_list;
	CALL production_buffer_problems;

	DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer;
	CREATE TEMPORARY TABLE tmp.production_buffer
	(PRIMARY KEY(Id_Ticket))
	ENGINE = MEMORY
	SELECT t.Id_Ticket
			, t.Id_Cliente
			, t.warehouse_id
			, t.Alias
			, t.Bultos
			, HOUR(t.Fecha) as Hora
			, HOUR(t.Fecha) + vLoadingDelay as Departure
            , MINUTE(t.Fecha) as minuto
			, t.Id_Ruta
			, IF(a.Vista = 2,ap.zona,0) as zona
			, CS.Consignatario
			, CS.CODPOSTAL
			, CS.POBLACION
			, p.name PROVINCIA
			, IF(a.Vista= 2, CONCAT(LEFT(z.alias,16),' ',IFNULL(RIGHT(t.Id_Ruta,3),'')), a.Agencia) Agencia
			, a.agency_id
			, 0 AS `lines`
			, CAST( 0 AS DECIMAL(5,2)) AS m3
			, 0 AS problems
			, "                         " as problem
			, IFNULL(tls.state,2)  AS state
			, w.Codigotrabajador
			, DATE(t.Fecha) AS Fecha
			, Averiguar_ComercialCliente_IdTicket(t.Id_Ticket) AS Comercial
			, p.province_id
			, tls.productionOrder as state_order
			, ifnull(tls.alertLevel,0) alert_level
			, t.boxed as palletized
            , rg.deviceId ubicacion
		FROM tmp.ticket_list tt
			JOIN Tickets t on tt.Id_Ticket = t.Id_Ticket
			JOIN Consignatarios CS on CS.Id_Consigna = t.Id_Consigna
			LEFT JOIN province p on p.province_id = CS.province_id
			JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia
			LEFT JOIN Agencias_province ap on ap.province_id = CS.province_id AND ap.warehouse_id = t.warehouse_id AND ap.agency_id = a.agency_id
			LEFT JOIN vn.ticketState tls on tls.ticket = tt.Id_Ticket
			LEFT JOIN Trabajadores w on w.Id_Trabajador = tls.worker
            LEFT JOIN zoneNickname z ON z.warehouse_id = ap.warehouse_id and z.agency_id = ap.agency_id AND z.zona = ap.zona
            LEFT JOIN vn.routeGate rg ON rg.routeFk = t.Id_Ruta
		WHERE t.warehouse_id = vWarehouseId
			AND a.Vista IN (1,2,3);


	-- Líneas y volumen por ticket

	UPDATE tmp.production_buffer pb
		JOIN (
			SELECT m.Id_Ticket, COUNT(Id_Movimiento) as `lines`, cast(  sum( m.Cantidad * r.cm3 / 1000000 )   as decimal(10,2)) as m3 
			FROM tmp.ticket_list tt
				JOIN Movimientos m on tt.Id_Ticket = m.Id_Ticket
				JOIN bi.rotacion r on m.Id_Article = r.Id_Article
			WHERE r.warehouse_id = vWarehouseId
			GROUP BY m.Id_Ticket
		) m on m.Id_Ticket = pb.Id_Ticket
		SET pb.`lines` = m.`lines`,
			pb.m3 = m.m3;

	DELETE FROM tmp.production_buffer
		WHERE `lines`= 0;

	-- Cajas

	ALTER TABLE tmp.production_buffer 
		ADD Cajas DOUBLE DEFAULT NULL;
/*
	UPDATE tmp.production_buffer pb
		JOIN (
			SELECT  t.Id_Ticket, sum(floor(m.Cantidad / c.Packing) * bultoCubico) as Cajas
			FROM tmp.ticket_list tt
				JOIN Tickets t on tt.Id_Ticket = t.Id_Ticket
				JOIN Movimientos m on m.Id_Ticket = t.Id_Ticket
				JOIN cache.last_buy lb on lb.warehouse_id = t.warehouse_id AND lb.item_id = m.Id_Article
				JOIN Compres c on c.Id_Compra = lb.buy_id
				JOIN Cubos cb on cb.Id_Cubo = c.Id_Cubo
			WHERE m.Cantidad >= c.Packing
				GROUP BY t.Id_Ticket
				HAVING Cajas >= 1
		) sub ON sub.Id_Ticket = pb.Id_Ticket
		SET pb.Cajas =  sub.Cajas;
*/	
	-- Artificial, Seco y Preservado: Reino 4
    
	ALTER TABLE tmp.production_buffer 
		ADD lineasArtificial INT DEFAULT NULL;

	UPDATE tmp.production_buffer pb
		JOIN (
			SELECT tt.Id_Ticket, COUNT(m.Id_Movimiento) as Lineas
			FROM tmp.ticket_list tt
				JOIN Movimientos m ON m.Id_Ticket = tt.Id_Ticket
                JOIN Articles a ON a.Id_Article = m.Id_Article
                JOIN Tipos tp ON tp.tipo_id = a.tipo_id
                JOIN reinos r ON r.id = tp.reino_id
				WHERE reino = 'Artificial'
				GROUP BY tt.Id_Ticket
				HAVING Lineas >= 1
		) sub ON sub.Id_Ticket = pb.Id_Ticket
		SET pb.lineasArtificial =  sub.Lineas;


	-- Problemas por ticket

	UPDATE tmp.production_buffer pb
		JOIN (
			SELECT Id_Ticket, COUNT(Id_Ticket) as problems, GROUP_CONCAT(problem) problem
				FROM tmp.buffer_problems
				GROUP BY Id_Ticket
		) p on p.Id_Ticket = pb.Id_Ticket
		SET pb.problems = p.problems,
			 pb.problem = p.problem; 

	-- Hora limite de preparación

	CALL production_buffer_set_priority;

	-- Entradas

	INSERT INTO tmp.production_buffer(
			Fecha
			, Id_Ticket
			, Agencia
			, Id_Cliente
			, Consignatario
			, state
			, CodigoTrabajador
			, m3
			, `lines`
		)
		SELECT DISTINCT c.shipment AS Fecha
				, c.Id_Entrada AS Id_Ticket
				, warehouse.name
				, c.Id_Proveedor
				,	c.ref AS Consignatario
				, IF(BIT_OR(controlado.Id_Compra),6,IF(BIT_OR(preparado.Id_Compra),5,3)) AS state
				, c.Id_Trabajador AS CodigoTrabajador
				, round(sum(cm3) / 1000000,2) AS m3
				, count(c.Id_Compra) as `lines`
			FROM v_compres c
			INNER JOIN warehouse ON c.warehouse_id = warehouse.id
			LEFT JOIN Compres_ok preparado ON c.Id_Compra = preparado.Id_Compra AND preparado.valor = 1
			LEFT JOIN Compres_ok controlado ON c.Id_Compra = controlado.Id_Compra AND controlado.valor = 2
			WHERE warehouse_id_out = vWarehouseId AND IFNULL(c.Confirmada,FALSE) = FALSE
			AND c.shipment >= CURDATE()
			GROUP BY Id_Entrada;

	-- Refresca la caché para el cierre dinámico de agencias

	CALL cache.departure_timing(vWarehouseId);

	-- Tickets de recogida

	REPLACE tmp.production_buffer(
			Fecha
			, Id_Ticket
			, Agencia
			, Id_Cliente
			, Consignatario
			, state
			, CodigoTrabajador
			, alert_level
			, warehouse_id
		)
		SELECT
			DATE(t.Fecha) AS Fecha
			, t.Id_Ticket
			, a.Agencia
			, t.Id_Cliente
			, CS.Consignatario
			, s.id as state
			, w.Codigotrabajador
			, ifnull(tls.alertLevel,0) alert_level
			, vWarehouseId
		FROM vn2008.Tickets t
			JOIN vn2008.Consignatarios CS on CS.Id_Consigna = t.Id_Consigna
			JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia
			LEFT JOIN vn2008.warehouse_pickup wp ON wp.agency_id = a.Id_Agencia
			LEFT JOIN vn.ticketState tls on tls.ticket = t.Id_Ticket
			LEFT JOIN vn.state s ON s.id = tls.state
			LEFT JOIN vn2008.Trabajadores w on w.Id_Trabajador = tls.worker
		WHERE t.Fecha between TIMESTAMPADD(WEEK,-1,CURDATE()) AND dayend(TIMESTAMPADD(DAY,-1,CURDATE()))
			AND wp.warehouse_id = vWarehouseId;

	-- DROP TEMPORARY TABLE tmp.ticket_list;
	-- DROP TEMPORARY TABLE IF EXISTS tmp.risk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `production_control_source_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 `production_control_source_Beta`(vWarehouseId INT, vScopeDays TINYINT)
BEGIN
	DECLARE vMidnight DATETIME DEFAULT TIMESTAMP(CURDATE(),'23:59:59');
	DECLARE vEndingDate DATETIME DEFAULT TIMESTAMPADD(DAY,vScopeDays,vMidnight);
	DECLARE SAFE_ALERT_LEVEL INT DEFAULT 3;
    DECLARE vLoadingDelay DECIMAL(5) DEFAULT 2;

	CALL prepare_ticket_list(TIMESTAMPADD(DAY,0,CURDATE()-1), vEndingDate);
	CALL prepare_client_list;
	CALL production_buffer_problems;
    
    IF vWarehouseId = 0 THEN
    
		DELETE tt.* 
			FROM tmp.ticket_list tt
				JOIN Tickets t on tt.Id_Ticket = t.Id_Ticket
            WHERE t.warehouse_id NOT IN (1,44);
            
	ELSE
    
		DELETE tt.* 
			FROM tmp.ticket_list tt
				JOIN Tickets t on tt.Id_Ticket = t.Id_Ticket
            WHERE t.warehouse_id != vWarehouseId;          
        
    END IF;
    
    /*  
    DROP TEMPORARY TABLE IF EXISTS tmp.selectedWarehouses;
  
    IF vWarehouseId = 0 THEN
    
     CREATE TEMPORARY TABLE tmp.selectedWarehouses
		(PRIMARY KEY(id))
		ENGINE = MEMORY
		SELECT id
		FROM warehouse
		WHERE id = vWarehouseId;
        
    ELSE
    
     CREATE TEMPORARY TABLE tmp.selectedWarehouses
		(PRIMARY KEY(id))
		ENGINE = MEMORY
		SELECT id
		FROM warehouse
		WHERE id IN (1,44); -- Silla FV y Silla PCA
        
    END IF;
    */
   

	DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer;
	CREATE TEMPORARY TABLE tmp.production_buffer
	(PRIMARY KEY(Id_Ticket))
	ENGINE = MEMORY
	SELECT t.Id_Ticket
			, t.Id_Cliente
			, t.warehouse_id
			, t.Alias
			, t.Bultos
			, HOUR(t.Fecha) as Hora
			, HOUR(t.Fecha) + vLoadingDelay as Departure
            , MINUTE(t.Fecha) as minuto
			, t.Id_Ruta
			, IF(a.Vista = 2,ap.zona,0) as zona
			, CS.Consignatario
			, CS.CODPOSTAL
			, CS.POBLACION
			, p.name PROVINCIA
			, IF(a.Vista= 2, CONCAT(LEFT(z.alias,16),' ',IFNULL(RIGHT(t.Id_Ruta,3),'')), a.Agencia) Agencia
			, a.agency_id
			, 0 AS `lines`
			, CAST( 0 AS DECIMAL(5,2)) AS m3
			, 0 AS problems
			, "                         " as problem
			, IFNULL(tls.state,2)  AS state
			, w.Codigotrabajador
			, DATE(t.Fecha) AS Fecha
			, Averiguar_ComercialCliente_IdTicket(t.Id_Ticket) AS Comercial
			, p.province_id
			, tls.productionOrder as state_order
			, ifnull(tls.alertLevel,0) alert_level
			, t.boxed as palletized
		FROM tmp.ticket_list tt
			JOIN Tickets t on tt.Id_Ticket = t.Id_Ticket
			JOIN Consignatarios CS on CS.Id_Consigna = t.Id_Consigna
			LEFT JOIN province p on p.province_id = CS.province_id
			JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia
			LEFT JOIN Agencias_province ap on ap.province_id = CS.province_id AND ap.warehouse_id = t.warehouse_id AND ap.agency_id = a.agency_id
			LEFT JOIN vn.ticketState tls on tls.ticket = tt.Id_Ticket
			LEFT JOIN Trabajadores w on w.Id_Trabajador = tls.worker
            LEFT JOIN zoneNickname z ON z.warehouse_id = ap.warehouse_id and z.agency_id = ap.agency_id AND z.zona = ap.zona
			AND a.Vista IN (1,2,3);


	-- Líneas y volumen por ticket

	UPDATE tmp.production_buffer pb
		JOIN (
			SELECT m.Id_Ticket, COUNT(Id_Movimiento) as `lines`, cast(  sum( m.Cantidad * r.cm3 / 1000000 )   as decimal(10,2)) as m3 
			FROM tmp.ticket_list tt
				JOIN Tickets t ON t.Id_Ticket = tt.Id_Ticket
				JOIN Movimientos m on tt.Id_Ticket = m.Id_Ticket
				JOIN bi.rotacion r on m.Id_Article = r.Id_Article AND r.warehouse_id = t.warehouse_id
			GROUP BY m.Id_Ticket
		) m on m.Id_Ticket = pb.Id_Ticket
		SET pb.`lines` = m.`lines`,
			pb.m3 = m.m3;

	DELETE FROM tmp.production_buffer
		WHERE `lines`= 0;

	-- Cajas

	ALTER TABLE tmp.production_buffer 
		ADD Cajas DOUBLE DEFAULT NULL;

	UPDATE tmp.production_buffer pb
		JOIN (
			SELECT  t.Id_Ticket, sum(floor(m.Cantidad / c.Packing) * bultoCubico) as Cajas
			FROM tmp.ticket_list tt
				JOIN Tickets t on tt.Id_Ticket = t.Id_Ticket
				JOIN Movimientos m on m.Id_Ticket = t.Id_Ticket
				JOIN cache.last_buy lb on lb.warehouse_id = t.warehouse_id AND lb.item_id = m.Id_Article
				JOIN Compres c on c.Id_Compra = lb.buy_id
				JOIN Cubos cb on cb.Id_Cubo = c.Id_Cubo
			WHERE m.Cantidad > c.Packing
				GROUP BY t.Id_Ticket
				HAVING Cajas >= 1
		) sub ON sub.Id_Ticket = pb.Id_Ticket
		SET pb.Cajas =  sub.Cajas;
	
	-- Artificial, Seco y Preservado: Reino 4
    
	ALTER TABLE tmp.production_buffer 
		ADD lineasArtificial INT DEFAULT NULL;

	UPDATE tmp.production_buffer pb
		JOIN (
			SELECT tt.Id_Ticket, COUNT(m.Id_Movimiento) as Lineas
			FROM tmp.ticket_list tt
				JOIN Movimientos m ON m.Id_Ticket = tt.Id_Ticket
                JOIN Articles a ON a.Id_Article = m.Id_Article
                JOIN Tipos tp ON tp.tipo_id = a.tipo_id
                JOIN reinos r ON r.id = tp.reino_id
				WHERE reino = 'Artificial'
				GROUP BY tt.Id_Ticket
				HAVING Lineas >= 1
		) sub ON sub.Id_Ticket = pb.Id_Ticket
		SET pb.lineasArtificial =  sub.Lineas;


	-- Problemas por ticket

	UPDATE tmp.production_buffer pb
		JOIN (
			SELECT Id_Ticket, COUNT(Id_Ticket) as problems, GROUP_CONCAT(problem) problem
				FROM tmp.buffer_problems
				GROUP BY Id_Ticket
		) p on p.Id_Ticket = pb.Id_Ticket
		SET pb.problems = p.problems,
			 pb.problem = p.problem; 

	-- Hora limite de preparación

	CALL production_buffer_set_priority;

	-- Entradas

	INSERT INTO tmp.production_buffer(
			Fecha
			, Id_Ticket
			, Agencia
			, Id_Cliente
			, Consignatario
			, state
			, CodigoTrabajador
			, m3
			, `lines`
		)
		SELECT DISTINCT c.shipment AS Fecha
				, c.Id_Entrada AS Id_Ticket
				, warehouse.name
				, c.Id_Proveedor
				,	c.ref AS Consignatario
				, IF(BIT_OR(controlado.Id_Compra),6,IF(BIT_OR(preparado.Id_Compra),5,3)) AS state
				, c.Id_Trabajador AS CodigoTrabajador
				, round(sum(cm3) / 1000000,2) AS m3
				, count(c.Id_Compra) as `lines`
			FROM v_compres c
			INNER JOIN warehouse ON c.warehouse_id = warehouse.id
			LEFT JOIN Compres_ok preparado ON c.Id_Compra = preparado.Id_Compra AND preparado.valor = 1
			LEFT JOIN Compres_ok controlado ON c.Id_Compra = controlado.Id_Compra AND controlado.valor = 2
			WHERE (warehouse_id_out = CASE vWarehouseId WHEN 0 THEN 1 ELSE vWarehouseId END 
					OR
                   warehouse_id_out = CASE vWarehouseId WHEN 0 THEN 44 ELSE vWarehouseId END)
            AND IFNULL(c.Confirmada,FALSE) = FALSE
			AND c.shipment >= CURDATE()
			GROUP BY Id_Entrada;

	-- Refresca la caché para el cierre dinámico de agencias

	CALL cache.departure_timing;

	-- Tickets de recogida

	REPLACE tmp.production_buffer(
			Fecha
			, Id_Ticket
			, Agencia
			, Id_Cliente
			, Consignatario
			, state
			, CodigoTrabajador
			, alert_level
			, warehouse_id
		)
		SELECT
			DATE(t.Fecha) AS Fecha
			, t.Id_Ticket
			, a.Agencia
			, t.Id_Cliente
			, CS.Consignatario
			, s.id as state
			, w.Codigotrabajador
			, ifnull(tls.alertLevel,0) alert_level
			, t.warehouse_id
		FROM vn2008.Tickets t
			JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.Id_Ticket
			JOIN vn2008.Consignatarios CS on CS.Id_Consigna = t.Id_Consigna
			JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia
			LEFT JOIN vn2008.warehouse_pickup wp ON wp.agency_id = a.Id_Agencia
			LEFT JOIN vn.ticketState tls on tls.ticket = t.Id_Ticket
			LEFT JOIN vn.state s ON s.id = tls.state
			LEFT JOIN vn2008.Trabajadores w on w.Id_Trabajador = tls.worker
		WHERE t.Fecha between TIMESTAMPADD(WEEK,-1,CURDATE()) AND dayend(TIMESTAMPADD(DAY,-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 `proveedores_saldo` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `proveedores_saldo`(IN datFEC DATE)
BEGIN

SET datFEC = IF(datfec < CURDATE(), CURDATE(), datfec);

SELECT      P.Id_Proveedor
			, P.Proveedor
			, P.empresa_id
			, P.pay_met_id
			, P.cuenta
			, RED(IFNULL(sub_tot.Saldo,0) + IFNULL(sub_fut.Saldo,0) + IFNULL(sub_hoy.Saldo,0))  Total
			, RED(IFNULL(sub_hoy.Saldo,0) + IFNULL(sub_fut.Saldo,0)) Inmediato
			, RED(IFNULL(sub_hoy.Saldo,0)) Vencido
FROM 
(SELECT  Id_Proveedor, Proveedor, id as empresa_id, pay_met_id, P.cuenta FROM Proveedores P INNER JOIN empresa) P

LEFT JOIN
(
SELECT Id_Proveedor, empresa_id, SUM(Sald) as Saldo
FROM
(
SELECT RV.Fecha, SUM(-1* ROUND(IFNULL(cantidad,0) / IF(p.cuenta LIKE '___4______',rr.rate,1),2)) as Sald, proveedor_id as Id_Proveedor, empresa_id
FROM recibida_vencimiento RV 
INNER JOIN recibida R ON RV.recibida_id = R.id
INNER JOIN Proveedores p ON p.Id_Proveedor = R.proveedor_id
INNER JOIN reference_rate rr ON rr.date=R.fecha
WHERE RV.fecha > datFEC
 AND R.contabilizada
GROUP BY proveedor_id, empresa_id
UNION ALL
SELECT fecha, red(SUM(IFNULL(importe,0))), id_proveedor, empresa_id
FROM pago
WHERE fecha > datFEC 
GROUP BY id_proveedor, empresa_id
) sub
GROUP BY Id_Proveedor, empresa_id
) sub_tot USING(Id_Proveedor, empresa_id)

-- Saldo inmediato

LEFT JOIN
(
SELECT Id_Proveedor, empresa_id, SUM(Sald) as Saldo
FROM
(
SELECT RV.Fecha, SUM(-1* ROUND(IFNULL(cantidad,0)/ IF(p.cuenta LIKE '___4______',rr.rate,1),2)) as Sald, proveedor_id as Id_Proveedor, empresa_id
FROM recibida_vencimiento RV 
INNER JOIN recibida R ON RV.recibida_id = R.id
INNER JOIN Proveedores p ON p.Id_Proveedor = R.proveedor_id
INNER JOIN reference_rate rr ON rr.date = R.fecha
WHERE RV.fecha BETWEEN CURDATE() AND datFEC
AND R.contabilizada
GROUP BY proveedor_id, empresa_id
UNION ALL
SELECT fecha, ROUND(SUM(IFNULL(importe,0)),2), id_proveedor, empresa_id
FROM pago
WHERE fecha BETWEEN CURDATE() AND datFEC
GROUP BY id_proveedor, empresa_id
) sub3
GROUP BY Id_Proveedor, empresa_id
) sub_fut USING(Id_Proveedor, empresa_id)



LEFT JOIN
(
SELECT Id_Proveedor, empresa_id, SUM(Sald) as Saldo
FROM
(
SELECT RV.Fecha, SUM(-1* ROUND(IFNULL(cantidad,0)/ IF(p.cuenta LIKE '___4______',rr.rate,1),2)) as Sald, proveedor_id as Id_Proveedor, empresa_id
FROM recibida_vencimiento RV 
INNER JOIN recibida R ON RV.recibida_id = R.id
INNER JOIN Proveedores p ON p.Id_Proveedor = R.proveedor_id
INNER JOIN reference_rate rr ON rr.date = R.fecha
WHERE RV.fecha  > '2014-12-31' AND RV.fecha < CURDATE() 
AND R.contabilizada
GROUP BY proveedor_id, empresa_id
UNION ALL
SELECT fecha, red(SUM(IFNULL(importe,0))), id_proveedor, empresa_id
FROM pago
WHERE fecha > '2014-12-31' AND fecha < CURDATE() 
GROUP BY id_proveedor, empresa_id
) sub5
GROUP BY Id_Proveedor, empresa_id
) sub_hoy USING(Id_Proveedor, empresa_id)
WHERE abs(sub_tot.Saldo) >0.2
      OR ABS(sub_fut.Saldo) >0.2
      OR ABS(sub_hoy.Saldo) >0.2
;

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

 DECLARE startingDate DATETIME DEFAULT TIMESTAMPADD(MONTH,-3,CURDATE());
    
 DROP TEMPORARY TABLE IF EXISTS saldos_iniciales;

 CREATE TEMPORARY TABLE saldos_iniciales
  

  (proveedor_id INT NOT NULL
  , empresa_id INT NOT NULL
  , saldo_inicial double NOT NULL
        , saldo_final DOUBLE NOT NULL
  , moneda_id INT NOT NULL
  , PRIMARY KEY(proveedor_id, empresa_id, moneda_id))
        ENGINE =  MEMORY;

 -- Calcula el saldo inicial y final de cada proveedor
 INSERT INTO saldos_iniciales
 SELECT id_proveedor, empresa_id, sum(importe * isBeforeStarting) as saldo_inicial,sum(importe) saldo_final, moneda_id
    FROM (
  SELECT 
    p.id_proveedor,
    p.empresa_id,
    if(p.id_moneda = 1, p.importe, p.divisa) as importe,
                if( p.fecha < startingDate,1,0) isBeforeStarting,
    p.id_moneda moneda_id
  FROM pago p
  WHERE p.fecha > '2014-12-31'
   AND p.empresa_id = 442
            AND p.id_proveedor <> 567
    
  UNION ALL
    
  SELECT 
    r.proveedor_id,
    r.empresa_id,
    - if(r.moneda_id = 1, rv.cantidad, rv.divisa) AS Total,
                if(rv.fecha < startingDate,1,0) isBeforeStarting,
    r.moneda_id
  FROM
   recibida r
  INNER JOIN recibida_vencimiento rv ON r.id = rv.recibida_id
  WHERE  r.fecha > '2014-12-31' 
            AND r.contabilizada AND r.empresa_id = 442
            AND r.proveedor_id <> 567
    ) sub
    GROUP BY empresa_id, id_proveedor, moneda_id;

    DROP TEMPORARY TABLE IF EXISTS vencimientos_pendientes;
    
    CREATE TEMPORARY TABLE vencimientos_pendientes
    (vencimiento_id INT, id INT auto_increment
    ,fecha DATE
    ,proveedor_id INT NOT NULL
    ,empresa_id INT NOT NULL
    ,importe DECIMAL(10,2) NOT NULL
    ,moneda_id INT NOT NULL
    ,pendiente DECIMAL(10,2) DEFAULT 0
    ,saldo DECIMAL(10,2) DEFAULT 0
    ,saldoFinal DECIMAL(10,2) DEFAULT 0
    ,isPago BOOLEAN
    ,conciliado BOOLEAN
    ,PRIMARY KEY(id), 
    INDEX(proveedor_id,empresa_id,moneda_id))
    ENGINE =  MEMORY;

 INSERT INTO vencimientos_pendientes(vencimiento_id
                                      , fecha
                                      , proveedor_id
                                      , empresa_id
                                      , importe
                                      , moneda_id
                                      , isPago
                                      , conciliado)
 SELECT p.id,
   p.fecha,
   p.id_proveedor,
   p.empresa_id,
   if(p.id_moneda = 1, p.importe, p.divisa) as importe,
   p.id_moneda,
            TRUE isPago,
            p.conciliado
  FROM pago p
  WHERE p.fecha >= startingDate AND p.empresa_id = 442
   AND p.id_proveedor <> 567
 UNION ALL
    SELECT r.id
         , rv.fecha
         , r.proveedor_id
         , r.empresa_id
         , -if(r.moneda_id = 1, rv.cantidad, rv.divisa) as importe
         , r.moneda_id
         , FALSE
         , TRUE
 FROM recibida r
    LEFT JOIN saldos_iniciales si ON r.empresa_id = si.empresa_id AND r.proveedor_id = si.proveedor_id AND r.moneda_id = si.moneda_id
    INNER JOIN recibida_vencimiento rv ON r.id = rv.recibida_id
    WHERE rv.fecha >= startingDate AND IFNULL(saldo_final,TRUE) <> 0
  and r.contabilizada AND r.empresa_id = 442
  AND r.proveedor_id <> 567
    ORDER BY id_proveedor, empresa_id, id_moneda, fecha, isPago DESC,id;
    
    -- Ahora, calculamos el importe pendiente para cada recibo en orden descendente
    SET @saldo:= 0.0;
    SET @prov := 0.0;
	SET @emp := 0.0;
    set @moneda := 0.0;
    SET @pendiente := 0.0;
    SET @day := CURDATE();
    
 UPDATE vencimientos_pendientes vp LEFT JOIN saldos_iniciales si ON 
  vp.empresa_id = si.empresa_id AND vp.proveedor_id = si.proveedor_id AND vp.moneda_id = si.moneda_id
    SET vp.saldo = @saldo:= (IF(@emp <> vp.empresa_id OR @prov <> vp.proveedor_id OR @moneda <> vp.moneda_id, IFNULL(si.saldo_inicial,0),@saldo) + vp.importe) -- si hay cambio de empresa o proveedor o moneda, el saldo se reinicia
  , vp.pendiente = @pendiente:= IF(@emp <> vp.empresa_id OR @prov <> vp.proveedor_id OR @moneda <> vp.moneda_id  OR @day <> vp.fecha, vp.importe * (NOT isPago) , @pendiente + vp.importe)
        , vp.empresa_id = @emp:= vp.empresa_id
  , vp.proveedor_id = @prov:= vp.proveedor_id
  , vp.moneda_id = @moneda:= vp.moneda_id
        , vp.fecha = @day:= vp.fecha
  , vp.saldo = @saldo
        , vp.pendiente = @pendiente;

 CREATE TEMPORARY TABLE rowsToDelete 
    ENGINE =  MEMORY
  SELECT vencimiento_id, fecha,proveedor_id,empresa_id,moneda_id,saldo
    FROM vencimientos_pendientes
    -- GROUP BY fecha,proveedor_id,empresa_id,moneda_id
    WHERE saldo < 0.5 AND saldo > -0.5;

 DELETE vp.* FROM vencimientos_pendientes vp JOIN rowsToDelete rd 
  ON (vp.fecha < rd.fecha OR (vp.fecha = rd.fecha AND vp.vencimiento_id <= rd.vencimiento_id)) 
		AND vp.proveedor_id = rd.proveedor_id AND vp.empresa_id = rd.empresa_id AND vp.moneda_id = rd.moneda_id 
  
        WHERE isPago = FALSE;
 
    SELECT vp.vencimiento_id
   , vp.fecha
   , vp.proveedor_id
         , vp.empresa_id
         , vp.moneda_id
         , vp.importe
         , vp.pendiente
         , vp.saldo
         , p.pay_met_id
         , vp.isPago
         , vp.conciliado
         , vp.saldoFinal
 FROM vencimientos_pendientes vp
  LEFT JOIN Proveedores p ON p.Id_Proveedor = vp.proveedor_id;

    DROP TEMPORARY TABLE vencimientos_pendientes;
    DROP TEMPORARY TABLE saldos_iniciales;
    DROP TEMPORARY TABLE rowsToDelete;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `proveedores_saldosKk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `proveedores_saldosKk`()
BEGIN
	
	DECLARE startingDate DATETIME DEFAULT TIMESTAMPADD(MONTH,-3,CURDATE());
    
	DROP TEMPORARY TABLE IF EXISTS saldos_iniciales;

	CREATE TEMPORARY TABLE saldos_iniciales
		
		(proveedor_id INT NOT NULL
		, empresa_id INT NOT NULL
		, saldo_inicial double NOT NULL
        , saldo_final DOUBLE NOT NULL
		, moneda_id INT NOT NULL
		, PRIMARY KEY(proveedor_id, empresa_id, moneda_id))
        ENGINE =  MEMORY;

	-- Calcula el saldo inicial y final de cada proveedor
	INSERT INTO saldos_iniciales
	SELECT id_proveedor, empresa_id, sum(importe * isBeforeStarting) as saldo_inicial,sum(importe) saldo_final, moneda_id
    FROM (
		SELECT 
				p.id_proveedor,
				p.empresa_id,
				if(p.id_moneda = 1, p.importe, p.divisa) as importe,
                if( p.fecha < startingDate,1,0) isBeforeStarting,
				p.id_moneda moneda_id
		FROM pago p
		WHERE p.fecha > '2014-12-31'
			AND p.empresa_id = 442
            AND p.id_proveedor <> 567
    
		UNION ALL
    
		SELECT 
				r.proveedor_id,
				r.empresa_id,
				- if(r.moneda_id = 1, rv.cantidad, rv.divisa) AS Total,
                if(rv.fecha < startingDate,1,0) isBeforeStarting,
				r.moneda_id
		FROM
			recibida r
		INNER JOIN recibida_vencimiento rv ON r.id = rv.recibida_id
		WHERE  r.fecha > '2014-12-31' 
            AND r.contabilizada AND r.empresa_id = 442
            AND r.proveedor_id <> 567
    ) sub
    GROUP BY empresa_id, id_proveedor, moneda_id;

    DROP TEMPORARY TABLE IF EXISTS vencimientos_pendientes;
    
    CREATE TEMPORARY TABLE vencimientos_pendientes
    (vencimiento_id INT, id INT auto_increment
    ,fecha DATE
    ,proveedor_id INT NOT NULL
    ,empresa_id INT NOT NULL
    ,importe DECIMAL(10,2) NOT NULL
    ,moneda_id INT NOT NULL
    ,pendiente DECIMAL(10,2) DEFAULT 0
    ,saldo DECIMAL(10,2) DEFAULT 0
    ,saldoFinal DECIMAL(10,2) DEFAULT 0
    ,isPago BOOLEAN
    ,conciliado BOOLEAN
    ,PRIMARY KEY(id), 
    INDEX(proveedor_id,empresa_id,moneda_id))
    ENGINE =  MEMORY;

	INSERT INTO vencimientos_pendientes(vencimiento_id
                                      , fecha
                                      , proveedor_id
                                      , empresa_id
                                      , importe
                                      , moneda_id
                                      , isPago
                                      , conciliado)
	SELECT p.id,
			p.fecha,
			p.id_proveedor,
			p.empresa_id,
			if(p.id_moneda = 1, p.importe, p.divisa) as importe,
			p.id_moneda,
            TRUE isPago,
            p.conciliado
		FROM pago p
		WHERE p.fecha >= startingDate AND p.empresa_id = 442
			AND p.id_proveedor <> 567
	UNION ALL
    SELECT rv.id
         , rv.fecha
         , r.proveedor_id
         , r.empresa_id
         , -if(r.moneda_id = 1, rv.cantidad, rv.divisa) as importe
         , r.moneda_id
         , FALSE
         , TRUE
	FROM recibida r
    LEFT JOIN saldos_iniciales si ON r.empresa_id = si.empresa_id AND r.proveedor_id = si.proveedor_id AND r.moneda_id = si.moneda_id
    INNER JOIN recibida_vencimiento rv ON r.id = rv.recibida_id
    WHERE rv.fecha >= startingDate AND IFNULL(saldo_final,TRUE) <> 0
		and r.contabilizada AND r.empresa_id = 442
		AND r.proveedor_id <> 567
    ORDER BY id_proveedor, empresa_id, id_moneda, fecha, isPago DESC,id;

    -- Ahora, calculamos el importe pendiente para cada recibo en orden descendente
    SET @saldo:= 0.0;
    SET @prov := 0.0;
	SET @emp := 0.0;
    set @moneda := 0.0;
    SET @pendiente := 0.0;
    SET @day := CURDATE();
    
	UPDATE vencimientos_pendientes vp LEFT JOIN saldos_iniciales si ON 
		vp.empresa_id = si.empresa_id AND vp.proveedor_id = si.proveedor_id AND vp.moneda_id = si.moneda_id
    SET vp.saldo = @saldo:= (IF(@emp <> vp.empresa_id OR @prov <> vp.proveedor_id OR @moneda <> vp.moneda_id, IFNULL(si.saldo_inicial,0),@saldo) + vp.importe) -- si hay cambio de empresa o proveedor o moneda, el saldo se reinicia
		, vp.pendiente = @pendiente:= IF(@emp <> vp.empresa_id OR @prov <> vp.proveedor_id OR @moneda <> vp.moneda_id  OR @day <> vp.fecha, vp.importe * (NOT isPago) , @pendiente + vp.importe)
        , vp.empresa_id = @emp:= vp.empresa_id
		, vp.proveedor_id = @prov:= vp.proveedor_id
		, vp.moneda_id = @moneda:= vp.moneda_id
        , vp.fecha = @day:= vp.fecha
		, vp.saldo = @saldo
        , vp.pendiente = @pendiente;
            
	CREATE TEMPORARY TABLE rowsToDelete 
    ENGINE =  MEMORY
    SELECT fecha,proveedor_id,empresa_id,moneda_id
		FROM vencimientos_pendientes 
        WHERE saldo < 0.5 AND saldo > -0.5;

	DELETE vp.* FROM vencimientos_pendientes vp JOIN rowsToDelete rd 
		ON vp.fecha <= rd.fecha AND vp.proveedor_id = rd.proveedor_id AND vp.empresa_id = rd.empresa_id AND vp.moneda_id = rd.moneda_id 
        WHERE isPago = FALSE;
	
    SELECT vp.vencimiento_id
		 , vp.fecha
		 , vp.proveedor_id
         , vp.empresa_id
         , vp.moneda_id
         , vp.importe
         , vp.pendiente
         , vp.saldo
         , p.pay_met_id
         , vp.isPago
         , vp.conciliado
         , vp.saldoFinal
	FROM vencimientos_pendientes vp
		LEFT JOIN Proveedores p ON p.Id_Proveedor = vp.proveedor_id;

    DROP TEMPORARY TABLE vencimientos_pendientes;
    DROP TEMPORARY TABLE saldos_iniciales;
    DROP TEMPORARY TABLE rowsToDelete;

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

 DECLARE startingDate DATETIME DEFAULT TIMESTAMPADD(MONTH,-3,CURDATE());
    
 DROP TEMPORARY TABLE IF EXISTS saldos_iniciales;

 CREATE TEMPORARY TABLE saldos_iniciales
  

  (proveedor_id INT NOT NULL
  , empresa_id INT NOT NULL
  , saldo_inicial double NOT NULL
        , saldo_final DOUBLE NOT NULL
  , moneda_id INT NOT NULL
  , PRIMARY KEY(proveedor_id, empresa_id, moneda_id))
        ENGINE =  MEMORY;

 -- Calcula el saldo inicial y final de cada proveedor
 INSERT INTO saldos_iniciales
 SELECT id_proveedor, empresa_id, sum(importe * isBeforeStarting) as saldo_inicial,sum(importe) saldo_final, moneda_id
    FROM (
  SELECT 
    p.id_proveedor,
    p.empresa_id,
    if(p.id_moneda = 1, p.importe, p.divisa) as importe,
                if( p.fecha < startingDate,1,0) isBeforeStarting,
    p.id_moneda moneda_id
  FROM pago p
  WHERE p.fecha > '2014-12-31'
   AND p.empresa_id = 442
            AND p.id_proveedor <> 567
    
  UNION ALL
    
  SELECT 
    r.proveedor_id,
    r.empresa_id,
    - if(r.moneda_id = 1, rv.cantidad, rv.divisa) AS Total,
                if(rv.fecha < startingDate,1,0) isBeforeStarting,
    r.moneda_id
  FROM
   recibida r
  INNER JOIN recibida_vencimiento rv ON r.id = rv.recibida_id
  WHERE  r.fecha > '2014-12-31' 
            AND r.contabilizada AND r.empresa_id = 442
            AND r.proveedor_id <> 567
    ) sub
    GROUP BY empresa_id, id_proveedor, moneda_id;

    DROP TEMPORARY TABLE IF EXISTS vencimientos_pendientes;
    
    CREATE TEMPORARY TABLE vencimientos_pendientes
    (vencimiento_id INT, id INT auto_increment
    ,fecha DATE
    ,proveedor_id INT NOT NULL
    ,empresa_id INT NOT NULL
    ,importe DECIMAL(10,2) NOT NULL
    ,moneda_id INT NOT NULL
    ,pendiente DECIMAL(10,2) DEFAULT 0
    ,saldo DECIMAL(10,2) DEFAULT 0
    ,saldoFinal DECIMAL(10,2) DEFAULT 0
    ,isPago BOOLEAN
    ,conciliado BOOLEAN
    ,PRIMARY KEY(id), 
    INDEX(proveedor_id,empresa_id,moneda_id))
    ENGINE =  MEMORY;

 INSERT INTO vencimientos_pendientes(vencimiento_id
                                      , fecha
                                      , proveedor_id
                                      , empresa_id
                                      , importe
                                      , moneda_id
                                      , isPago
                                      , conciliado)
 SELECT p.id,
   p.fecha,
   p.id_proveedor,
   p.empresa_id,
   if(p.id_moneda = 1, p.importe, p.divisa) as importe,
   p.id_moneda,
            TRUE isPago,
            p.conciliado
  FROM pago p
  WHERE p.fecha >= startingDate AND p.empresa_id = 442
   AND p.id_proveedor <> 567
 UNION ALL
    SELECT r.id
         , rv.fecha
         , r.proveedor_id
         , r.empresa_id
         , -if(r.moneda_id = 1, rv.cantidad, rv.divisa) as importe
         , r.moneda_id
         , FALSE
         , TRUE
 FROM recibida r
    LEFT JOIN saldos_iniciales si ON r.empresa_id = si.empresa_id AND r.proveedor_id = si.proveedor_id AND r.moneda_id = si.moneda_id
    INNER JOIN recibida_vencimiento rv ON r.id = rv.recibida_id
    WHERE rv.fecha >= startingDate AND IFNULL(saldo_final,TRUE) <> 0
  and r.contabilizada AND r.empresa_id = 442
  AND r.proveedor_id <> 567
    ORDER BY id_proveedor, empresa_id, id_moneda, fecha, isPago DESC,id;
    
    
SELECT p.id,
   p.fecha,
   p.id_proveedor,
   p.empresa_id,
   if(p.id_moneda = 1, p.importe, p.divisa) as importe,
   p.id_moneda,
            TRUE isPago,
            p.conciliado
  FROM pago p
  WHERE p.fecha >= startingDate AND p.empresa_id = 442
   AND p.id_proveedor <> 567
 UNION ALL
    SELECT r.id
         , rv.fecha
         , r.proveedor_id
         , r.empresa_id
         , -if(r.moneda_id = 1, rv.cantidad, rv.divisa) as importe
         , r.moneda_id
         , FALSE
         , TRUE
 FROM recibida r
    LEFT JOIN saldos_iniciales si ON r.empresa_id = si.empresa_id AND r.proveedor_id = si.proveedor_id AND r.moneda_id = si.moneda_id
    INNER JOIN recibida_vencimiento rv ON r.id = rv.recibida_id
    WHERE rv.fecha >= startingDate 
  and r.contabilizada AND r.empresa_id = 442
  AND r.proveedor_id <> 567
    ORDER BY id_proveedor, empresa_id, id_moneda, fecha, isPago DESC,id;
    

    -- Ahora, calculamos el importe pendiente para cada recibo en orden descendente
    SET @saldo:= 0.0;
    SET @prov := 0.0;
 SET @emp := 0.0;
    set @moneda := 0.0;
    SET @pendiente := 0.0;
    SET @day := CURDATE();
    
 UPDATE vencimientos_pendientes vp LEFT JOIN saldos_iniciales si ON 
  vp.empresa_id = si.empresa_id AND vp.proveedor_id = si.proveedor_id AND vp.moneda_id = si.moneda_id
    SET vp.saldo = @saldo:= (IF(@emp <> vp.empresa_id OR @prov <> vp.proveedor_id OR @moneda <> vp.moneda_id, IFNULL(si.saldo_inicial,0),@saldo) + vp.importe) -- si hay cambio de empresa o proveedor o moneda, el saldo se reinicia
  , vp.pendiente = @pendiente:= IF(@emp <> vp.empresa_id OR @prov <> vp.proveedor_id OR @moneda <> vp.moneda_id  OR @day <> vp.fecha, vp.importe * (NOT isPago) , @pendiente + vp.importe)
        , vp.empresa_id = @emp:= vp.empresa_id
  , vp.proveedor_id = @prov:= vp.proveedor_id
  , vp.moneda_id = @moneda:= vp.moneda_id
        , vp.fecha = @day:= vp.fecha
  , vp.saldo = @saldo
        , vp.pendiente = @pendiente;
    select * FROM vencimientos_pendientes;    
    

 CREATE TEMPORARY TABLE rowsToDelete 
    ENGINE =  MEMORY
  SELECT vencimiento_id, fecha,proveedor_id,empresa_id,moneda_id,saldo
    FROM vencimientos_pendientes
    -- GROUP BY fecha,proveedor_id,empresa_id,moneda_id
    WHERE saldo < 0.5 AND saldo > -0.5;


    select *,'delete' from rowsToDelete;
    
    
 DELETE vp.* FROM vencimientos_pendientes vp JOIN rowsToDelete rd 
  ON (vp.fecha < rd.fecha OR (vp.fecha = rd.fecha AND vp.vencimiento_id <= rd.vencimiento_id)) 
		AND vp.proveedor_id = rd.proveedor_id AND vp.empresa_id = rd.empresa_id AND vp.moneda_id = rd.moneda_id 
  
        WHERE isPago = FALSE;
 

    SELECT vp.vencimiento_id
   , vp.fecha
   , vp.proveedor_id
         , vp.empresa_id
         , vp.moneda_id
         , vp.importe
         , vp.pendiente
         , vp.saldo
         , p.pay_met_id
         , vp.isPago
         , vp.conciliado
         , vp.saldoFinal
 FROM vencimientos_pendientes vp
  LEFT JOIN Proveedores p ON p.Id_Proveedor = vp.proveedor_id;

    DROP TEMPORARY TABLE vencimientos_pendientes;
    DROP TEMPORARY TABLE saldos_iniciales;
    DROP TEMPORARY TABLE rowsToDelete;

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


 DECLARE datSTART DATE;
 SET datFEC =  TIMESTAMP(datFEC,'23:59:59');
 SELECT FIRSTDAYOFYEAR(datFEC) INTO datSTART;

 SELECT P2.Alias, C.Id_Cliente, C.Cuenta, Gestion, Contaplus, Gestion - Contaplus as Diferencia, empresa_id, Cliente
 
 FROM Clientes C
 
 JOIN pay_met pm ON pm.id = C.pay_met_id
 
 JOIN
 
 (

 SELECT empresa_id, Id_Cliente, round(sum(Gestion),2) as Gestion, round(sum(Contaplus),2) as Contaplus 
 
 FROM
 
 (
            SELECT empresa_id, Id_Cliente, Gestion, 0 as Contaplus
     
            FROM
            
               (
                    SELECT empresa_id, Id_Cliente, -1 * Importe as Gestion
                    FROM Facturas 
                    WHERE Fecha BETWEEN datSTART AND datFEC
                    UNION ALL 
                    SELECT empresa_id, Id_Cliente, Entregado
                    FROM Recibos
                    WHERE Fechacobro BETWEEN datSTART AND datFEC
               ) G 
            
            WHERE empresa_id <> 965
            
            UNION ALL
 
            SELECT empresa_id, Id_Cliente, 0, round(nz(Eurohaber) - nz(Eurodebe),2) as Contaplus
            
            FROM bi.XDiario_ALL XD
            
            JOIN Clientes C ON C.Cuenta = XD.SUBCTA
            
            WHERE Fecha BETWEEN datSTART AND datFEC
             
 ) sub1
  
 GROUP BY empresa_id, Id_Cliente
 
 ) sub2 USING(Id_Cliente)
 
 JOIN Proveedores P2 ON P2.Id_Proveedor = sub2.empresa_id
 
 WHERE pm.deudaviva -- Cliente de perdidas no vale la pena revisarlo 
  
 HAVING ABS(Diferencia) > 0.05
 
 ORDER BY 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 `quadre_clientes_detalle` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `quadre_clientes_detalle`(IN idC INT, IN idE INT, IN datFEC DATETIME)
BEGIN

DECLARE datSTART DATE;

SET datSTART = FIRSTDAYOFYEAR(datFEC);
SET datFEC =  TIMESTAMP(datFEC,'23:59:59');

-- Creamos una tabla para almacenar las facturas del cliente, junto con el numero de veces que se repite.
DROP TEMPORARY TABLE IF EXISTS qFACTURAS;

CREATE TEMPORARY TABLE qFACTURAS
(Fecha      DATETIME,
 TPVcount INT,
 Factura  DECIMAL(10,2) SIGNED,
 Recibo  DECIMAL(10,2) SIGNED,
 CPcount INT,
 Debe  DECIMAL(10,2) SIGNED,
 Haber DECIMAL(10,2) SIGNED,
 Control INT DEFAULT 0,
 PRIMARY KEY(Fecha, TPVcount, Factura, Recibo, CPcount, Debe, Haber))
 ENGINE = InnoDB
;

-- Insertamos las facturas y los recibos de gestion.
INSERT INTO qFACTURAS

    SELECT Fecha, COUNT(*) as TPVcount, round(Importe,2) as Factura, 0 as Recibo, COUNT(*)as CPcount,round(Importe,2) as Debe, 0 as Haber, 1 as Control
    FROM Facturas
    WHERE Id_Cliente = idC AND empresa_id = idE AND Fecha BETWEEN datSTART AND datFEC
    GROUP BY Fecha, round(Importe,2)
    UNION ALL
    SELECT Fechacobro as Fecha, COUNT(*) as TPVcount, 0 as Factura, round(Entregado,2) as Recibo,COUNT(*) as CPCount, 0 as Debe, round(Entregado,2) as Haber, 3 as Control
    FROM Recibos
    WHERE Id_Cliente = idC AND empresa_id = idE AND Fechacobro BETWEEN datSTART AND datFEC
    GROUP BY Fechacobro, round(Entregado,2);

-- Insertamos los asientos de contabilidad, marcando con control = -1 las repetidas.
INSERT INTO qFACTURAS
    SELECT * 
    FROM (
    SELECT Fecha, COUNT(*) as TPVcount, round(Eurodebe,2) as Factura,  round(Eurohaber,2) as Recibo, COUNT(*) as CPcount, round(Eurodebe,2) as Debe, round(Eurohaber,2) as Haber, 2 as Control
    FROM bi.XDiario_ALL XD
    JOIN Clientes C ON C.Cuenta = XD.SUBCTA
    WHERE Id_Cliente = idC AND empresa_id = idE AND Fecha BETWEEN datSTART AND datFEC
    AND (Eurodebe <> 0 OR Eurohaber <>0)
    GROUP BY Fecha, round(Eurodebe,2), round(Eurohaber,2) 
          ) sub
    
    ON DUPLICATE KEY UPDATE Control = -1;  



-- Eliminamos las repetidas
-- DELETE FROM qFACTURAS WHERE Control = -1;

-- Arreglamos las buenas
UPDATE qFACTURAS SET TPVcount = 0, Factura = 0, Recibo = 0 WHERE Control = 2;
UPDATE qFACTURAS SET CPcount = 0, Debe = 0, Haber = 0 WHERE Control IN (1,3);

-- Mostramos el resultado
SELECT *, @saldo := @saldo +  TPVcount * (Factura + Recibo) - CPCount * ( Debe + Haber ) as Saldo 
FROM qFACTURAS
JOIN (SELECT @saldo := 0) truqui ;
DROP TEMPORARY TABLE IF EXISTS qFACTURAS;


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

 DECLARE datSTART DATE;
 SET datFEC =  TIMESTAMP(datFEC,'23:59:59');

 SELECT FIRSTDAYOFYEAR(datFEC) INTO datSTART;
 
 SELECT P2.Alias, P.Id_Proveedor, P.Cuenta, Gestion, Contaplus, Gestion - Contaplus as Diferencia, empresa_id, P.Proveedor
 
 FROM Proveedores P
 
 JOIN
 
 (

 SELECT empresa_id, Id_Proveedor, round(sum(Gestion),2) as Gestion, round(sum(Contaplus),2) as Contaplus 
 
 FROM
 
 (
            SELECT empresa_id, proveedor_id as Id_Proveedor, Gestion, 0 as Contaplus
     
            FROM
            
               (
                    SELECT empresa_id, proveedor_id, -1 * sum(cantidad) as Gestion
                    FROM recibida_vencimiento rv
                    INNER JOIN recibida r ON r.id = rv.recibida_id 
                    WHERE IFNULL(r.bookEntried,r.fecha) BETWEEN datSTART AND datFEC
                    AND r.contabilizada
                    GROUP BY r.id
                    
                    UNION ALL 
                    
                    SELECT empresa_id, id_proveedor, importe
                    FROM pago
                    WHERE Fecha BETWEEN datSTART AND datFEC
                    AND conciliado
                    AND pay_met_id <> 18 -- Saldos iniciales
               ) G 
                           
            UNION ALL
 
            SELECT empresa_id, Id_Proveedor, 0, round(nz(Eurodebe) - nz(Eurohaber),2) as Contaplus
            
            FROM bi.XDiario_ALL XD
            
            JOIN Proveedores P ON P.cuenta = XD.SUBCTA
            
            WHERE Fecha BETWEEN datSTART AND datFEC
            
 
 ) sub1
 
 
 GROUP BY empresa_id, Id_Proveedor
 
 ) sub2 USING(Id_Proveedor)
 
 JOIN Proveedores P2 ON P2.Id_Proveedor = sub2.empresa_id
 
 HAVING ABS(Diferencia) > 0.05
  
 ORDER BY P.Proveedor;
            
            
            
            
            
            

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `quadre_proveedores_detalle` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `quadre_proveedores_detalle`(IN idP INT, IN idE INT, IN datFEC DATETIME)
BEGIN

DECLARE datSTART DATE;
SET datFEC =  TIMESTAMP(datFEC,'23:59:59');

SET datSTART = FIRSTDAYOFYEAR(datFEC);

-- Creamos una tabla para almacenar las facturas del proveedor, junto con el numero de veces que se repite.
DROP TEMPORARY TABLE IF EXISTS qFACTURAS;

CREATE TEMPORARY TABLE qFACTURAS
(Fecha      DATE,
 TPVcount INT,
 Factura  DECIMAL(10,2) SIGNED,
 Recibo  DECIMAL(10,2) SIGNED,
 CPcount INT,
 Debe  DECIMAL(10,2) SIGNED,
 Haber DECIMAL(10,2) SIGNED,
 Control INT DEFAULT 0,
 PRIMARY KEY(Fecha, TPVcount, Factura, Recibo, CPcount, Debe, Haber))
 ENGINE = InnoDB
;

-- Insertamos las facturas y los pagos de gestion.
INSERT INTO qFACTURAS

    SELECT Fecha, COUNT(*) as TPVcount, round(Importe,2) as Factura
		 , 0 as Recibo, COUNT(*)as CPcount,round(Importe,2) as Debe, 0 as Haber, 1 as Control
    FROM (SELECT IFNULL(r.dateBooking,r.Fecha) as Fecha, sum(rv.cantidad) as Importe 
    FROM recibida_vencimiento rv
    JOIN recibida r ON r.id = rv.recibida_id 
    WHERE proveedor_id = idP 
    AND empresa_id = idE 
    AND IFNULL(r.dateBooking,r.Fecha) BETWEEN datSTART AND datFEC
    AND (r.contabilizada OR r.dateBooking)
    GROUP BY r.id) F
    GROUP BY Fecha, round(Importe,2)
    UNION ALL
    SELECT Fecha, COUNT(*) as TPVcount, 0 as Factura, round(importe,2) as Recibo,COUNT(*) as CPCount, 0 as Debe, round(importe,2) as Haber, 3 as Control
    FROM pago
    WHERE Id_Proveedor = idP AND empresa_id = idE AND Fecha BETWEEN datSTART AND datFEC
    AND conciliado
    GROUP BY Fecha, round(importe,2);

-- Insertamos los asientos de contabilidad, marcando con control = -1 las repetidas
INSERT INTO qFACTURAS
    SELECT * 
    FROM (
    SELECT Fecha, COUNT(*) as TPVcount, round(Eurohaber,2) as Factura,  round(Eurodebe,2) as Recibo, COUNT(*) as CPcount, round(Eurohaber,2) as Debe, round(Eurodebe,2) as Haber, 2 as Control
    FROM bi.XDiario_ALL XD
    JOIN Proveedores P ON P.cuenta = XD.SUBCTA
    WHERE Id_Proveedor = idP AND empresa_id = idE AND Fecha BETWEEN datSTART AND datFEC
    AND (Eurodebe <> 0 OR Eurohaber <>0)
    GROUP BY Fecha, round(Eurohaber,2), round(Eurodebe,2) 
          ) sub
    
    ON DUPLICATE KEY UPDATE Control = -1;  



-- Eliminamos las repetidas
DELETE FROM qFACTURAS WHERE Control = -1;

-- Arreglamos las buenas
UPDATE qFACTURAS SET TPVcount = 0, Factura = 0, Recibo = 0 WHERE Control = 2;
UPDATE qFACTURAS SET CPcount = 0, Debe = 0, Haber = 0 WHERE Control IN (1,3);

-- Mostramos el resultado
SELECT *, @saldo := @saldo + TPVcount * (Factura + Recibo) - CPcount * (Debe + Haber) as Saldo 
FROM qFACTURAS
JOIN (SELECT @saldo := 0) truqui ;

DROP TEMPORARY TABLE IF EXISTS qFACTURAS;


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

 DECLARE datSTART DATE;
 SET datFEC =  TIMESTAMP(datFEC,'23:59:59');

 SELECT FIRSTDAYOFYEAR(datFEC) INTO datSTART;
 
 SELECT P2.Alias, P.Id_Proveedor, P.Cuenta, Gestion, Contaplus, Gestion - Contaplus as Diferencia, empresa_id, P.Proveedor
 
 FROM Proveedores P
 
 JOIN
 
 (

 SELECT empresa_id, Id_Proveedor, round(sum(Gestion),2) as Gestion, round(sum(Contaplus),2) as Contaplus 
 
 FROM
 
 (
            SELECT empresa_id, proveedor_id as Id_Proveedor, Gestion, 0 as Contaplus
     
            FROM
            
               (
                    SELECT empresa_id, proveedor_id, -1 * sum(cantidad) as Gestion
                    FROM recibida_vencimiento rv
                    INNER JOIN recibida r ON r.id = rv.recibida_id 
                    WHERE r.Fecha BETWEEN datSTART AND datFEC
                    AND r.contabilizada
                    GROUP BY r.id
                    
                    UNION ALL 
                    
                    SELECT empresa_id, id_proveedor, importe
                    FROM pago
                    WHERE Fecha BETWEEN datSTART AND datFEC
                    AND conciliado
                    AND pay_met_id <> 18 -- Saldos iniciales
               ) G 
                           
            UNION ALL
 
            SELECT empresa_id, Id_Proveedor, 0, round(nz(Eurodebe) - nz(Eurohaber),2) as Contaplus
            
            FROM bi.XDiario_ALL XD
            
            JOIN Proveedores P ON P.cuenta = XD.SUBCTA
            
            WHERE Fecha BETWEEN datSTART AND datFEC
            
 
 ) sub1
 
 
 GROUP BY empresa_id, Id_Proveedor
 
 ) sub2 USING(Id_Proveedor)
 
 JOIN Proveedores P2 ON P2.Id_Proveedor = sub2.empresa_id
 
 HAVING ABS(Diferencia) > 0.05
  
 ORDER BY P.Proveedor;
            
            
            
            
            
            

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `radar` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `radar`(IN `today` DATETIME, IN `worker` INT, IN `scopeDays` SMALLINT)
    NO SQL
BEGIN
	DECLARE todayMidnight DATE DEFAULT TIMESTAMP(today,'23:59:59');
	DECLARE yesterday DATETIME;
	DECLARE maxDate DATETIME;
	DECLARE datBUF DATETIME;
	DECLARE warehouse INTEGER;
	DECLARE done BIT DEFAULT 0;
	DECLARE visible_calc INTEGER;
	DECLARE available_calc INTEGER;
	DECLARE dateStart DATE;

	SET dateStart = TIMESTAMPADD(MONTH, -2, CURDATE());
	SELECT TIMESTAMPADD(DAY, -1, today) INTO yesterday;

	-- Lo quitamos despues de campaña
	SELECT TIMESTAMP(TIMESTAMPADD(DAY, scopeDays, yesterday),'23:59:59') INTO maxDate;
	-- SELECT TIMESTAMP(TIMESTAMPADD(DAY, 14, yesterday),'23:59:59') INTO maxDate;
	-- Creamos una tabla con los Comerciales de los que se mostraran los tickets

	IF worker = 2 AND curdate() between '2018-07-02' AND '2018-07-09' THEN
		SET worker = 43;
	END IF;

	CALL subordinate(worker, TRUE);

	-- Se genera una tabla con los tickets representados

	DROP TEMPORARY TABLE IF EXISTS ticketRange;
	CREATE TEMPORARY TABLE ticketRange
		(INDEX (Id_Ticket))
		ENGINE = MEMORY
		SELECT T.Id_Ticket, T.Id_Cliente, C.Id_Trabajador
			FROM Tickets T
				LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket
				JOIN Clientes C on C.Id_Cliente = T.Id_Cliente 
				JOIN subordinate s1 ON C.Id_Trabajador = s1.Id_Trabajador
			WHERE Fecha >=  yesterday
				AND Fecha <=  maxDate AND T.Factura Is NULL
				AND IFNULL(tls.alertLevel,0) < 3;

	INSERT INTO ticketRange
		SELECT Id_Ticket, s.Id_Cliente, s.Id_Trabajador
			FROM sharingclient s
				JOIN Tickets T USING(Id_Cliente)
				LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket
				JOIN subordinate s2 ON s.Id_Trabajador = s2.Id_Trabajador
			WHERE maxDate >= datSTART 
				AND datEND >= yesterday
				AND date(Fecha) >= IF(yesterday > datSTART, yesterday, datSTART)
				AND date(Fecha) <= IF(datEND > maxDate, maxDate, datEND)
				AND IFNULL(tls.alertLevel,0) < 3;

	INSERT INTO ticketRange
		SELECT Id_Ticket, C.Id_Cliente, s.Id_Suplente
			FROM Clientes C       
				JOIN Tickets T USING(Id_Cliente)
				LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket
				JOIN sharingcart s ON s.Id_Trabajador = C.Id_Trabajador
				JOIN subordinate su on su.Id_Trabajador = Id_Suplente
			WHERE maxDate >= datSTART 
				AND datEND >= yesterday
				AND date(Fecha) >= IF(yesterday > datSTART, yesterday, datSTART)
				AND date(Fecha) <= IF(datEND > maxDate, maxDate, datEND)
				AND IFNULL(tls.alertLevel,0) < 3;

	INSERT INTO ticketRange
		SELECT Id_Ticket, C.Id_Cliente, C.Id_Trabajador
			FROM Clientes C       
				JOIN Tickets T USING(Id_Cliente)
				LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket
				JOIN workerTeamCollegues w ON w.collegueId = C.Id_Trabajador
			WHERE Fecha >=  yesterday
				AND Fecha <=  maxDate AND T.Factura Is NULL 
				AND IFNULL(tls.alertLevel,0) < 3
				AND w.workerId = worker;
		
	IF (SELECT COUNT(*) FROM ticketRange) THEN 

		-- Generamos varias auxiliares (ya podian los de mysql haber solucionado esto)

		DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
		CREATE TEMPORARY TABLE tmp.client_list
			(INDEX (Id_Cliente))
			ENGINE = MEMORY
				SELECT DISTINCT Id_Cliente FROM ticketRange;

		DROP TEMPORARY TABLE IF EXISTS cr5;
		CREATE TEMPORARY TABLE cr5
			(INDEX (Id_Cliente))
			ENGINE = MEMORY
				SELECT Id_Cliente FROM tmp.client_list;
			
		DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
		CREATE TEMPORARY TABLE tmp.ticket
			ENGINE = MEMORY
			SELECT t.Id_Ticket ticketFk
				FROM Tickets t
					STRAIGHT_JOIN tmp.client_list c ON t.Id_Cliente = c.Id_Cliente
				WHERE Fecha BETWEEN dateStart AND  maxDate 
				AND Factura IS NULL;

		CALL vn.ticketGetTotal;

		-- Generamos otra tabla temporal con los Tickets_iva
				
		DROP TEMPORARY TABLE IF EXISTS tt3;
		CREATE TEMPORARY TABLE tt3
			ENGINE = MEMORY
			SELECT t.ticketFk, tt.total, tr.* 
				FROM tmp.ticket t
					LEFT JOIN tmp.ticketTotal tt ON t.ticketFk = tt.ticketFk
					JOIN ticketRange tr ON tr.Id_Ticket = t.ticketFk;

		-- Generamos la lista de tickets y sus datos 
				
		DROP TEMPORARY TABLE IF EXISTS Radartest;
		CREATE TEMPORARY TABLE Radartest
			SELECT IF(C.Id_Trabajador = worker, 1, 0) as Propio,
				Credito,
				CAST(Riesgo AS DECIMAL (10,2)) Riesgo,
				-- Greuge,
				T.Id_Ticket,
				T.warehouse_id as wh,
				T.Fecha,
				T.Alias,
				-- T.Vista,
				REPEAT(' ',50) as problem,
				T.Agencia Tipo,
				-- C.Id_Trabajador,
				T.workerId AS Id_Trabajador,
				T.Solucion,
				T.Localizacion,
				IFNULL(state,'LIBRE') as Estado, 
				alertLevel,
				alertCode,
				Date(T.Fecha) as Fecha_Simple,
				CAST(T.Importe AS DECIMAL (10,2)) Importe,
				C.Descuento,
				C.calidad,
				C.Id_Cliente,
				p.`name` provincia
			FROM Clientes C
				JOIN (
					SELECT T.* ,  A.Vista, A.Agencia, s.`name` as state, alertLevel,
							s.`code` AS alertCode, tt3.Id_Trabajador AS workerId,
							tt3.total as Importe,
							0 AS inacabable
							-- (-1 < ifnull(order_id,-1)) as isbionic
						FROM Tickets T
							LEFT JOIN vn.ticketState ts on ts.ticket = T.Id_Ticket
							LEFT JOIN vn2008.state s on s.id = ts.state
							JOIN tt3 ON tt3.ticketFk = T.Id_Ticket
							JOIN Agencias A ON A.Id_Agencia = T.Id_Agencia
						-- WHERE T.Etiquetasemitidas = FALSE
						GROUP BY T.Id_Ticket
				) AS T ON T.Id_Cliente = C.Id_Cliente
				LEFT JOIN Consignatarios co ON co.Id_Consigna = T.Id_Consigna
				LEFT JOIN province p ON p.province_id = co.province_id
				LEFT JOIN (
					SELECT TOTAL.Id_Cliente, ROUND(SUM(amount),2) as Riesgo
						FROM (
							SELECT cl.Id_Cliente, amount
								FROM bi.customer_risk cr
									JOIN tmp.client_list cl ON cr.customer_id = cl.Id_Cliente
							UNION ALL
							SELECT t.Id_Cliente, tt.total
								FROM tmp.ticketTotal tt
									JOIN Tickets t ON t.Id_Ticket = tt.ticketFk
									JOIN cr5 C ON C.Id_Cliente = t.Id_Cliente
								WHERE t.Fecha BETWEEN dateStart AND  maxDate  
									AND t.Factura is null
						) as TOTAL GROUP BY TOTAL.Id_Cliente
				) AS Peligros ON Peligros.Id_Cliente = C.Id_Cliente;

		-- Actualizamos el Riesgo con los tickets futuros

		SET @cliente:= 0;
		SET @riesgo := 0;
				
		UPDATE Radartest
			SET Riesgo = IF(@cliente <> @cliente:= Id_Cliente,
				-Importe + @riesgo:= - Riesgo + Importe,
				-Importe + @riesgo:= @riesgo + Importe
			)
			ORDER BY Id_Cliente, Fecha_Simple DESC;
			
		DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list;
		
		CREATE TEMPORARY TABLE tmp.ticket_list
		SELECT Id_Ticket, Id_Cliente FROM Radartest;
		
		CALL prepare_client_list;
		CALL production_buffer_problems;

		UPDATE Radartest r
			JOIN (    
				SELECT Id_Ticket, GROUP_CONCAT(problem) problem
				FROM tmp.buffer_problems
				GROUP BY Id_Ticket
			) p on p.Id_Ticket = r.Id_Ticket
			SET r.problem = p.problem;

		SELECT R.*, Riesgo + Credito as Risk , CodigoTrabajador 
			FROM Radartest R
				JOIN vn2008.Trabajadores trab on R.Id_Trabajador=trab.Id_Trabajador;
	END IF;

	DROP TEMPORARY TABLE ticketRange;
	DROP TEMPORARY TABLE subordinate;
	DROP TEMPORARY TABLE tmp.client_list;
	DROP TEMPORARY TABLE cr5;
	DROP TEMPORARY TABLE tmp.ticket; 
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `radar_lostcalls` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `radar_lostcalls`()
BEGIN

SELECT  Averiguar_ComercialCliente(C.Id_Cliente, calldate) as Comercial, C.Cliente AS Cliente, A2.Telefono
, A.Nombre as Destino, t3.* FROM
  
( SELECT * FROM 
           (SELECT * FROM 
                      (  SELECT dstchannel, disposition, calldate,src,dst,1 as missed,  TIMESTAMPADD(SECOND,duration,calldate) as hangupdate,  
                                     TIMESTAMPADD(SECOND, (-billsec),TIMESTAMPADD(SECOND,duration,calldate) ) as answerdate,
                                     duration, billsec FROM 
                                                   (SELECT * FROM 
                                                              (SELECT * FROM cdr WHERE calldate > timestampadd(day, -4,curdate()) ORDER BY calldate DESC ) t  
                                                               GROUP BY src
                                                    ) cdr_sub 
                                                   WHERE (dstchannel = '' or disposition <> 'ANSWERED' or lastapp = 'Playback') AND dstchannel <> 'killed'
                                                   AND src > 6000   
                                                   AND calldate > TIMESTAMPADD(DAY,-4,CURDATE())  
                         UNION ALL  
                         SELECT dstchannel, disposition, calldate,dst, 0,0,calldate,calldate,0,0 
                         FROM cdr 
                         WHERE dst > 6000  
                         AND calldate > TIMESTAMPADD(WEEK,-4,CURDATE())  
                     ) t 
                    ORDER BY calldate DESC  
          ) t2 GROUP BY src 
            HAVING missed 
            ORDER BY calldate DESC 
) t3 

LEFT JOIN v_Agenda2 A2 ON CAST(A2.Telefono AS SIGNED) = t3.src 
LEFT JOIN v_Agenda2 A ON CAST(A.Telefono AS SIGNED) = t3.dst
LEFT JOIN Clientes C ON C.Id_Cliente = A2.Id AND A2.Tipo = 'C'
;


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `radar_negativos` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `radar_negativos`(IN v_force BOOLEAN, IN intRANGE INT)
BEGIN

/**
 * Calcula una tabla con el máximo negativo visible para cada producto y almacen
 *  
 * @param v_force Fuerza el recalculo del stock
 * @param intRANGE Numero de dias a considerar
**/

    CALL `cache`.stock_refresh(v_force);
    SET @aid = NULL;
	call article_minacum(NULL,CURDATE(),intRANGE);
    
    SELECT a.Id_Article, a.Article, sub.warehouse_id, p.`name` producer, a.Medida, a.Categoria
         , w.name as Almacen, sum(IFNULL(amount,0)) as Negativo
    FROM (SELECT item_id, warehouse_id, amount
          FROM cache.stock
          WHERE amount > 0
		  UNION ALL
          SELECT article_id, warehouse_id, amount
		  FROM article_minacum
		 ) sub
         JOIN warehouse w on w.id = warehouse_id
         JOIN Articles a on a.Id_Article = item_id
         LEFT JOIN producer p on p.producer_id = a.producer_id
         JOIN Tipos t on t.tipo_id = a.tipo_id
         JOIN reinos r on r.id = t.reino_id
         WHERE w.tpv 
         AND t.tipo_id NOT IN (61, 101, 100, 99, 180, 7, 259, 257)
         AND r.display <> 0
         AND a.Id_Article NOT IN (95,98)
	GROUP BY item_id, warehouse_id
    HAVING negativo < 0;
    
	DROP TEMPORARY TABLE IF EXISTS article_minacum;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `raidUpdate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `raidUpdate`()
BEGIN
	UPDATE travel
		SET shipment = CURDATE(),
			landing = TIMESTAMPADD(DAY, 1, CURDATE())
        WHERE id = 12505;
    
    UPDATE Entradas e
		JOIN Entradas_Auto ea USING (Id_Entrada)
        JOIN travel t ON t.id = e.travel_id
        JOIN (
			SELECT *
				FROM (
					SELECT id, landing, warehouse_id, warehouse_id_out  
						FROM travel
							JOIN (
								SELECT warehouse_id, warehouse_id_out
									FROM Entradas_Auto ea
										JOIN Entradas e USING(Id_Entrada)
										JOIN travel t ON t.id = e.travel_id
									GROUP BY warehouse_id, warehouse_id_out
							) t USING (warehouse_id, warehouse_id_out)
						WHERE shipment > CURDATE() AND delivered = FALSE
						ORDER BY landing
				) t  
				GROUP BY warehouse_id, warehouse_id_out
		) t USING (warehouse_id, warehouse_id_out)
        SET e.travel_id = t.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 `rateView` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `rateView`()
BEGIN

	SELECT 
			t.year as año,
			t.month as  mes, 
			pagos.dolares,
			pagos.cambioPractico,
			CAST(sum(divisa) / sum(bi) as DECIMAL(5,4)) as cambioTeorico,
			pagos.cambioOficial
		FROM recibida r
			JOIN time t ON t.date = r.fecha
			JOIN recibida_iva ri ON r.id = ri.recibida_id
			JOIN
			(	
				SELECT 
					t.year as Año,
					t.month as  Mes, 
					cast(sum(divisa) as DECIMAL(10,2)) as dolares,
					cast(sum(divisa) / sum(importe) as DECIMAL(5,4)) as cambioPractico,
					cast(rr.rate * 0.998 as DECIMAL(5,4)) as cambioOficial
				FROM pago p
				JOIN time t ON t.date = p.fecha
				JOIN reference_rate rr ON rr.date = p.fecha AND moneda_id = 2
				WHERE divisa 
				AND fecha >= '2015-01-11' 
				GROUP BY t.year, t.month
			) pagos ON t.year = pagos.Año AND t.month = pagos.Mes
		WHERE moneda_id = 2
			AND fecha >= '2015-01-01'
			AND divisa 
			AND bi
		GROUP BY t.year, t.month;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `recalculator` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `recalculator`(vTicketId INT)
BEGIN
	DECLARE vWh INT;
	DECLARE vDate DATE;
	DECLARE vCustomerId INT;
	DECLARE vServiFac INT;

	SELECT warehouse_id, Fecha, Id_Cliente, IFNULL(Factura, 0) != 0 OR Etiquetasemitidas != 0
		INTO vWh, vDate, vCustomerId, vServiFac
		FROM Tickets
		WHERE Id_Ticket = vTicketId;

	IF NOT vServiFac
    THEN
		DROP TEMPORARY TABLE IF EXISTS item;

		CREATE TEMPORARY TABLE item
			(INDEX (id))
			ENGINE = MEMORY
			SELECT Id_Article id, Id_Movimiento
				FROM Movimientos
				WHERE Preciofijado = FALSE
					AND Id_Ticket = vTicketId
					AND (Id_Article < 82 OR Id_Article > 100);

		CALL item_buy (vWh, vDate);
		CALL item_buy_price	(vCustomerId, vDate, vWh);

		UPDATE Movimientos
			JOIN item USING (Id_Movimiento)
			SET Preu = price,
				Descuento = discount;

		SELECT * FROM item; 

		DROP TEMPORARY TABLE item;
	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 `recalculator_plus` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `recalculator_plus`(vTicketId INT)
BEGIN
	CALL recalculator (vTicketId);

	CREATE TEMPORARY TABLE movement
		ENGINE = MEMORY
		SELECT Id_Movimiento, Id_Article, Preu, Descuento, Cantidad, ABS(Preciofijado) AS PrecioFijado
			FROM Movimientos
			WHERE Id_Ticket = vTicketId
				AND Reservado = FALSE
				AND Id_Article NOT BETWEEN 85 AND 100
				AND Id_Movimiento NOT IN
				(
					SELECT Id_Movimiento FROM Movimientos
						WHERE Id_Ticket = vTicketId
							AND Reservado = FALSE
							AND Id_Article NOT BETWEEN 71 AND 100
						GROUP BY Id_Article, Preu, Descuento, ABS(PrecioFijado)
							HAVING COUNT(*) = 1
					UNION ALL
					SELECT Id_Movimiento FROM movement_label
				) FOR UPDATE;
		
	CREATE TEMPORARY TABLE movement_u
		ENGINE = MEMORY
		SELECT Id_Movimiento, Id_Article, Preu, Descuento, PrecioFijado, SUM(Cantidad) amount
			FROM movement
			GROUP BY Id_Article, Preu, Descuento, PrecioFijado;

	UPDATE Movimientos 
		JOIN movement_u u USING(Id_Movimiento) 
        JOIN Tickets T ON T.Id_Ticket = vTicketId
		SET Cantidad = amount;

	DELETE movement FROM movement JOIN movement_u USING (Id_Movimiento);
	DELETE Movimientos FROM Movimientos JOIN movement USING (Id_Movimiento);

	DROP TEMPORARY TABLE movement;
	DROP TEMPORARY TABLE movement_u;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `recibidaIvaDivisaUpdate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `recibidaIvaDivisaUpdate`(IN vRecibidaId INT)
BEGIN

/* Actualiza el valor de la divisa en función del cambio oficial para el dia de expedicion
*/
	UPDATE recibida_iva
		SET bi = NULL
        WHERE recibida_id = vRecibidaId
        AND divisa IS NOT NULL;

	UPDATE recibida_iva ri
		JOIN recibida r ON r.id = ri.recibida_id
        JOIN reference_rate rr ON rr.date = r.fecha AND r.moneda_id = rr.moneda_id
	SET ri.bi = ri.divisa / rr.rate
		WHERE r.id = vRecibidaId;
        
    UPDATE recibida_vencimiento rv
		JOIN recibida r ON r.id = rv.recibida_id
        JOIN reference_rate rr ON rr.date = r.fecha AND r.moneda_id = rr.moneda_id
	SET rv.cantidad = rv.divisa / rr.rate
		WHERE r.id = vRecibidaId;     

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

	DECLARE vRate DOUBLE DEFAULT 1;
    DECLARE vDated DATE;
        
	SELECT MAX(rr.date) INTO vDated
		FROM reference_rate rr
			JOIN recibida r ON r.id = vId
		WHERE rr.date <= r.fecha 
			AND rr.moneda_id = r.moneda_id ;
    
    IF vDated THEN
    
		SELECT rate INTO vRate
			FROM reference_rate
			WHERE `date` = vDated;
	END IF;
    
	DELETE FROM recibida_iva WHERE recibida_id = vId;

    INSERT INTO recibida_iva(recibida_id, iva_id, bi,gastos_id,divisa)
		SELECT r.id,  
			CASE 
				WHEN p.cuenta LIKE '___4______' THEN 120 -- 71 2018-04-24 JGF-PAK
				WHEN p.cuenta LIKE '___1______' THEN 36 
				WHEN p.cuenta LIKE '___3______' THEN 121 -- 63 2018-05-15 PAK 
			END,  
			SUM(Costefijo * Cantidad) / IFNULL(vRate,1) ,
			6003000000,  
			IF(r.moneda_id = 1,NULL,SUM(Costefijo * Cantidad )) 
			FROM recibida r 
				JOIN Entradas e ON e.recibida_id = r.id
				JOIN Proveedores p ON p.Id_Proveedor = e.Id_Proveedor
				JOIN Compres c ON c.Id_Entrada = e.Id_Entrada
				LEFT JOIN reference_rate rr ON rr.moneda_id = r.moneda_id AND rr.date = r.fecha
			WHERE r.id = vId;

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

	DELETE FROM recibida_vencimiento
		WHERE recibida_id = lngRecibida;

	INSERT INTO recibida_vencimiento (recibida_id,fecha,cantidad,divisa) 
		SELECT   lngRecibida,
				IF(pay_day,next_venc(t.fecha,detalle,pay_day),TIMESTAMPADD(DAY,detalle,t.fecha)),  
				IF((@cont:=@cont+1) < cont,TRUNCATE(venc / cont,2),venc-(TRUNCATE(venc / cont,2)*(cont-1))) venc,  
				IF(@cont < cont,TRUNCATE(divisa / cont,2),divisa-(TRUNCATE(divisa / cont,2)*(cont-1))) divisa  
			FROM (
				SELECT  SUM((1 + (IVA / 100)*(p.pais_id = p2.pais_id)) * bi)/COUNT(DISTINCT(pdd.detalle)) venc,  
						SUM(ri.divisa)/COUNT(DISTINCT(pdd.detalle)) divisa,
						r.id,
						p.pay_dem_id,  
						r.empresa_id,
						COUNT(DISTINCT(pdd.detalle)) cont,
						p.pay_day,
						r.fecha 
					FROM recibida r 
						INNER JOIN recibida_iva ri ON r.id = ri.recibida_id 
						INNER JOIN iva_codigo AS i ON ri.iva_id=i.id 
						INNER JOIN Proveedores p ON p.Id_Proveedor=r.proveedor_id   
						INNER JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id 
						INNER JOIN pay_dem_det pdd ON p.pay_dem_id = pdd.id  
					WHERE r.id = lngRecibida   
					GROUP BY recibida_id
				) t 
				INNER JOIN  pay_dem_det pdd ON t.pay_dem_id = pdd.id 
				INNER JOIN (SELECT @cont:=0) t2 
			GROUP BY detalle;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `recibida_select` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `recibida_select`(IN recibida INT)
BEGIN
 DECLARE cta_proveed VARCHAR(10);
 DECLARE cta_proveeda VARCHAR(10);
 DECLARE v_num_recibida INT;
 DECLARE dblRefRate,dblRefMin,dblRef DOUBLE;
	
	DECLARE NEW_id,NEW_empresa_id,NEW_proveedor_id INT;
	DECLARE NEW_serie VARCHAR(1);
	DECLARE NEW_fecha DATE;
	DECLARE NEW_num_recibida VARCHAR(10);
	DECLARE NEW_sref VARCHAR(20);
	
	SELECT id,empresa_id,proveedor_id,serie,fecha,num_recibida,sref 
		INTO NEW_id,NEW_empresa_id,NEW_proveedor_id, NEW_serie,NEW_fecha,NEW_num_recibida, NEW_sref
		FROM recibida WHERE id = recibida;


 SELECT rate INTO dblRefRate FROM reference_rate WHERE date = (SELECT MAX(date) FROM reference_rate 
 WHERE date <= (SELECT t.shipment FROM
 recibida_entrada re 
 INNER JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada
 LEFT JOIN travel t ON t.id = e.travel_id 
 WHERE re.awb_recibida = recibida GROUP BY re.awb_recibida));
 
 SELECT rate INTO dblRefMin FROM reference_min WHERE date=(SELECT MAX(date) FROM reference_min 
 WHERE date<=(SELECT t.shipment FROM
 recibida_entrada re 
 INNER JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada
 LEFT JOIN travel t ON t.id = e.travel_id 
 WHERE re.awb_recibida = NEW_id GROUP BY re.awb_recibida));

 -- IF dblRefMin < dblRefRate THEN
 -- SET dblRef = dblRefRate;
 -- ELSE
 -- SET dblRef =dblRefMin;
 -- END IF;
 SELECT IFNULL(MAX(r.num_recibida) + 1,1) INTO v_num_recibida FROM recibida r
 WHERE r.serie LIKE NEW_serie 
 AND YEAR(r.fecha) = YEAR(NEW_fecha)
 AND r.empresa_id = NEW_empresa_id GROUP BY r.empresa_id;
 
 SET NEW_num_recibida = IFNULL(v_num_recibida,1);	
 SELECT REPLACE(cuenta,' ','') INTO cta_proveed FROM Proveedores WHERE Id_Proveedor=NEW_proveedor_id;


SELECT a,NEW_fecha,subcta,contra,concepto,eurodebe,eurohaber,baseeuro,NEW_serie,NEW_sref,iva,
 (SELECT CONCAT(NEW_serie,'/', LPAD(v_num_recibida,5,'0'))),l340,LRECT349,TIPOOPE,AUXILIAR,NEW_empresa_id
			FROM

			(SELECT MAX(ASIEN) + 1 as a FROM XDiario) t

			INNER JOIN

			(

 SELECT *,NEW_serie FROM 

 (SELECT CONCAT('s/fra',RIGHT(sref,8),':',LEFT(Proveedor, 10)) concepto FROM Proveedores

 INNER JOIN recibida ON Id_Proveedor = proveedor_id WHERE id = NEW_id) t4

 INNER JOIN(
 -- Linea del proveedor/acreedor
				SELECT subcta,'' contra,eurodebe,ROUND(SUM(eurohaber) + 0.0001,2)	eurohaber,baseeuro,0 iva, l340,LRECT349,TIPOOPE,'' AUXILIAR

						FROM (

							SELECT cta_proveed subcta,

							NULL eurodebe, ROUND((1+(iva/100)*(r.serie = 'R'))*SUM(bi),2) eurohaber, NULL baseeuro,ri.recibida_id, 0 l340,0 LRECT349,' ' TIPOOPE

							FROM recibida r

							INNER JOIN recibida_iva ri ON ri.recibida_id = r.id	INNER JOIN iva_codigo ic ON ri.iva_id = ic.id 

							INNER JOIN Proveedores p ON p.Id_Proveedor=r.proveedor_id
							INNER JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id

								WHERE r.id = NEW_id GROUP BY iva) t

							GROUP BY recibida_id

			UNION ALL
 -- Linea de iva
				SELECT ic.codigo,cta_proveed contra,

					ROUND(iva/100*SUM(ri.bi) + 0.0001,2) eurodebe, NULL eurohaber,

					ROUND(SUM(ri.bi),2) baseeuro,iva, 1 l340,(NOT ((p.pais_id <> p2.pais_id) AND pa.CEE < 2)) LRECT349,TIPOOPE,
					IF(pa2.CEE < 2 AND ri2.gastos_id IS NULL,'','*') AUXILIAR -- JGF 30-01-2014 IF(NOT ((p.pais_id <> p2.pais_id) AND pa.CEE < 2),'*','') -- ANTES '' AUXILIAR JGF < 30-01-2014
-- AND ri.gastos_id LIKE '4751______'
							FROM recibida r

						INNER JOIN recibida_iva ri ON ri.recibida_id = r.id 

						LEFT JOIN recibida_iva ri2 ON ri2.recibida_id = r.id AND ri2.gastos_id LIKE '4751______'
						
						INNER JOIN iva_codigo ic ON ri.iva_id = ic.id

						INNER JOIN iva_tipo it ON ic.iva_tipo_id = it.id

						INNER JOIN Gastos g ON ri.gastos_id = g.Id_Gasto AND g.iva_tipo_id = ic.iva_tipo_id
						
						INNER JOIN Proveedores p ON p.Id_Proveedor=r.proveedor_id
						
						INNER JOIN Paises pa ON p.pais_id = pa.Id
						
						INNER JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id
						
						INNER JOIN Paises pa2 ON p2.pais_id = pa2.Id
							WHERE r.id = NEW_id AND g.conbase AND link GROUP BY iva

			UNION ALL
 -- Linea iva inversor sujeto pasivo
				SELECT ic2.codigo,cta_proveed contra,

					 NULL eurodebe, ROUND(ic2.iva/100*SUM(bi) + 0.0001,2) eurohaber,

					ROUND(SUM(bi),2) baseeuro,ic2.iva, 1 l340,0 LRECT349,TIPOOPE,'*' AUXILIAR

						FROM recibida r

						INNER JOIN recibida_iva ri ON ri.recibida_id = r.id 

						INNER JOIN iva_codigo ic ON ri.iva_id = ic.id

						INNER JOIN iva_codigo ic2 ON ic2.link = ic.link AND ic.id <> ic2.id						

						INNER JOIN iva_tipo it ON ic.iva_tipo_id = it.id

							WHERE r.id = NEW_id AND ic2.link GROUP BY ic2.iva

			UNION ALL
 -- Linea de Gastos
				SELECT if(gastos_id LIKE '4751______',LPAD(RIGHT(cta_proveed ,4),10,gastos_id),gastos_id),cta_proveed ,

					if(gastos_id LIKE '4751______',NULL,ABS(ROUND(SUM(bi),2))) ,

 if(gastos_id LIKE '4751______',ABS(ROUND(SUM(bi),2)),NULL) ,

 NULL ,0, 0 l340,0 LRECT349,' ' TIPOOPE,'' AUXILIAR

						FROM recibida r

						INNER JOIN recibida_iva ri ON ri.recibida_id = r.id

 INNER JOIN Proveedores p ON p.Id_Proveedor=r.proveedor_id 

							WHERE r.id = NEW_id AND gastos_id <> 5660000002 GROUP BY gastos_id

 ) t2

 UNION ALL


 -- Extracomunitarias gasto contra proveedor/acreedor 
 SELECT CONCAT('COMPRA s/fra ',sref,':',LEFT(p.Proveedor, 10)) concepto ,gastos_id,cuenta,

 ROUND(SUM(bi)/IF(r.serie='W',dblRefRate,1)* (re.percentage / 100),2),NULL ,IF( @a:=@a+1 ,NULL,NULL) ,0, 0 l340,0 LRECT349,' ' TIPOOPE,'' AUXILIAR,r.serie

 FROM recibida_entrada re
		
 INNER JOIN recibida_iva ri ON re.recibida_id = ri.recibida_id
			
 INNER JOIN recibida r ON r.id = ri.recibida_id

 INNER JOIN Proveedores p ON p.Id_Proveedor = r.proveedor_id

 INNER JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada

 LEFT JOIN travel t ON t.id = e.travel_id
			
			INNER JOIN (SELECT @a:=0,@cont:=1,@total:=0,@base:=2) t1

 WHERE re.awb_recibida = NEW_id AND re.percentage GROUP BY r.id

UNION ALL

 -- Extracomunitarias proveedor contra gasto
 SELECT CONCAT('COMPRA s/fra ',sref,':',LEFT(p.Proveedor, 10)) concepto ,p.cuenta subcta,gastos_id,

 NULL eurodebe, ROUND((1+(iva/100)*(r.serie = 'R'))*SUM(bi)/IF(r.serie='W',dblRefRate,1)* (re.percentage / 100),2) eurohaber,
	
 NULL baseeuro,0 iva, 0 l340,0 LRECT349,' ' TIPOOPE,'' AUXILIAR,r.serie
 -- antes sols iva
 FROM recibida_entrada re 

 INNER JOIN recibida_iva ri ON re.recibida_id = ri.recibida_id

 INNER JOIN recibida r ON r.id = ri.recibida_id

 INNER JOIN iva_codigo ic ON ri.iva_id = ic.id 

 INNER JOIN Proveedores p ON Id_Proveedor = r.proveedor_id
				
				INNER JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id

 WHERE re.awb_recibida = NEW_id AND re.percentage GROUP BY r.id

UNION ALL

 -- Linea de iva adquisicion
				SELECT CONCAT('ADQUI. INTRA FRA ',sref),ic.codigo,p.cuenta contra,

					ROUND(iva/100*SUM(ri.importe) + 0.0001,2) eurodebe, NULL eurohaber,

					ROUND(SUM(ri.importe),2) baseeuro,iva, 1 l340,1 LRECT349,TIPOOPE,'' AUXILIAR,r.serie

						FROM awb_recibida ar
						
						JOIN awb a ON ar.awb_id = a.id

						JOIN iva_codigo ic ON a.iva_id = ic.id

						JOIN iva_tipo it ON ic.iva_tipo_id = it.id

						JOIN Proveedores p ON a.transitario_id = p.Id_Proveedor

						JOIN recibida_intrastat ri ON ri.recibida_id = ar.recibida_id

						JOIN recibida r ON r.id = ri.recibida_id
						
						JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id

							WHERE ar.recibida_id = NEW_id AND (p.pais_id <> p2.pais_id)
							GROUP BY iva

			UNION ALL
 
 -- Linea de iva adquisicion
				SELECT CONCAT('ADQUI. INTRA FRA ',sref),ic2.codigo,p.cuenta contra,

					 NULL eurodebe, ROUND(ic2.iva/100*SUM(ri.importe) + 0.0001,2) eurohaber,

					ROUND(SUM(ri.importe),2) baseeuro,ic2.iva, 1 l340,0 LRECT349, TIPOOPE,'' AUXILIAR,r.serie

						FROM awb_recibida ar
						
						JOIN awb a ON ar.awb_id = a.id 

						JOIN iva_codigo ic ON a.iva_id = ic.id

						JOIN iva_codigo ic2 ON ic2.link = ic.link AND ic.id <> ic2.id						

						JOIN iva_tipo it ON ic.iva_tipo_id = it.id

						JOIN Proveedores p ON a.transitario_id = p.Id_Proveedor

						JOIN recibida_intrastat ri ON ri.recibida_id = ar.recibida_id

						JOIN recibida r ON r.id = ar.recibida_id
						
						JOIN Proveedores p1 ON p1.Id_Proveedor = r.proveedor_id
												
						JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id

							WHERE ar.recibida_id = NEW_id AND (p.pais_id <> p2.pais_id) GROUP BY ic2.iva
 
 UNION ALL
 -- Linea iva importacion
 SELECT concepto,subcta,Cuenta,
 IF (NOT ((ppais_id <> p2pais_id) AND CEE < 2),
 (IF(@cont<@a,
 eurodebe,
 ROUND(bi-@total,2)
 ))
 ,NULL)eurodebe,eurohaber,baseeuro,iva,
 IF(@total:=@total+eurodebe ,0,0) l340,0 LRECT349,
 IF(@cont:=@cont+1,'','') TIPOOPE,'*' AUXILIAR,serie FROM (
 
 SELECT CONCAT('COMPRA FRA ',p.Proveedor) concepto,ic.codigo subcta,p.Cuenta,ic.iva,
 red(sum(costefijo * Cantidad / sub1.costetotal * sub2.importe)*0.21) eurodebe,NULL eurohaber,
 ROUND(sum(costefijo * Cantidad / sub1.costetotal * sub2.importe),2) baseeuro,ri.bi,r.serie,pa.CEE,p.pais_id ppais_id,p2.pais_id p2pais_id

 FROM awb_recibida ar
						
 JOIN recibida_entrada re ON ar.recibida_id = re.awb_recibida
			
			JOIN Compres c ON c.Id_Entrada = re.Id_Entrada

 INNER JOIN Articles a ON a.Id_Article = c.Id_Article

 INNER JOIN (

 SELECT a.Codintrastat, sum(c.costefijo * c.Cantidad) as costetotal

 FROM Compres c 

 JOIN Articles a ON a.Id_Article = c.Id_Article

 JOIN recibida_entrada re ON re.Id_Entrada = c.Id_Entrada
				
				JOIN awb_recibida ar ON ar.recibida_id = re.awb_recibida
						
				JOIN awb aw ON ar.awb_id = aw.id

 WHERE ar.recibida_id = NEW_id AND re.percentage

 GROUP BY a.Codintrastat

 ) sub1 USING(Codintrastat)

 INNER JOIN (

 SELECT Codintrastat,ri.importe

 FROM recibida_intrastat ri

 WHERE ri.recibida_id = NEW_id

 ) sub2 USING(Codintrastat)

			-- JOIN recibida_intrastat ri ON ar.awb_recibida = ri.recibida_id and ri.Codintrastat = sub1.Codintrastat

 JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada

 JOIN Proveedores p ON p.Id_Proveedor = e.Id_Proveedor
			
			JOIN Paises pa ON p.pais_id = pa.Id
							 
 JOIN recibida_iva ri ON ri.recibida_id = re.awb_recibida
 
 JOIN recibida_iva ri2 ON ri2.recibida_id = re.recibida_id
 
 JOIN iva_codigo ic ON ic.id = ri2.iva_id 
 
 JOIN recibida r ON r.id = re.recibida_id
			
			JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id

 WHERE re.awb_recibida = NEW_id AND re.percentage AND IF(cta_proveed like '___0______',ri.gastos_id = 5660000002,TRUE)
 -- canvie el cta_proveed like '___1______' per cero cuidao en les van de put

 GROUP BY p.Id_Proveedor

 
 -- antes GROUP BY a.Codintrastat,Id_Entrada

) t3)t4;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `recibida_select2` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `recibida_select2`(IN recibida INT)
BEGIN
    DECLARE cta_proveed VARCHAR(10);
    DECLARE cta_proveeda VARCHAR(10);
    DECLARE v_num_recibida INT;
    DECLARE dblRefRate,dblRefMin,dblRef DOUBLE;
	
	DECLARE NEW_id,NEW_empresa_id,NEW_proveedor_id INT;
	DECLARE NEW_serie VARCHAR(1);
	DECLARE NEW_fecha DATE;
	DECLARE NEW_num_recibida VARCHAR(10);
	DECLARE NEW_sref VARCHAR(20);
	
	SELECT id,empresa_id,proveedor_id,serie,fecha,num_recibida,sref 
		INTO NEW_id,NEW_empresa_id,NEW_proveedor_id, NEW_serie,NEW_fecha,NEW_num_recibida, NEW_sref
		FROM recibida WHERE id = recibida;


 SELECT rate INTO dblRefRate FROM reference_rate WHERE date = (SELECT MAX(date) FROM reference_rate 
            WHERE date <= (SELECT  t.shipment FROM
    recibida_entrada re 
    INNER JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada
    LEFT JOIN travel t ON t.id = e.travel_id 
    WHERE re.awb_recibida = recibida GROUP BY re.awb_recibida));
        
    SELECT rate INTO dblRefMin FROM reference_min  WHERE date=(SELECT MAX(date) FROM reference_min 
            WHERE date<=(SELECT  t.shipment FROM
    recibida_entrada re 
    INNER JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada
    LEFT JOIN travel t ON t.id = e.travel_id 
    WHERE re.awb_recibida = NEW_id GROUP BY re.awb_recibida));

    -- IF dblRefMin < dblRefRate THEN
    --    SET dblRef = dblRefRate;
    -- ELSE
    --     SET dblRef =dblRefMin;
    -- END IF;
    SELECT IFNULL(MAX(r.num_recibida) + 1,1) INTO v_num_recibida FROM recibida r
            WHERE r.serie LIKE NEW_serie 
            AND YEAR(r.fecha) = YEAR(NEW_fecha)
            AND r.empresa_id = NEW_empresa_id GROUP BY r.empresa_id;
            
    SET NEW_num_recibida = IFNULL(v_num_recibida,1);	


    SELECT REPLACE(cuenta,' ','') INTO cta_proveed FROM Proveedores WHERE Id_Proveedor=NEW_proveedor_id;


SELECT CONCAT('COMPRA FRA ',p.Proveedor) concepto,ic.codigo subcta,p.Cuenta,ic.iva,
            red(sum(costefijo * Cantidad / sub1.costetotal * sub2.importe)*0.21) eurodebe,NULL eurohaber,
            ROUND(sum(costefijo * Cantidad / sub1.costetotal * sub2.importe),2) baseeuro,ri.bi,r.serie,pa.CEE,p.pais_id ppais_id,p2.pais_id p2pais_id

            FROM awb_recibida ar
						
            left JOIN recibida_entrada re ON ar.recibida_id = re.awb_recibida
			
			left JOIN Compres c ON c.Id_Entrada = re.Id_Entrada

            left JOIN Articles a ON a.Id_Article = c.Id_Article

            left JOIN (

                SELECT a.Codintrastat, sum(c.costefijo * c.Cantidad) as costetotal

                FROM Compres c 

                left JOIN Articles a ON a.Id_Article = c.Id_Article

                left JOIN recibida_entrada re ON re.Id_Entrada = c.Id_Entrada
				
				left JOIN awb_recibida ar ON ar.recibida_id = re.awb_recibida
						
				left JOIN awb aw ON ar.awb_id = aw.id

                WHERE ar.recibida_id = NEW_id AND re.percentage/*JGF 27/08/14*/

                GROUP BY a.Codintrastat

                ) sub1 USING(Codintrastat)

            left JOIN (

                SELECT Codintrastat,ri.importe

                FROM recibida_intrastat ri

                WHERE ri.recibida_id = NEW_id

            ) sub2 USING(Codintrastat)

			-- JOIN recibida_intrastat ri ON ar.awb_recibida = ri.recibida_id and ri.Codintrastat = sub1.Codintrastat

            left JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada

            left JOIN Proveedores p ON p.Id_Proveedor = e.Id_Proveedor
			
			left JOIN Paises pa ON p.pais_id = pa.Id
							            
            left JOIN recibida_iva ri ON ri.recibida_id = re.awb_recibida
            
            left JOIN recibida_iva ri2 ON ri2.recibida_id = re.recibida_id
            
            left JOIN iva_codigo ic ON ic.id = ri2.iva_id 
            
            left JOIN recibida r ON r.id = re.recibida_id
			
			left JOIN Proveedores p2 ON p2.Id_Proveedor =  r.empresa_id

            WHERE re.awb_recibida = NEW_id AND re.percentage/*JGF 27/08/14*/ AND IF(cta_proveed like '___0______',ri.gastos_id = 5660000002,TRUE)
             -- canvie el cta_proveed like '___1______' per cero cuidao en les van de put
            GROUP BY p.Id_Proveedor;




END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `recobro_credito` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `recobro_credito`()
BEGIN
	DROP TEMPORARY TABLE IF EXISTS clientes_credit;
	CREATE TEMPORARY TABLE clientes_credit
		SELECT Id_Cliente, if (Credito > Recobro ,Credito - Recobro,0) AS newCredit
		FROM (
			SELECT r.Id_Cliente, r.amount AS Recobro,
				timestampadd(DAY, period, UltimaFecha) AS Deadline, sub2.amount AS Credito
				FROM vn2008.recovery r
					JOIN (
						SELECT Id_Cliente, amount , odbc_date AS UltimaFecha
						FROM (
							SELECT * FROM credit
								ORDER BY odbc_date DESC
						) sub
						GROUP BY Id_Cliente
					) sub2 USING(Id_Cliente)
				WHERE dend IS NULL or dend >= curdate()
				GROUP BY Id_Cliente
					HAVING Deadline <= curdate()
		) sub3
		WHERE Credito > 0;

	UPDATE Clientes
		JOIN clientes_credit USING(Id_Cliente)
			SET Clientes.Credito = newCredit;

	INSERT INTO credit(Id_Cliente, amount, Id_Trabajador)
		SELECT Id_Cliente, newCredit, 20
			FROM clientes_credit;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `reinvoice` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `reinvoice`(Id_Factura VARCHAR(15))
BEGIN
	DECLARE date_invoice DATE;
	DECLARE customer_id INTEGER;
	DECLARE serie CHAR(1);
	DECLARE bi DOUBLE;
	DECLARE bi_diff DOUBLE;
	DECLARE base_max DOUBLE;
	DECLARE day_vec INT;
	DECLARE bi_r DOUBLE DEFAULT 0;
	DECLARE bi_g DOUBLE DEFAULT 0;
	DECLARE bi_n DOUBLE DEFAULT 0;
	DECLARE iva_r DOUBLE DEFAULT 0;
	DECLARE iva_g DOUBLE DEFAULT 0;
	DECLARE re_r DOUBLE DEFAULT 0;
	DECLARE re_g DOUBLE DEFAULT 0;
	DECLARE dblImporte DOUBLE DEFAULT 0;
	DECLARE intpais_id TINYINT DEFAULT 1;
	DECLARE intFac INTEGER;

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

	DROP TEMPORARY TABLE IF EXISTS `iva_base`;
	CREATE TEMPORARY TABLE `iva_base`
	(
		`id` VARCHAR(3) NOT NULL,
		`base` DOUBLE NOT NULL DEFAULT 0,
		PRIMARY KEY  (`id`)
	)
	ENGINE = MEMORY;

	DROP TEMPORARY TABLE IF EXISTS `ticket_invoice`;
	CREATE TEMPORARY TABLE `ticket_invoice`
	(
		`ticket_id` INT NOT NULL,
		PRIMARY KEY  (`ticket_id`)
	)
	ENGINE = MEMORY;

	START TRANSACTION;

	SELECT pais_id,Fecha,f.Id_Factura,Id_Cliente INTO intpais_id,date_invoice,Id_Factura,customer_id FROM Proveedores p
		JOIN Facturas f ON p.Id_Proveedor = f.empresa_id
		WHERE f.Id_Factura = Id_Factura;

	INSERT INTO ticket_invoice (ticket_id) SELECT Id_Ticket FROM Tickets t
		WHERE Factura = Id_Factura;

	-- Eliminem els tickets que no han de ser facturats

	IF (SELECT COUNT(*) FROM ticket_invoice) > 0
    THEN
		INSERT INTO iva_base (id) SELECT tipoiva FROM tblIVA;

		UPDATE iva_base
			INNER JOIN
			(SELECT tipo, SUM(base) base
				FROM
				(SELECT t.tipo,	red(m.Cantidad * m.Preu * (100 - Descuento) / 100) AS base
					FROM
					Movimientos m
					INNER JOIN ticket_invoice ti ON m.Id_Ticket = ti.ticket_id
					INNER JOIN (SELECT 	t.tipo, Id_Article
								FROM
									(SELECT 
									date, iva_codigo_id, ic.tipo, iva_group_id
								FROM
									iva_group_codigo gi
								INNER JOIN iva_codigo ic ON gi.iva_codigo_id = ic.id
								INNER JOIN iva_tipo itp ON itp.id = ic.iva_tipo_id
								WHERE
									date <= date_invoice
										AND Id_Pais = intpais_id
								ORDER BY date DESC) t
							INNER JOIN Articles USING (iva_group_id)
				   GROUP BY Id_Article) t USING (Id_Article)) sub
			  GROUP BY tipo) iva_movement ON iva_base.id = iva_movement.tipo 
			SET 
			iva_base.base = iva_movement.base;
			
		IF (serie = 'H' OR serie = 'V' OR serie = 'E' OR serie = 'X') THEN
			SELECT SUM(base) into dblImporte from iva_base;
		ELSE

			SET bi_r = (SELECT base FROM iva_base WHERE id = 'R');

			SET bi_g = (SELECT base FROM iva_base WHERE id = 'G');
			SET bi_n = (SELECT base FROM iva_base WHERE id = '0');
			SET iva_r = red(bi_r * (SELECT iva FROM iva_codigo INNER JOIN iva_tipo it ON it.id = iva_tipo_id 
					WHERE tipo = 'R' AND Id_Pais = intpais_id AND Fecha <= date_invoice and iva ORDER BY fecha DESC, recargo DESC LIMIT 1) / 100 );
			SET iva_g = red(bi_g * (SELECT iva FROM iva_codigo INNER JOIN iva_tipo it ON it.id = iva_tipo_id 
					WHERE tipo = 'G' AND Id_Pais = intpais_id AND Fecha <= date_invoice and iva ORDER BY fecha DESC, recargo DESC LIMIT 1) / 100 );
	
			IF (SELECT IF(RE = 0, FALSE, TRUE) FROM Clientes WHERE Clientes.Id_cliente = customer_id)
            THEN
				SET re_r = red(bi_r * (SELECT recargo FROM iva_codigo INNER JOIN iva_tipo it ON it.id = iva_tipo_id 
					WHERE tipo = 'R' AND Id_Pais = intpais_id AND Fecha <= date_invoice and iva ORDER BY fecha DESC, recargo DESC LIMIT 1) / 100 );
				SET re_g = red(bi_g * (SELECT recargo FROM iva_codigo INNER JOIN iva_tipo it ON it.id = iva_tipo_id
					WHERE tipo = 'G' AND Id_Pais = intpais_id AND Fecha <= date_invoice and iva ORDER BY fecha DESC, recargo DESC LIMIT 1) / 100 );
			END IF;

			SET dblImporte = bi_r + bi_g + bi_n + iva_r + iva_g + re_r + re_g ;
		END IF;
	END IF;

	IF (SELECT SUM(base) FROM iva_base) != 0
    THEN
		UPDATE Facturas
		SET
			BI7 = bi_r,
			BI16 = bi_g,
			IVA7 = iva_r,
			IVA16 = iva_g,
			RE1 = re_r,
			RE4 = re_g,
			Importe = dblImporte
		 WHERE Facturas.Id_Factura = Id_Factura;
	END IF;

	DROP TEMPORARY TABLE `iva_base`;
	DROP TEMPORARY TABLE `ticket_invoice`;

	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 `risk_vs_client_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 `risk_vs_client_list`(maxRiskDate DATE)
BEGIN
/**
 * Calcula el riesgo para los clientes activos de la tabla temporal tmp.client_list
 *
 * @deprecated usar vn.clientGetDebt
 * @param maxRiskDate Fecha maxima de los registros
 * @return table tmp.risk
 */
	DECLARE startingDate DATETIME DEFAULT TIMESTAMPADD(DAY, - DAYOFMONTH(CURDATE()) - 60, CURDATE());
	DECLARE endingDate DATETIME;
	DECLARE MAX_RISK_ALLOWED INT DEFAULT 200;

	SET maxRiskDate = IFNULL(maxRiskDate, CURDATE());
	SET endingDate = TIMESTAMP(maxRiskDate, '23:59:59');

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

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

	DROP TEMPORARY TABLE IF EXISTS tmp.tickets_sin_facturar;
	CREATE TEMPORARY TABLE tmp.tickets_sin_facturar
		(PRIMARY KEY (Id_Cliente))
		ENGINE = MEMORY
			SELECT t.Id_Cliente, floor(IF(cl.isVies, 1, 1.1) * sum(Cantidad * Preu * (100 - Descuento) / 100)) as total
			FROM Movimientos m
				JOIN Tickets t on m.Id_Ticket = t.Id_Ticket
				JOIN tmp.client_list c on c.Id_Cliente = t.Id_Cliente
				JOIN vn.client cl ON cl.id = t.Id_Cliente
			WHERE Factura IS NULL
				AND Fecha BETWEEN startingDate AND endingDate
			GROUP BY t.Id_Cliente;      

	DROP TEMPORARY TABLE IF EXISTS tmp.risk;
	CREATE TEMPORARY TABLE tmp.risk
		(PRIMARY KEY (Id_Cliente))
		ENGINE = MEMORY
		SELECT Id_Cliente, SUM(amount) risk, sum(saldo) saldo
			FROM Clientes c
			JOIN (
				SELECT customer_id, SUM(amount) amount,SUM(amount) saldo 
					FROM bi.customer_risk
						JOIN tmp.client_list on Id_Cliente = customer_id
					GROUP BY customer_id
				UNION ALL
				SELECT Id_Cliente, SUM(Entregado),SUM(Entregado)
					FROM Recibos
						JOIN tmp.client_list_2 using(Id_Cliente)
					WHERE  Fechacobro > endingDate
					GROUP BY Id_Cliente
				UNION ALL
				SELECT Id_Cliente, total,0
					FROM tmp.tickets_sin_facturar
				UNION ALL
				SELECT t.clientFk, CAST(-SUM(t.amount) / 100 AS DECIMAL(10,2)), CAST(-SUM(t.amount) / 100 AS DECIMAL(10,2))
					FROM hedera.tpvTransaction t
						JOIN tmp.client_list_3 on 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;
			
	DELETE r.*
		FROM tmp.risk r
			JOIN vn2008.Clientes c on c.Id_Cliente = r.Id_Cliente
			JOIN vn2008.pay_met pm on pm.id = c.pay_met_id
		WHERE IFNULL(r.saldo,0) < 10
			AND r.risk <= MAX_RISK_ALLOWED
			AND pm.`name` = 'TARJETA';
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_Graph` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_Graph`()
BEGIN

DECLARE datSTART DATE DEFAULT TIMESTAMPADD(DAY,-3,CURDATE());
DECLARE datEND DATE;

SET datEND = vn2008.dayend(timestampadd(day,3,CURDATE()));

CALL item_last_buy_(NULL,datSTART);

Select  cast(sum(Cantidad * vn2008.cm3_unidad(buy_id)) / 1000000 as DECIMAL(5,1)) as m3, Agencia, w.name as Almacen, date(R.Fecha) as Fecha_Ruta
              from vn2008.Rutas R              
			  JOIN vn2008.Agencias a on a.Id_Agencia = R.Id_Agencia
              join vn2008.Tickets t using(Id_Ruta) 
              JOIN vn2008.warehouse w on w.id = t.warehouse_id
              join vn2008.Movimientos m using(Id_Ticket) 
              JOIN cache.last_buy b ON m.Id_Article = b.item_id AND t.warehouse_id = b.warehouse_id
              where R.Fecha between datSTART and datEND
              group by Agencia, Almacen, Fecha_Ruta

UNION ALL
Select cast(sum(Cantidad * vn2008.cm3_unidad(buy_id)) / 1000000 as decimal(5,1)) as m3 ,Agencia,   w.name as Almacen, timestampadd(day,1,t.Fecha) Fecha
              from vn2008.Tickets t 
              join warehouse w on w.id = warehouse_id
              join Agencias a using(Id_Agencia)
              join vn2008.Movimientos m using(Id_Ticket) 
              JOIN cache.last_buy b ON m.Id_Article = b.item_id AND t.warehouse_id = b.warehouse_id
              LEFT JOIN warehouse_pickup wp ON wp.agency_id = t.Id_Agencia and wp.warehouse_id = t.warehouse_id
              JOIN warehouse_pickup is_rec ON is_rec.agency_id = t.Id_Agencia
              where t.Fecha between TIMESTAMPADD(DAY,-1,datSTART) and TIMESTAMPADD(DAY,-1,datEND)
              AND wp.agency_id IS NULL
              group by Agencia, Almacen, Fecha
              -- JGF 2016-05-05 
UNION ALL
	Select cast(sum(Cantidad * vn2008.cm3_unidad(Id_Compra)) / 1000000 as decimal(5,1)) as m3 ,a.Agencia, w.name as Almacen, 
	timestampadd(day,1,t.shipment) Fecha
              from Compres c JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada
              JOIN travel t ON t.id = e.travel_id
              JOIN Agencias a on a.Id_Agencia = t.agency_id
              JOIN warehouse w on w.id = t.warehouse_id_out
              JOIN warehouse_pickup wp ON wp.warehouse_id = t.warehouse_id_out
              where t.shipment between TIMESTAMPADD(DAY,-1,datSTART) and TIMESTAMPADD(DAY,-1,datEND)
              group by a.Agencia, Almacen, Fecha;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_monitor_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 `Rutas_monitor_update`(vDate DATE)
BEGIN

DECLARE vDateEND DATETIME;

SET vDateEND = util.dayend(vDate);
SET vDate = TIMESTAMPADD(DAY,-1,vDate);

INSERT IGNORE INTO Rutas_monitor(Id_Ruta)
	SELECT DISTINCT Id_Ruta
		FROM Tickets
		WHERE Fecha BETWEEN vDate AND vDateEND
        AND Id_Ruta;

UPDATE Rutas_monitor rm
JOIN Rutas r ON r.Id_Ruta = rm.Id_Ruta
JOIN Agencias a ON a.Id_Agencia = r.Id_Agencia
SET rm.`name` = a.Agencia, rm.fecha = r.Fecha,
	rm.pedidosLibres = 0,
    rm.pedidosProduccion = 0,
    rm.pedidosEncajados = 0,
    rm.Fecha = r.Fecha;
    
UPDATE vn2008.Rutas_monitor rm
	JOIN vn.routeGate rg ON rg.routeFk = rm.Id_Ruta
    SET rm.Ubicacion = rg.deviceId;
    
UPDATE Rutas_monitor rm
JOIN
(	SELECT Id_Ruta, count(*) AS pedidosLibres
		FROM Tickets t
			JOIN Tickets_state ts ON t.Id_Ticket = ts.Id_Ticket
            JOIN vncontrol.inter i ON i.inter_id = ts.inter_id
            JOIN state s ON i.state_id = s.id AND s.alert_level = 0
				WHERE t.Fecha BETWEEN vDate AND vDateEND
				AND Id_Ruta
				GROUP BY Id_Ruta
) t ON t.Id_Ruta = rm.Id_Ruta
SET rm.pedidosLibres = t.pedidosLibres;

UPDATE Rutas_monitor rm
JOIN
(	SELECT Id_Ruta, count(*) AS pedidosProduccion
		FROM Tickets t
			JOIN Tickets_state ts ON t.Id_Ticket = ts.Id_Ticket
            JOIN vncontrol.inter i ON i.inter_id = ts.inter_id
            JOIN state s ON i.state_id = s.id AND s.alert_level = 1
				WHERE t.Fecha BETWEEN vDate AND vDateEND
				AND Id_Ruta
				GROUP BY Id_Ruta
) t ON t.Id_Ruta = rm.Id_Ruta
SET rm.pedidosProduccion = t.pedidosProduccion;

UPDATE Rutas_monitor rm
JOIN
(	SELECT Id_Ruta, count(*) AS pedidosEncajados
		FROM Tickets t
			JOIN Tickets_state ts ON t.Id_Ticket = ts.Id_Ticket
            JOIN vncontrol.inter i ON i.inter_id = ts.inter_id
            JOIN state s ON i.state_id = s.id AND s.alert_level >= 2
				WHERE t.Fecha BETWEEN vDate AND vDateEND
				AND Id_Ruta
				GROUP BY Id_Ruta
) t ON t.Id_Ruta = rm.Id_Ruta
SET rm.pedidosEncajados = t.pedidosEncajados;

UPDATE Rutas_monitor rm
JOIN
(	SELECT Id_Ruta, count(*) AS bultos
		FROM Tickets t
			JOIN expeditions e ON e.ticket_id = t.Id_Ticket
			WHERE t.Fecha BETWEEN vDate AND vDateEND
            AND Id_Ruta
            GROUP BY Id_Ruta
) t ON t.Id_Ruta = rm.Id_Ruta
SET rm.bultos = t.bultos;

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

	SELECT  t.clientFk, 
			t.shipped, 
            a.nickname, 
			s.ticketFk,
			s.itemFk, 
			s.quantity, 
			s.concept, 
			s.reserved,
			s.id saleFk,
            i.size,
			i.inkFk,
			i.stems,
			i.image,
			i.subName,
			b.`grouping`,
			ip.code as placement, 
			lpad(ifnull(cooler_path_detail_id, ip.code),5,'0') as path, 
			stPrevious.isChecked as isPrevious,
            stPrepared.isChecked as isPrepared,
            stControled.isChecked as isControled
     
	FROM vn.ticket t
		JOIN vn.address a ON a.id = t.addressFk
		JOIN vn.sale s ON s.ticketFk = t.id
        JOIN vn.item i ON i.id = s.itemFk
        LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND i.warehouseFk = t.warehouseFk
        LEFT JOIN vn2008.cooler_path_detail cpd on left(ip.code,3) = cpd.pasillo 
        LEFT JOIN bi.Last_buy_id lb ON lb.Id_Article = i.id AND lb.warehouse_id = t.warehouseFk
        LEFT JOIN vn.buy b ON b.id = lb.Id_Compra
		LEFT JOIN vn.saleTracking stPrepared ON stPrepared.saleFk = s.id AND stPrepared.stateFk = 8
        LEFT JOIN vn.saleTracking stControled ON stControled.saleFk = s.id AND stControled.stateFk = 14
        LEFT JOIN vn.saleTracking stPrevious ON stPrevious.saleFk = s.id AND stPrevious.stateFk = 26
        
    WHERE t.id = idT 
    GROUP BY s.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 `scan_rutas_view` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `scan_rutas_view`()
BEGIN


/* muestra las rutas agrupadas de los ultimos tres dias, así como una lista de los tickets sin enrutar, agrpados por agencia y fecha*/

select Fecha, Id_Ruta, Matricula, sub.m3, CodigoTrabajador, Agencia, Bultos, w.name as Almacen
from
(
select r.Fecha, Id_Ruta, r.Id_Trabajador, r.Id_Agencia, Id_Vehiculo, sum(m3) m3, sum(Bultos) Bultos, warehouse_id
from Rutas r
join Tickets t using(Id_Ruta)
where r.Fecha >= timestampadd(day,-3,curdate())
group by Id_Ruta, warehouse_id

union all

select ifnull(landing,Fecha), dayofmonth(Fecha) * 100000 + Id_Agencia ruta , count(*) as m3, Id_Agencia, null, null, sum(Bultos), warehouse_id
from Tickets 
where Id_Ruta is null
and Fecha between timestampadd(day,-3,curdate()) and dayend(curdate())
group by ruta, warehouse_id
) sub
left join Vehiculos using(Id_Vehiculo)
left join Agencias using(Id_Agencia)
left join Trabajadores using(Id_Trabajador)
left join warehouse w on w.id = sub.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 `sendTicket` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `sendTicket`(vDate DATE)
BEGIN
	IF vDate IS NULL THEN
		SET vDate = AYER();
    END IF;
    
    INSERT INTO mail (`to`, `reply_to`, subject,text)
		SELECT IFNULL(c.`e-mail`,CONCAT(u.name,'@verdnatura.es')),
			CONCAT(u.name,'@verdnatura.es'),
			CONCAT('Albaran ',Id_Ticket),
CONCAT('Estimado cliente:

Aquí tiene el enlace a su albarán.

https://www.verdnatura.es/#!form=ecomerce/ticket&ticket=',Id_Ticket,
'

Estamos en periodo de pruebas para este nuevo método. En el caso de que tenga problemas para acceder a su albarán, responda a este correo explicando los detalles.

Estamos trabajando para mejorar el acceso a sus documentos.Le agradecemos su colaboración.

Reciba un muy cordial saludo,

',tr.nombre, ' ', tr.apellidos,'
',u.name,'@verdnatura.es

Dpto. Comercial')
		FROM Tickets  t
			JOIN Clientes c USING(Id_Cliente)
			JOIN Trabajadores tr ON tr.Id_Trabajador = c.Id_Trabajador
			JOIN account.user u ON tr.user_id = u.id
        WHERE vDate = DATE(t.Fecha);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `splitAnthuriums2016` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `splitAnthuriums2016`()
BEGIN

DECLARE vStartingDate DATETIME DEFAULT '2016-10-18';
DECLARE vEndingDate DATETIME DEFAULT '2016-10-31 23:59:00';
DECLARE vMyTicket INT;
DECLARE vNewTicket INT;
DECLARE SILLA_PCA INT DEFAULT 44;
DECLARE done INT DEFAULT 0;

DECLARE rs CURSOR FOR
SELECT DISTINCT Id_Ticket
FROM Movimientos m
JOIN Tickets t using(Id_Ticket)
JOIN Articles a using(Id_Article)
JOIN Tipos tp using(tipo_id)
WHERE t.Fecha between vStartingDate and vEndingDate
AND warehouse_id = 1
AND 
	(
    Id_Tipo = 'ANT'
	OR 
    (	Id_Article = 100 
		AND 
		Concepte LIKE 'ANT%')
    );

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

OPEN rs;

FETCH rs INTO vMyTicket;



WHILE NOT done DO


	INSERT INTO Tickets(Id_Cliente
						, warehouse_id
                        , Fecha
                        , Alias
                        , Id_Consigna
                        , Id_Trabajador
                        , Id_Ruta
						, empresa_id
						, Id_Agencia
						, landing)
		SELECT Id_Cliente
			 , SILLA_PCA as warehouse_id
             , Fecha
             , Alias
             , Id_Consigna
             , Id_Trabajador
             , Id_Ruta
             , empresa_id
             , Id_Agencia
             , landing
		FROM Tickets
        WHERE Id_Ticket = vMyTicket;
        
	SELECT LAST_INSERT_ID() INTO vNewTicket;

																-- SELECT vMyTicket, vNewTicket; SET done = 1;    
    UPDATE Movimientos m
		JOIN Articles a using(Id_Article)
		JOIN Tipos tp using(tipo_id)
		SET Id_Ticket = vNewTicket
		WHERE Id_Ticket = vMyTicket
		AND (
			Id_Tipo = 'ANT'
			OR 
			(	m.Id_Article = 100 
				AND 
				Concepte LIKE 'ANT%')
			);

	FETCH rs INTO vMyTicket;

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

DECLARE vStartingDate DATETIME DEFAULT '2018-10-16';
DECLARE vEndingDate DATETIME DEFAULT '2018-10-31 23:59:00';
DECLARE vMyTicket INT;
DECLARE vNewTicket INT;
DECLARE SILLA_PCA INT DEFAULT 44;
DECLARE done INT DEFAULT 0;

DECLARE rs CURSOR FOR
SELECT DISTINCT Id_Ticket
FROM Movimientos m
JOIN Tickets t using(Id_Ticket)
JOIN Articles a using(Id_Article)
JOIN Tipos tp using(tipo_id)
WHERE t.Fecha between vStartingDate and vEndingDate
AND warehouse_id = 1
AND 
	(
    Id_Tipo = 'ANT'
	OR 
    (	Id_Article = 100 
		AND 
		Concepte LIKE 'ANT%')
    );

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

OPEN rs;

FETCH rs INTO vMyTicket;



WHILE NOT done DO


	INSERT INTO Tickets(Id_Cliente
						, warehouse_id
                        , Fecha
                        , Alias
                        , Id_Consigna
                        , Id_Trabajador
                        , Id_Ruta
						, empresa_id
						, Id_Agencia
						, landing)
		SELECT Id_Cliente
			 , SILLA_PCA as warehouse_id
             , Fecha
             , Alias
             , Id_Consigna
             , Id_Trabajador
             , Id_Ruta
             , empresa_id
             , Id_Agencia
             , landing
		FROM Tickets
        WHERE Id_Ticket = vMyTicket;
        
	SELECT LAST_INSERT_ID() INTO vNewTicket;

																-- SELECT vMyTicket, vNewTicket; SET done = 1;    
    UPDATE Movimientos m
		JOIN Articles a using(Id_Article)
		JOIN Tipos tp using(tipo_id)
		SET Id_Ticket = vNewTicket
		WHERE Id_Ticket = vMyTicket
		AND (
			Id_Tipo = 'ANT'
			OR 
			(	m.Id_Article = 100 
				AND 
				Concepte LIKE 'ANT%')
			);

	FETCH rs INTO vMyTicket;

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

DECLARE vStartingDate DATETIME DEFAULT '2016-10-18';
DECLARE vEndingDate DATETIME DEFAULT '2016-10-31 23:59:00';
DECLARE vMyTicket INT;
DECLARE vNewTicket INT;
DECLARE SILLA_PCA INT DEFAULT 44;
DECLARE done INT DEFAULT 0;

DECLARE rs CURSOR FOR
SELECT DISTINCT Id_Ticket
FROM Movimientos m
JOIN Compres c ON Id_Entrada IN (100461, 100929) AND c.Id_Article = m.Id_Article
JOIN Tickets t using(Id_Ticket)
WHERE t.Fecha between vStartingDate and vEndingDate
AND warehouse_id = 1;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

OPEN rs;

FETCH rs INTO vMyTicket;



WHILE NOT done DO


	INSERT INTO Tickets(Id_Cliente
						, warehouse_id
                        , Fecha
                        , Alias
                        , Id_Consigna
                        , Id_Trabajador
                        , Id_Ruta
						, empresa_id
						, Id_Agencia
						, landing)
		SELECT Id_Cliente
			 , SILLA_PCA as warehouse_id
             , Fecha
             , Alias
             , Id_Consigna
             , Id_Trabajador
             , Id_Ruta
             , empresa_id
             , Id_Agencia
             , landing
		FROM Tickets
        WHERE Id_Ticket = vMyTicket;
        
	SELECT LAST_INSERT_ID() INTO vNewTicket;

																-- SELECT vMyTicket, vNewTicket; SET done = 1;    
    UPDATE Movimientos m
		JOIN Compres c ON Id_Entrada IN (100461, 100929) AND c.Id_Article = m.Id_Article
		SET Id_Ticket = vNewTicket
		WHERE Id_Ticket = vMyTicket
		;

	FETCH rs INTO vMyTicket;

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

DECLARE vStartingDate DATETIME DEFAULT '2018-10-16';
DECLARE vEndingDate DATETIME DEFAULT '2018-10-31 23:59:00';
DECLARE vMyTicket INT;
DECLARE vNewTicket INT;
DECLARE SILLA_PCA INT DEFAULT 44;
DECLARE done INT DEFAULT 0;

DECLARE rs CURSOR FOR
SELECT DISTINCT Id_Ticket
FROM Movimientos m
JOIN Compres c ON Id_Entrada IN (152622) AND c.Id_Article = m.Id_Article
JOIN Tickets t using(Id_Ticket)
LEFT JOIN vn.ticketStateToday tst ON t.Id_Ticket = tst.ticket
WHERE (IFNULL(tst.productionOrder,9) < 5 OR t.Fecha between vStartingDate and vEndingDate)
AND warehouse_id = 1;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

OPEN rs;

FETCH rs INTO vMyTicket;



WHILE NOT done DO


	INSERT INTO Tickets(Id_Cliente
						, warehouse_id
                        , Fecha
                        , Alias
                        , Id_Consigna
                        , Id_Trabajador
                        , Id_Ruta
						, empresa_id
						, Id_Agencia
						, landing)
		SELECT Id_Cliente
			 , SILLA_PCA as warehouse_id
             , Fecha
             , Alias
             , Id_Consigna
             , Id_Trabajador
             , Id_Ruta
             , empresa_id
             , Id_Agencia
             , landing
		FROM Tickets
        WHERE Id_Ticket = vMyTicket;
        
	SELECT LAST_INSERT_ID() INTO vNewTicket;

																-- SELECT vMyTicket, vNewTicket; SET done = 1;    
    UPDATE Movimientos m
		JOIN Compres c ON Id_Entrada IN (152622) AND c.Id_Article = m.Id_Article
		SET Id_Ticket = vNewTicket
		WHERE Id_Ticket = vMyTicket
		;

	FETCH rs INTO vMyTicket;

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

DECLARE vStartingDate DATETIME DEFAULT '2016-10-18';
DECLARE vEndingDate DATETIME DEFAULT '2016-10-31 23:59:00';
DECLARE vMyTicket INT;
DECLARE vNewTicket INT;
DECLARE SILLA_PCA INT DEFAULT 44;
DECLARE done INT DEFAULT 0;

DECLARE rs CURSOR FOR
SELECT DISTINCT Id_Ticket
FROM Movimientos m
JOIN Tickets t using(Id_Ticket)
JOIN Articles a using(Id_Article)
JOIN Tipos tp using(tipo_id)
WHERE t.Fecha between vStartingDate and vEndingDate
AND warehouse_id = 1
AND 
	(
    Id_Tipo = 'CYM'
    OR
    Id_Tipo = 'ORQ'
	OR 
    (	Id_Article = 100 
		AND 
		Concepte LIKE 'CYM%')
    );

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

OPEN rs;

FETCH rs INTO vMyTicket;



WHILE NOT done DO


	INSERT INTO Tickets(Id_Cliente
						, warehouse_id
                        , Fecha
                        , Alias
                        , Id_Consigna
                        , Id_Trabajador
                        , Id_Ruta
						, empresa_id
						, Id_Agencia
						, landing)
		SELECT Id_Cliente
			 , SILLA_PCA as warehouse_id
             , Fecha
             , Alias
             , Id_Consigna
             , Id_Trabajador
             , Id_Ruta
             , empresa_id
             , Id_Agencia
             , landing
		FROM Tickets
        WHERE Id_Ticket = vMyTicket;
        
	SELECT LAST_INSERT_ID() INTO vNewTicket;

																-- SELECT vMyTicket, vNewTicket; SET done = 1;    
    UPDATE Movimientos m
		JOIN Articles a using(Id_Article)
		JOIN Tipos tp using(tipo_id)
		SET Id_Ticket = vNewTicket
		WHERE Id_Ticket = vMyTicket
		AND (
			Id_Tipo = 'CYM'
			OR
			Id_Tipo = 'ORQ'
			OR 
			(	Id_Article = 100 
				AND 
				Concepte LIKE 'CYM%')
			);

	FETCH rs INTO vMyTicket;

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

DECLARE vStartingDate DATETIME DEFAULT '2018-10-16';
DECLARE vEndingDate DATETIME DEFAULT '2018-10-31 23:59:00';
DECLARE vMyTicket INT;
DECLARE vNewTicket INT;
DECLARE SILLA_PCA INT DEFAULT 44;
DECLARE done INT DEFAULT 0;

DECLARE rs CURSOR FOR
SELECT DISTINCT Id_Ticket
FROM Movimientos m
JOIN Tickets t using(Id_Ticket)
JOIN Articles a using(Id_Article)
JOIN Tipos tp using(tipo_id)
WHERE t.Fecha between vStartingDate and vEndingDate
AND warehouse_id = 1
AND 
	(
    Id_Tipo = 'CYM'
    OR
    Id_Tipo = 'ORQ'
	OR 
    (	Id_Article = 100 
		AND 
		Concepte LIKE 'CYM%')
    );

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

OPEN rs;

FETCH rs INTO vMyTicket;



WHILE NOT done DO


	INSERT INTO Tickets(Id_Cliente
						, warehouse_id
                        , Fecha
                        , Alias
                        , Id_Consigna
                        , Id_Trabajador
                        , Id_Ruta
						, empresa_id
						, Id_Agencia
						, landing)
		SELECT Id_Cliente
			 , SILLA_PCA as warehouse_id
             , Fecha
             , Alias
             , Id_Consigna
             , Id_Trabajador
             , Id_Ruta
             , empresa_id
             , Id_Agencia
             , landing
		FROM Tickets
        WHERE Id_Ticket = vMyTicket;
        
	SELECT LAST_INSERT_ID() INTO vNewTicket;

																-- SELECT vMyTicket, vNewTicket; SET done = 1;    
    UPDATE Movimientos m
		JOIN Articles a using(Id_Article)
		JOIN Tipos tp using(tipo_id)
		SET Id_Ticket = vNewTicket
		WHERE Id_Ticket = vMyTicket
		AND (
			Id_Tipo = 'CYM'
			OR
			Id_Tipo = 'ORQ'
			OR 
			(	Id_Article = 100 
				AND 
				Concepte LIKE 'CYM%')
			);

	FETCH rs INTO vMyTicket;

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

DECLARE vStartingDate DATETIME DEFAULT '2016-10-21';
DECLARE vEndingDate DATETIME DEFAULT '2016-10-31 23:59:00';
DECLARE vMyTicket INT;
DECLARE vNewTicket INT;
DECLARE SILLA_PCA INT DEFAULT 44;
DECLARE done INT DEFAULT 0;
DECLARE vLinesNotToChange INT;

DECLARE rs CURSOR FOR
SELECT DISTINCT Id_Ticket
	FROM Movimientos m
	JOIN 
	(
		SELECT DISTINCT Id_Article
			FROM Compres c
			JOIN Entradas e on c.Id_Entrada = e.Id_Entrada
			JOIN travel tr on tr.id = travel_id
			WHERE landing between vStartingDate and vEndingDate
			AND warehouse_id = 44
			AND Id_Proveedor = 850
	) c on c.Id_Article = m.Id_Article
	JOIN Tickets t using(Id_Ticket)
	WHERE t.Fecha between vStartingDate and vEndingDate
	AND warehouse_id = 1
	;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

OPEN rs;

FETCH rs INTO vMyTicket;



WHILE NOT done DO

	SELECT COUNT(*)
		INTO vLinesNotToChange
        FROM Movimientos m
		LEFT JOIN 
		(
			SELECT DISTINCT Id_Article
				FROM Compres c
				JOIN Entradas e on c.Id_Entrada = e.Id_Entrada
				JOIN travel tr on tr.id = travel_id
				WHERE landing between vStartingDate and vEndingDate
				AND warehouse_id = 44
				AND Id_Proveedor = 850
		) c on c.Id_Article = m.Id_Article
		WHERE Id_Ticket = vMyTicket
        AND c.Id_Article IS NULL;

	IF vLinesNotToChange THEN

		INSERT INTO Tickets(Id_Cliente
							, warehouse_id
							, Fecha
							, Alias
							, Id_Consigna
							, Id_Trabajador
							, Id_Ruta
							, empresa_id
							, Id_Agencia
							, landing)
			SELECT Id_Cliente
				 , SILLA_PCA as warehouse_id
				 , Fecha
				 , Alias
				 , Id_Consigna
				 , Id_Trabajador
				 , Id_Ruta
				 , empresa_id
				 , Id_Agencia
				 , landing
			FROM Tickets
			WHERE Id_Ticket = vMyTicket;
			
		SELECT LAST_INSERT_ID() INTO vNewTicket;

																-- SELECT vMyTicket, vNewTicket; SET done = 1;    
		UPDATE Movimientos m
		JOIN 
		(
			SELECT DISTINCT Id_Article
				FROM Compres c
				JOIN Entradas e on c.Id_Entrada = e.Id_Entrada
				JOIN travel tr on tr.id = travel_id
				WHERE landing between vStartingDate and vEndingDate
				AND warehouse_id = 44
				AND Id_Proveedor = 850
		) c on c.Id_Article = m.Id_Article
			SET Id_Ticket = vNewTicket
			WHERE Id_Ticket = vMyTicket;

	ELSE
    
		UPDATE Tickets 
        SET warehouse_id = 44
        WHERE Id_Ticket = vMyTicket;
    
    END IF;


	FETCH rs INTO vMyTicket;

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 `sql_query` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `sql_query`(IN v_sql TEXT)
BEGIN
/**
 * @deprecated Use procedure util.exec()
 */
	SET @v_sql = v_sql;

	PREPARE stmt FROM @v_sql;
	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 `subordinate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `subordinate`(IN `vWorker` INT, IN `vBaseCase` BOOLEAN)
    NO SQL
BEGIN
	DECLARE vAuxWorker INT;
		
	IF vBaseCase THEN
		SET @@max_sp_recursion_depth = 5 ;
		DROP TEMPORARY TABLE IF EXISTS subordinate;
		CREATE TEMPORARY TABLE subordinate
			(INDEX (Id_Trabajador))
			ENGINE = MEMORY
			SELECT vWorker Id_Trabajador, TRUE visited, 0 boss;
	END IF;
		
	INSERT INTO subordinate
		SELECT Id_Trabajador, FALSE, vWorker
			FROM Trabajadores WHERE boss = vWorker;

	IF (SELECT COUNT(*) FROM subordinate WHERE NOT visited AND vWorker = boss LIMIT 1) > 0 THEN
		SELECT Id_Trabajador INTO vAuxWorker
			FROM subordinate
			WHERE NOT visited AND vWorker = boss LIMIT 1;

		REPEAT 			
			CALL subordinate(vAuxWorker, FALSE);
			UPDATE subordinate SET visited = TRUE WHERE Id_Trabajador = vAuxWorker;
			SET vAuxWorker = 0;

			SELECT Id_Trabajador INTO vAuxWorker
				FROM subordinate
				WHERE NOT visited
					AND vWorker = boss
				LIMIT 1;

			UNTIL vAuxWorker = 0
		END REPEAT;
	END IF;

	IF vWorker = 2 THEN
		INSERT INTO subordinate
			SET Id_Trabajador = vWorker, visited = TRUE, boss = vWorker;
	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 `suppliersDebt` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `suppliersDebt`()
BEGIN

			SELECT abbreviation as Empresa, Proveedor, Euros, empresa_id, proveedor_id
            FROM
				(
				SELECT empresa_id, proveedor_id, cast(sum(Euros) AS DECIMAL(10,2)) as Euros 
					FROM
					(
					SELECT empresa_id, proveedor_id, -1 * cantidad as Euros
					FROM recibida_vencimiento rv
					INNER JOIN recibida r ON r.id = rv.recibida_id 
                    WHERE r.fecha > '2014-12-31'
					
					UNION ALL 
					
					SELECT empresa_id, id_proveedor, importe
					FROM pago
                    WHERE fecha > '2014-12-31'
					) sub
					GROUP BY empresa_id, proveedor_id
				) sub2
			JOIN Proveedores p ON p.Id_Proveedor = sub2.proveedor_id
            JOIN empresa e ON e.id = sub2.empresa_id
            ;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `supplierStatement` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `supplierStatement`(vSupplierFk INT, vCurrencyFk INT, vCompanyFk INT, vOrderBy VARCHAR(15))
BEGIN
	SET @saldo_eur:= 0;
	SET @saldo_div:= 0;

	DROP TEMPORARY TABLE IF EXISTS tmp.supplierStatement;
    
    CREATE TEMPORARY TABLE tmp.supplierStatement ENGINE = MEMORY
	SELECT 
		*,
		@saldo_eur:= round(@saldo_eur + IFNULL(Pago_Euros, 0) - IFNULL(Fac_Euros, 0) ,2 ) AS saldo_eur,
		@saldo_div:= round(@saldo_div + IFNULL(Pago_Divisas, 0) - IFNULL(Fac_Divisas, 0) ,2 ) AS saldo_div
	FROM
		(SELECT * FROM
			(SELECT 
				NULL as banco_id,
				r.empresa_id,
				r.serie,
				r.id,
				CASE
					WHEN vOrderBy = 'issued' THEN r.fecha
                    WHEN vOrderBy = 'bookEntried' THEN r.bookEntried
                    WHEN vOrderBy = 'booked' THEN r.dateBooking
                    WHEN vOrderBy = 'dueDate' THEN rv.fecha
				END AS fecha,
				CONCAT('S/Fra ', r.sref) sref,
				if(r.moneda_id > 1,round(sum(divisa) / sum(cantidad),3),NULL) val_cambio,
				CAST(sum(cantidad) as DECIMAL(10,2)) as Fac_Euros,
				CAST(sum(divisa) as DECIMAL(10,2)) as Fac_Divisas,
				NULL AS Pago_Euros,
				NULL AS Pago_Divisas,
				r.moneda_id,
				r.contabilizada,
				Moneda,
				NULL as pago_sdc_id
		FROM
			recibida r
		JOIN recibida_vencimiento rv on rv.recibida_id = r.id
		JOIN Monedas m on m.Id_Moneda = r.moneda_id
		WHERE
			r.fecha > '2014-12-31'
				AND r.proveedor_id = vSupplierFk 
				AND vCurrencyFk IN (r.moneda_id, 0)
				AND vCompanyFk IN (r.empresa_id,0)
		GROUP BY rv.id
				
				UNION ALL SELECT 
				p.id_banco,
				p.empresa_id,
				NULL,
				p.id,
				Fecha,
				CONCAT(IFNULL(name, ''), IF(pre.concepto <> '', CONCAT(' : ', pre.concepto), '')),
				if(p.id_moneda > 1, p.divisa / importe, NULL) tip_cambio,
				NULL,
				NULL,
				p.importe,
				p.divisa,
				p.id_moneda,
				IFNULL(conciliado, 0),
				Moneda,
				pago_sdc_id
		FROM
			pago p
		LEFT JOIN Monedas ON Monedas.Id_Moneda = p.id_moneda
		LEFT JOIN Bancos ON p.id_banco = Bancos.Id_banco
		LEFT JOIN pay_met pm ON p.pay_met_id = pm.id
		LEFT JOIN Pagares pre ON pre.pago_id = p.id
		WHERE
			Fecha > '2014-12-31'
				AND p.Id_Proveedor = vSupplierFk
				AND vCurrencyFk IN (p.id_moneda,0)
				AND vCompanyFk IN (p.empresa_id,0)
	) AS SUB
		ORDER BY (fecha is null and NOT contabilizada),fecha, IF(vOrderBy = 'dueDate', id, NULL)) t;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `tarjetas_credito_0` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `tarjetas_credito_0`()
BEGIN

	DECLARE MyMaxID INT;
    
    SELECT MAX(id) FROM credit INTO MyMaxID;

	UPDATE Clientes
	SET Credito = 0
	WHERE pay_met_id = 5  -- TARJETA
	;

	UPDATE credit 
    SET Id_Trabajador = 20
    WHERE id > MyMaxID;

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

    DECLARE vWarehouse INT;
    DECLARE vDate DATE;
    DECLARE vAvailableCache INT;
    DECLARE vVisibleCache INT;
    DECLARE vDone INT DEFAULT 0;

    DECLARE vCursor CURSOR FOR
        SELECT DISTINCT tt.warehouseFk, date(tt.shipped)
            FROM tmp.ticketGetProblems tt
            WHERE DATE(tt.shipped) BETWEEN CURDATE()
                AND TIMESTAMPADD(DAY, 1.9, CURDATE());
  
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1;

    DROP TEMPORARY TABLE IF EXISTS tmp.ticketProblems;
        CREATE TEMPORARY TABLE tmp.ticketProblems (
            ticketFk INT(11) PRIMARY KEY,
            isFreezed INTEGER(1) DEFAULT 0,
            risk DECIMAL(10,2) DEFAULT 0,
            hasTicketRequest INTEGER(1) DEFAULT 0,
            isAvailable INTEGER(1) DEFAULT 1
        ) ENGINE = MEMORY;

     DROP TEMPORARY TABLE IF EXISTS tmp.ticketList;
        CREATE TEMPORARY TABLE tmp.ticketList
        (PRIMARY KEY (ticketFk))
         ENGINE = MEMORY
            SELECT tp.ticketFk, c.id clientFk
                FROM tmp.ticketGetProblems tp
        JOIN vn.client c ON c.id = tp.clientFk;
 
    INSERT INTO tmp.ticketProblems(ticketFk, isFreezed)
        SELECT DISTINCT tl.ticketFk, 1
            FROM tmp.ticketList tl
                JOIN vn.client c ON c.id = tl.clientFk
            WHERE c.isFreezed;

    DELETE tl FROM tmp.ticketList tl
        JOIN tmp.ticketProblems tp ON tl.ticketFk = tp.ticketFk;

     DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt;
     CREATE TEMPORARY TABLE tmp.clientGetDebt
        (PRIMARY KEY (clientFk))
        ENGINE = MEMORY
            SELECT DISTINCT clientFk
                FROM tmp.ticketList;

    CALL clientGetDebt(CURDATE());

    INSERT INTO tmp.ticketProblems(ticketFk, risk)
        SELECT DISTINCT tl.ticketFk, r.risk
            FROM tmp.ticketList tl
                JOIN vn.ticket t ON t.id = tl.ticketFk
                JOIN vn.agencyMode a ON t.agencyModeFk = a.id
                JOIN tmp.risk r ON r.clientFk = t.clientFk
                JOIN vn.client c ON c.id = t.clientFk
            WHERE r.risk > c.credit + 10
                AND a.deliveryMethodFk != 3
        ON DUPLICATE KEY UPDATE
            risk = r.risk;
  
    INSERT INTO tmp.ticketProblems(ticketFk, hasTicketRequest)
        SELECT DISTINCT tl.ticketFk, 1
            FROM tmp.ticketList tl
                JOIN vn.ticketRequest tr ON tr.ticketFk = tl.ticketFk
            WHERE tr.isOK IS NULL
        ON DUPLICATE KEY UPDATE
            hasTicketRequest = 1;
      
    OPEN vCursor;

    WHILE NOT vDone
    DO
        FETCH vCursor INTO vWarehouse, vDate;
   
        CALL cache.visible_refresh(vVisibleCache, FALSE, vWarehouse);
        CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouse, vDate);

        INSERT INTO tmp.ticketProblems(ticketFk, isAvailable)
            SELECT tl.ticketFk, 0
                FROM tmp.ticketList tl
                    JOIN vn.ticket t ON t.id = tl.ticketFk
                    LEFT JOIN vn.sale s ON s.ticketFk = t.id
                    JOIN vn.item i ON i.id = s.itemFk
                    JOIN vn.itemType it on it.id = i.typeFk
                    LEFT JOIN cache.visible v ON i.id = v.item_id
                    AND v.calc_id = vVisibleCache
                    LEFT JOIN cache.available av ON av.item_id = i.id
                    AND av.calc_id = vAvailableCache
                WHERE date(t.shipped) = vDate
                    AND categoryFk != 6
                    AND s.quantity > IFNULL(v.visible, 0)
                    AND IFNULL(av.available, 0) < 0
                    AND s.isPicked = FALSE
                    AND NOT i.generic
                    AND vWarehouse = t.warehouseFk
                GROUP BY tl.ticketFk
            ON DUPLICATE KEY UPDATE
                isAvailable = 0;

    INSERT INTO tmp.ticketProblems(ticketFk, isAvailable)
        SELECT tl.ticketFk, 0
            FROM tmp.ticketList tl
                JOIN vn.ticket t ON t.id = tl.ticketFk
                LEFT JOIN vn.sale s ON s.ticketFk = t.id
                JOIN vn.item i ON i.id = s.itemFk
                JOIN vn.itemType it on it.id = i.typeFk
                LEFT JOIN cache.visible v ON i.id = v.item_id AND v.calc_id = vVisibleCache
                LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache
            WHERE IFNULL(av.available, 0) >= 0
                AND s.quantity > IFNULL(v.visible, 0)
                AND s.isPicked = FALSE
                AND s.reserved = FALSE
                AND it.categoryFk != 6
                AND date(t.shipped) = vDate
                AND NOT i.generic
                AND CURDATE() = vDate
                AND t.warehouseFk = vWarehouse
            GROUP BY tl.ticketFk
        ON DUPLICATE KEY UPDATE
            isAvailable = 0;

    END WHILE;

    CLOSE vCursor;
   
    DROP TEMPORARY TABLE
        tmp.clientGetDebt,
        tmp.ticketList; 
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `tickets_in_a_week` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `tickets_in_a_week`(IN intWEEK INT(2), IN intYEAR INT(4), IN idART INT(11), IN intWH INT(2))
BEGIN
	DECLARE period INT(6) DEFAULT intYEAR * 100 + intWEEK;
    DECLARE datINI DATE;
    DECLARE datFIN DATETIME;
    
	-- Seleccionamos la fecha minima/maxima del periodo que vamos a consultar
	SELECT MIN(`date`) INTO datINI FROM vn2008.`time` t WHERE t.period = period;
	SELECT TIMESTAMP(MAX(`date`),'23:59:59') INTO datFIN FROM vn2008.`time` t WHERE t.period = period;
        
       SELECT T.Fecha,
              T.Id_Ticket,
              M.Cantidad,
              M.Id_Article,
              T.Alias,
              M.PrecioFijado,
              M.Preu,
              M.Id_Movimiento,
              T.warehouse_id,
              W.name,
              ticket_state(Factura, PedidoImpreso, Etiquetasemitidas, blocked) as Estado,
              M.Descuento
       FROM Movimientos M
       INNER JOIN Tickets T using(Id_Ticket)
       LEFT JOIN warehouse W ON W.id = T.warehouse_id
       WHERE M.Id_Article = idART AND T.Fecha BETWEEN datINI and datFIN
	   AND IF(intWH = 0, W.comisionantes, intWH =T.warehouse_id)
       ORDER BY T.Fecha, T.Id_Ticket;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `tickets_in_a_week_by_type` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `tickets_in_a_week_by_type`(IN intWEEK INT(2), IN intYEAR INT(4), IN idART INT(11), IN intWH INT(2))
BEGIN

	DECLARE intTIPO INT;
	DECLARE period INT(6) DEFAULT intYEAR * 100 + intWEEK;
    DECLARE datINI DATE;
    DECLARE datFIN DATE;

	SELECT tipo_id INTO intTIPO FROM Articles WHERE Id_Article = idART;
    
	-- Seleccionamos la fecha minima/maxima del periodo que vamos a consultar
	SELECT MIN(`date`) INTO datINI FROM vn2008.`time` t WHERE t.period = period;
	SELECT TIMESTAMP(MAX(`date`),'23:59:59') INTO datFIN FROM vn2008.`time` t WHERE t.period = period;

       SELECT T.Fecha,
              T.Id_Ticket,
              M.Cantidad,
              M.Id_Article,
              T.Alias,
              M.PrecioFijado,
              M.Preu,
              M.Id_Movimiento,
              T.warehouse_id,
              W.name,
              ticket_state(Factura, PedidoImpreso, Etiquetasemitidas, blocked) as Estado,
              M.Descuento
       FROM Movimientos M
	   JOIN Articles A using(Id_Article)
       INNER JOIN Tickets T ON M.Id_Ticket = T.Id_Ticket
       LEFT JOIN warehouse W ON W.id = T.warehouse_id
       WHERE A.tipo_id = intTIPO
       AND T.Fecha between datINI and datFIN
	   AND IF(intWH = 0, W.comisionantes, intWH =T.warehouse_id)
       ORDER BY T.Fecha, T.Id_Ticket;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `tickets_week_joined` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `tickets_week_joined`(IN intWEEK INT(2), IN intYEAR INT(4), IN idART INT(11), IN intWhJoined INT(2))
BEGIN


	DECLARE datSTART date;
	DECLARE datEND date;

	
	SET datSTART = TIMESTAMPADD(YEAR,intYEAR,'0000-01-01');
	SET datSTART = TIMESTAMPADD(WEEK, intWEEK-1,datSTART);
    SET datSTART = TIMESTAMPADD(DAY,-1 * WEEKDAY(datSTART),datSTART);
  


-- Año 2014
/*
IF datSTART = '2013-12-31' THEN 

	SET datSTART = '2013-12-30' ;

END IF;
*/


	SET datEND = TIMESTAMPADD(DAY,7,datSTART);



       SELECT T.Fecha,
              T.Id_Ticket,
              M.Cantidad,
              M.Id_Article,
              T.Alias,
              M.PrecioFijado,
              M.Preu,
              M.Id_Movimiento,
              T.warehouse_id,
              wa.alias `name`,
              ticket_state(Factura, PedidoImpreso, Etiquetasemitidas, blocked) as Estado,
              M.Descuento
		FROM Movimientos M
		JOIN Tickets T ON M.Id_Ticket = T.Id_Ticket
		JOIN warehouse_joined wj ON wj.warehouse_id = T.warehouse_id
		JOIN warehouse_alias wa ON wa.warehouse_alias_id = wj.warehouse_alias_id
		WHERE M.Id_Article = idART
		AND T.Fecha between datSTART and datEND
		AND intWhJoined IN (0,wj.warehouse_alias_id)
		ORDER BY T.Fecha, T.Id_Ticket;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `tickets_week_type_joined` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `tickets_week_type_joined`(IN intWEEK INT(2), IN intYEAR INT(4), IN idART INT(11), IN intWhJoined INT(2))
BEGIN

		DECLARE intTIPO INT;
		DECLARE datSTART date;
		DECLARE datEND date;

	SELECT tipo_id INTO intTIPO FROM Articles WHERE Id_Article = idART;

	SET datSTART = TIMESTAMPADD(YEAR,intYEAR,'0000-01-01');
	SET datSTART = TIMESTAMPADD(WEEK, intWEEK-1,datSTART);
    SET datSTART = TIMESTAMPADD(DAY,-1 * WEEKDAY(datSTART),datSTART);
  
	SET datEND = TIMESTAMPADD(DAY,7,datSTART);



       SELECT T.Fecha,
              T.Id_Ticket,
              M.Cantidad,
              M.Id_Article,
              T.Alias,
              M.PrecioFijado,
              M.Preu,
              M.Id_Movimiento,
              T.warehouse_id,
              wa.alias `name`,
              ticket_state(Factura, PedidoImpreso, Etiquetasemitidas, blocked) as Estado,
              M.Descuento
		FROM Movimientos M
		JOIN Articles A using(Id_Article)
		INNER JOIN Tickets T ON M.Id_Ticket = T.Id_Ticket
		JOIN warehouse_joined wj ON wj.warehouse_id = T.warehouse_id
		JOIN warehouse_alias wa ON wa.warehouse_alias_id = wj.warehouse_alias_id
		WHERE A.tipo_id = intTIPO
		AND T.Fecha between datSTART and datEND
		AND intWhJoined IN (0,wj.warehouse_alias_id)
		ORDER BY T.Fecha, T.Id_Ticket;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_canarias` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_canarias`(IN v_entrada BIGINT, IN v_ticket BIGINT)
BEGIN


set @w := 1;
set @tr := 0;
set @e := v_entrada;
set @t := v_ticket;

select id, IF(warehouse_id_out = 13, @w, warehouse_id_out) into @tr, @w from travel join Entradas on id = travel_id where Id_Entrada = @e;

update travel tr join Entradas e on tr.id = e.travel_id set warehouse_id_out = 13 where Id_Entrada = @e and warehouse_id_out <> 13;

update Tickets set warehouse_id = @w where Id_Ticket = @t;

delete mc.* from Movimientos_componentes mc join Movimientos m using(Id_Movimiento) where Id_Ticket = @t;

insert into Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
select Id_Movimiento, 28, nz(Costefijo) 
from Movimientos m
join Compres c on Id_Entrada = @e and c.Id_Article = m.Id_Article
where Id_Ticket = @t
on DUPLICATE KEY UPDATE Valor = nz(Costefijo) ;

insert into Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
select Id_Movimiento, 29, Preu - nz(Costefijo) 
from Movimientos m
join Compres c on Id_Entrada = @e and c.Id_Article = m.Id_Article
where Id_Ticket = @t
on DUPLICATE KEY UPDATE Valor = Preu - nz(Costefijo) ;

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

SET @a:=0;

SELECT  IF(@a = Id_Movimiento, NULL, Concepte) as Concepte
       ,IF(@a = Id_Movimiento, NULL, Cantidad) as Cantidad
       ,IF(@a = Id_Movimiento, NULL, Id_Article) as Id_Article
       , @a:= Id_Movimiento as IdM
       , Id_Article as IdA
       , Componente
       ,  Valor
       , Importe 
       , base
       , margen
       
FROM
(
SELECT  m.Id_Movimiento
      , m.Concepte
	  , tc.Componente
      , m.Cantidad
	  , mc.Valor
      , round(m.Cantidad * mc.Valor,3)  as Importe
      , Id_Article
      , base 
      , margen
FROM vn2008.Movimientos m
JOIN vn2008.Movimientos_componentes mc using(Id_Movimiento)
INNER JOIN bi.tarifa_componentes tc ON mc.Id_Componente = tc.Id_Componente
INNER JOIN bi.tarifa_componentes_series tcs using(tarifa_componentes_series_id)
WHERE m.Id_Ticket = idTICKET
ORDER BY Id_Movimiento
) sub; 


        




END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_from_Entry` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_from_Entry`(IN IdEntrada INT(11), IN IdCliente INT(6), IN IdEmpresa INT(4), IN buying_quote DOUBLE, IN Ratio DOUBLE)
BEGIN

	DECLARE idTICKET INT(11);

	INSERT INTO Tickets(Id_Cliente, warehouse_id, Fecha, Alias, Id_Agencia, Id_Consigna, Id_Trabajador, empresa_id, Etiquetasemitidas, Localizacion)
	SELECT               IdCliente, 13, shipment, Consignatario, TR.agency_id, Id_Consigna, 20, IdEmpresa, TRUE, IdEntrada
	FROM Entradas E
		JOIN travel TR ON TR.id = E.travel_id
		JOIN (SELECT Consignatario, Id_Consigna FROM Consignatarios WHERE Id_Cliente = IdCliente AND Predeterminada LIMIT 1) Consigna
	WHERE Id_Entrada = IdEntrada;
	-- JOIN Agencias AG ON AG.Id_Agencia = TR.agency_id

	SELECT LAST_INSERT_ID() INTO idTICKET;

	INSERT INTO Movimientos(Id_Ticket, Id_Article, Concepte, Cantidad, Preu, PrecioFijado)
	SELECT idTICKET, Id_Article, Article, round(Cantidad * IF(Cantidad > round(1+ (1/buying_quote),0),buying_quote,1), 0), ROUND(Costefijo * Ratio,2), TRUE
	FROM Compres c 
		JOIN Articles a using(Id_Article)
		JOIN Tipos t on t.tipo_id = a.tipo_id
		JOIN reinos r on r.id = t.reino_id
	WHERE Id_Entrada = idEntrada
		AND r.display <> 0
		AND Cantidad * buying_quote > 1;

	SELECT idTICKET;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_from_Entry_cursor` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `Ticket_from_Entry_cursor`(IN IdEmpresa INt(4), IN IdCliente INT(5), IN buying_quote DOUBLE, IN Ratio DOUBLE)
BEGIN

DECLARE done BIT DEFAULT 0;
DECLARE IdEntrada INT(10);

-- Declaro el cursor para las entradas
DECLARE cursor_entradas CURSOR FOR 
SELECT Id_Entrada
FROM Entradas E 
JOIN travel TR ON TR.id = E.travel_id
WHERE shipment BETWEEN '2013-04-01' AND '2013-04-30'
AND warehouse_id = 17
and warehouse_id_out = 1;



DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

OPEN cursor_entradas;

REPEAT

    FETCH cursor_entradas INTO IdEntrada;
    
    CALL Ticket_from_Entry(IdEntrada, IdCliente, IdEmpresa, buying_quote, Ratio);
    
    
UNTIL done END REPEAT;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_newkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_newkk`(
                       IN idC INT
                     , IN newFEC DATE
                     , IN idWH INT
                     , IN idUSER INT
                     , IN idEMP INT
                     , IN idCON INT
                     , IN intTIPO INT
					 , IN idRUTA INT
                     , IN datLANDING DATE
                     , OUT newTICKET INT)
BEGIN
-- DEPRECATED usar ticketCreate
	DECLARE boolaux TINYINT;

	SET boolaux = If(IdC = 200 Or IdC = 400 Or intTIPO = 23, True, False);

	INSERT INTO Tickets (
		Id_Cliente,
		Fecha,
		Id_Consigna,
		Id_Trabajador,
		Id_Agencia,
		Alias,
		Etiquetasemitidas,
		Firmado,
		warehouse_id,
		Id_Ruta,
		empresa_id,
        landing) 
    SELECT
		IdC,
		newFEC,
		Id_Consigna,
		idUSER,
		IF(intTIPO,intTIPO,Id_Agencia),
		consignatario,
		boolaux,
		boolaux,
		idWH,
		IF(idRUTA,idRuta,NULL),
		idEMP,
        datLANDING
	FROM Consignatarios c
		INNER JOIN Agencias a USING(Id_Agencia)
	WHERE IF(IdCON, Id_Consigna = IdCON, Predeterminada != 0)
		AND Id_Cliente = idC
    LIMIT 1;

	SELECT LAST_INSERT_ID() INTO newTICKET;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_new_completkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_new_completkk`(
                       IN idC INT
                     , IN newFEC DATE
                     , IN idWH INT
                     , IN idUSER INT
                     , IN idEMP INT
                     , IN idCON INT
                     , IN intTIPO INT
					 , IN idRUTA INT
                     , OUT newTICKET INT)
BEGIN
-- DEPRECATED usar ticketCreate
	DECLARE boolaux TINYINT;


	SET boolaux = If(IdC = 200 Or IdC = 400 Or intTIPO = 23, True, False);

	INSERT INTO Tickets (
		Id_Cliente,
		Fecha,
		Id_Consigna,
		Id_Trabajador,
		Id_Agencia,
		Alias,
		Etiquetasemitidas,
		Firmado,
		warehouse_id,
		Id_Ruta,
		empresa_id) 
    SELECT
		IdC,
		newFEC,
		Id_Consigna,
		idUSER,
		IF(intTIPO,intTIPO,Id_Agencia),
		consignatario,
		boolaux,
		boolaux,
		idWH,
		IF(idRUTA,idRuta,NULL),
		idEMP
	FROM Consignatarios c
		INNER JOIN Agencias a USING(Id_Agencia)
	WHERE IF(IdCON, Id_Consigna = IdCON, Predeterminada != 0)
		AND Id_Cliente = idC
    LIMIT 1;

	SELECT LAST_INSERT_ID() INTO newTICKET;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_portes_cobrados` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `ticket_portes_cobrados`(IN idTICKET BIGINT)
BEGIN

SELECT  m.Id_Article, m.Concepte, m.Cantidad, mc.Valor, round(m.Cantidad * mc.Valor,2)  as Porte 
FROM vn2008.Movimientos m
JOIN vn2008.Movimientos_componentes mc using(Id_Movimiento)
INNER JOIN bi.tarifa_componentes tc ON mc.Id_Componente = tc.Id_Componente
WHERE m.Id_Ticket = idTICKET
AND tc.tarifa_componentes_series_id = 6; -- agencia
        




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

SELECT 
    TICKET_FREIGHT(vTicketId) AS Porte_Volumen,
    SUM(CAST(es.shipping_charge AS DECIMAL (10 , 2 ))) AS Porte_Bultos,
    IFNULL(is_volumetric,0) AS is_volumetric
FROM
    vn2008.v_expeditions_shipping_charge2 es
JOIN
 vn2008.Tickets t on es.Id_Ticket = t.Id_Ticket
LEFT JOIN 
 vn2008.Rutas r on r.Id_Ruta = t.Id_Ruta
LEFT JOIN 
 vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia
WHERE
    es.Id_Ticket = vTicketId;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_volumen` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_volumen`(IN idT INT)
BEGIN
	DECLARE intWh INTEGER;
	DECLARE datFecha DATE;

	DROP TEMPORARY TABLE IF EXISTS ticket_volumen;
	SELECT warehouse_id, Fecha INTO intWh,datFecha FROM Tickets WHERE Id_Ticket = idT;
    
	CREATE TEMPORARY TABLE IF NOT EXISTS ticket_volumen ENGINE MEMORY
	SELECT Id_Article,Cantidad, Concepte, VolUd as m3_uni, Volumen as m3, @m3:= @m3 + ifnull(Volumen,0) as m3_total
	FROM
	(
		SELECT round(A.compression * r.cm3 / 1000000,3) as VolUd ,M.Cantidad, round(A.compression * r.cm3 * M.Cantidad / 1000000,3) as Volumen, 
				M.Id_Article, Concepte, @m3:= 0, @vol:=0, Id_Agencia
			FROM Movimientos M
				JOIN Articles A ON A.Id_Article = M.Id_Article
				JOIN Tickets T on T.Id_Ticket = M.Id_Ticket
                JOIN bi.rotacion r ON r.Id_Article = M.Id_Article AND r.warehouse_id = T.warehouse_id
			WHERE M.Id_Ticket = idT
	) sub;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `top_seller` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `top_seller`()
BEGIN
	
	drop table if exists top_sellers_min;
	create temporary table top_sellers_min ENGINE = MEMORY
	select a.Id_Article , tip.reino_id as Reino, count(m.Id_Article) as contados 
	  from Movimientos m
	  inner join Tickets t
	  on m.Id_Ticket = t.Id_Ticket
	  inner join Articles a 
	  on a.Id_Article = m.Id_Article
	  inner join Tipos tip 
	  on a.tipo_id = tip.tipo_id
	  inner join reinos r
	  on r.id = tip.reino_id
	  where t.Fecha between timestampadd(day,-7,curdate()) and curdate()
	  group by m.Id_Article;

	drop table if exists top_seller;
	create temporary table top_seller ENGINE = MEMORY                      
	select a.Article, tmp.Id_Article , a.Foto as foto, a.tipo_id as Id_Tipo, 
	tmp.Reino, r.reino as ReinoNombre, tip.Tipo as Tipo, tmp.contados
	from top_sellers_min tmp
	  inner join Articles a 
	  on a.Id_Article = tmp.Id_Article
	  inner join Tipos tip 
	  on a.tipo_id = tip.tipo_id
	  inner join reinos r
	  on r.id = tmp.Reino
	  where tmp.Reino = 1
		order by contados desc 
		limit 5;
  
	insert into top_seller
	select 
	a.Article, tmp.Id_Article , a.Foto as foto, a.tipo_id as Id_Tipo, 
	tmp.Reino, r.reino as ReinoNombre, tip.Tipo as Tipo, tmp.contados
	from top_sellers_min tmp
	  inner join Articles a 
	  on a.Id_Article = tmp.Id_Article
	  inner join Tipos tip 
	  on a.tipo_id = tip.tipo_id
	  inner join reinos r
	  on r.id = tmp.Reino
	  where tmp.Reino = 2
		order by contados desc 
		limit 5;

	insert into top_seller
	select 
	a.Article, tmp.Id_Article , a.Foto as foto, a.tipo_id as Id_Tipo, 
	tmp.Reino, r.reino as ReinoNombre, tip.Tipo as Tipo, tmp.contados
	from top_sellers_min tmp
	  inner join Articles a 
	  on a.Id_Article = tmp.Id_Article
	  inner join Tipos tip 
	  on a.tipo_id = tip.tipo_id
	  inner join reinos r
	  on r.id = tmp.Reino
	  where tmp.Reino = 3
		order by contados desc 
		limit 5;

	insert into top_seller
	select 
	a.Article, tmp.Id_Article , a.Foto as foto, a.tipo_id as Id_Tipo, 
	tmp.Reino, r.reino as ReinoNombre, tip.Tipo as Tipo, tmp.contados
	from top_sellers_min tmp
	  inner join Articles a 
	  on a.Id_Article = tmp.Id_Article
	  inner join Tipos tip 
	  on a.tipo_id = tip.tipo_id
	  inner join reinos r
	  on r.id = tmp.Reino
	  where tmp.Reino = 4
		order by contados desc 
		limit 5;

	insert into top_seller
	select 
	a.Article, tmp.Id_Article , a.Foto as foto, a.tipo_id as Id_Tipo, 
	tmp.Reino, r.reino as ReinoNombre, tip.Tipo as Tipo, tmp.contados
	from top_sellers_min tmp
	  inner join Articles a 
	  on a.Id_Article = tmp.Id_Article
	  inner join Tipos tip 
	  on a.tipo_id = tip.tipo_id
	  inner join reinos r
	  on r.id = tmp.Reino
	  where tmp.Reino = 5
		order by contados desc 
		limit 5;

	insert into top_seller
	select 
	a.Article, tmp.Id_Article , a.Foto as foto, a.tipo_id as Id_Tipo, 
	tmp.Reino, r.reino as ReinoNombre, tip.Tipo as Tipo, tmp.contados
	from top_sellers_min tmp
	  inner join Articles a 
	  on a.Id_Article = tmp.Id_Article
	  inner join Tipos tip 
	  on a.tipo_id = tip.tipo_id
	  inner join reinos r
	  on r.id = tmp.Reino
	  where tmp.Reino = 7
		order by contados desc 
		limit 5;

	drop table if exists top_sellers_min;	

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



#Vamos a calcular el porcentaje a incrementar las cantidades de las lineas de movimiento para inflar / desinflar la base final

DECLARE dblBASE_INICIAL DOUBLE DEFAULT 0;
DECLARE dblBASE_FINAL DOUBLE DEFAULT 0;
DECLARE dblAUMENTO DOUBLE DEFAULT 1;


SELECT SUM(Cantidad * Preu * (100 - Descuento) / 100)
INTO dblBASE_INICIAL
FROM Movimientos
WHERE Id_Ticket = intIDTICKET;

SET dblBASE_FINAL = dblBASE_INICIAL;


#Eliminamos lineas a 0

DELETE FROM Movimientos WHERE Cantidad = 0 AND Id_Ticket = intIDTICKET;

# Vamos a ir probando incrementos paulatinos hasta que encontremos el que supera lo pedido, teniendo en cuenta el sentido del incremento

IF dblINCREMENTO < 0 THEN

  

  WHILE (dblBASE_FINAL > dblBASE_INICIAL + dblINCREMENTO) or (dblAUMENTO < 0 ) DO

  SET dblAUMENTO = dblAUMENTO - 0.01;

  SELECT SUM(IF(@cantidad:= ROUND(dblAUMENTO * Cantidad),@cantidad,1) * Preu * (100 - Descuento) / 100) 
  INTO dblBASE_FINAL
  FROM Movimientos
  WHERE Id_Ticket = intIDTICKET;

  END WHILE;

ELSE

  WHILE dblBASE_FINAL < dblBASE_INICIAL + dblINCREMENTO DO

  SET dblAUMENTO = dblAUMENTO + 0.01;

  SELECT SUM(IF(@cantidad:= ROUND(dblAUMENTO * Cantidad),@cantidad,1) * Preu * (100 - Descuento) / 100) 
   INTO dblBASE_FINAL
  FROM Movimientos
  WHERE Id_Ticket = intIDTICKET;

  END WHILE;
  
END IF;

UPDATE Movimientos
SET Cantidad = IF(@cantidad:= ROUND(dblAUMENTO * Cantidad),@cantidad,1)
WHERE Id_Ticket = intIDTICKET;

SELECT tipoiva
     , ROUND(SUM(Cantidad * Preu * (100 - Descuento) / 100),2) as Base
     , ROUND(ROUND(SUM(Cantidad * Preu * (100 - Descuento) / 100),2) * iva / 100,2) as Cuota 
FROM Movimientos M
INNER JOIN Articles A USING(Id_Article)
INNER JOIN tblIVA USING(tipoiva)
WHERE Id_Ticket = intIDTICKET
GROUP BY tipoiva;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `traslado` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `traslado`(IN i_entrada INTEGER)
BEGIN
-- Lo esta probando JFP 2018-12-13
	DECLARE dateShipment DATE;
	DECLARE dateLanding DATE;
	DECLARE warehouseShipment INTEGER;
	DECLARE warehouseLanding INTEGER;
	DECLARE v_calc_visible INTEGER;
    DECLARE vInventoryDate DATE;

	SET vInventoryDate := date_inv();
	SELECT shipment, landing, warehouse_id_out, warehouse_id
	INTO  dateShipment, dateLanding, warehouseShipment, warehouseLanding
	FROM travel t JOIN Entradas e ON t.id = e.travel_id
	WHERE Id_Entrada = i_entrada;

	CALL buy_tarifas_table(i_entrada);

	-- Traslado en almacen origen

	DROP TEMPORARY TABLE IF EXISTS buy_edi_temp;
	CREATE TEMPORARY TABLE buy_edi_temp
			(KEY (Id_Article), INDEX(Id_Compra)) ENGINE = MEMORY
		SELECT * 
			FROM (SELECT c.Id_Article, c.Id_Compra
					FROM Compres c INNER JOIN Entradas e USING(Id_Entrada)
					INNER JOIN travel t ON t.id = e.travel_id
						WHERE t.landing BETWEEN vInventoryDate AND dateShipment
							AND c.Novincular = FALSE
							AND c.Tarifa2 >= 0
						ORDER BY (warehouseShipment = t.warehouse_id) DESC, t.landing DESC) t
		GROUP BY Id_Article;

	CALL vn.buyUltimateFromInterval(warehouseLanding,vInventoryDate,dateLanding);
        
	IF dateShipment >= CURDATE() THEN

        CALL availableTraslate(warehouseShipment, dateShipment,NULL);
		CALL `cache`.visible_refresh(v_calc_visible,TRUE,warehouseShipment);
        
		DROP TEMPORARY TABLE IF EXISTS tmp_item;
		CREATE TEMPORARY TABLE tmp_item (UNIQUE INDEX i USING HASH (item_id)) ENGINE = MEMORY
			SELECT item_id, visible,0 available FROM `cache`.visible WHERE calc_id = v_calc_visible;
		INSERT INTO tmp_item(item_id, available)
			SELECT a.item_id, a.available FROM availableTraslate a
			ON DUPLICATE KEY UPDATE available = a.available;
	ELSE
		CALL item_stock(warehouseShipment, dateShipment,NULL);
	END IF;

	DROP TEMPORARY TABLE IF EXISTS Traslados;
	CREATE TEMPORARY TABLE Traslados ENGINE MEMORY
		SELECT tp.Id_Tipo AS Tipo,
        
				tp.reino_id,
                
				ar.tipo_id,
                
				ar.Id_Article AS article_id,

				ar.Article,

				ar.Medida,

				ar.Categoria,

				ar.Color,

				Origen.abreviatura as Origen,

				CE.Cantidad,

				ar.Tallos,

				CAST(AIM.visible AS DECIMAL(10,0)) as vis1,

				CAST(AIM.available AS DECIMAL(10,0)) as dis1,

				0 as vis2,

				0 as dis2,
				
				COALESCE(/*cl.`grouping`, */CE.`grouping`, C.`grouping`) as `grouping`,
                
				COALESCE(/*cl.Packing, */CE.Packing, C.Packing) as Packing,
				
				COALESCE(cl.caja, CE.caja, C.caja) as caja,

				IFNULL(C.Productor, P2.Alias) AS Productor,

				C.Id_Cubo,

				1 Tinta,

				CE.Id_Compra,

				CE.Etiquetas,

				C.buy_edi_id,
                
                tp.Id_Trabajador,
                
                CB.Volumen,
                
                CB.x, CB.y, CB.z,
                
                IFNULL(C.Costefijo,0) Costefijo,
                
                IFNULL(C.Comisionfija,0) Comisionfija,
                
                IFNULL(C.Portefijo,0) Portefijo,
                
                A.m3,
                
                E.comision,
                
                CB.Retornable,
                
                IFNULL(CEB.Valor,CB.Valor) Valor,
                
                t3, t2, tp.promo,
                
                C.`grouping` groupingOrigin,
                
                C.Packing PackingOrigin,
                
                C.Id_Compra CompraOrigin,
                
                CB.costeRetorno
                
			FROM Articles ar
				LEFT JOIN tmp_item AIM  ON AIM.item_id = ar.Id_Article
				LEFT JOIN Tipos tp ON tp.tipo_id = ar.tipo_id
				LEFT JOIN Origen ON Origen.id = ar.id_origen
				LEFT JOIN buy_edi_temp lb ON lb.Id_Article = ar.Id_Article              
				LEFT JOIN Compres C ON C.Id_Compra = lb.Id_Compra
				LEFT JOIN Cubos CB ON CB.Id_Cubo = C.Id_Cubo
				LEFT JOIN Entradas E2 ON E2.Id_Entrada = C.Id_Entrada
				LEFT JOIN Proveedores P2 ON P2.Id_Proveedor = E2.Id_Proveedor
				LEFT JOIN Entradas E ON E.Id_Entrada = i_entrada
				LEFT JOIN travel TR ON TR.id = E.travel_id
				LEFT JOIN Agencias A ON A.Id_Agencia = TR.agency_id
				LEFT JOIN Compres CE ON CE.Id_Article = ar.Id_Article AND CE.Id_Entrada = i_entrada
				LEFT JOIN Cubos CEB ON CEB.Id_Cubo = CE.Id_Cubo
				LEFT JOIN tblTARIFAS ON TRUE
                LEFT JOIN tmp.buyUltimateFromInterval bufi ON bufi.itemFk = ar.Id_Article
                LEFT JOIN Compres cl ON cl.Id_Compra = bufi.buyFk
		WHERE tp.reino_id <> 6 AND tp.reino_id <> 8
		AND E.Redada = FALSE;
	
    CREATE INDEX tindex USING HASH ON Traslados (article_id);

-- Inventario en el warehouse destino
	IF dateShipment >= CURDATE() THEN

		CALL cache.visible_refresh(v_calc_visible, TRUE, warehouseLanding);
		CALL availableTraslate(warehouseLanding, dateLanding,warehouseShipment);

		UPDATE Traslados t
			LEFT JOIN availableTraslate a ON t.article_id = a.item_id
			LEFT JOIN `cache`.visible v ON v.calc_id = v_calc_visible AND t.article_id = v.item_id
		SET vis2 = v.visible, dis2 = a.available;
        
	END IF;
-- ---------------------------------------------

    SELECT t.*,
			
            Cantidad - MOD(Cantidad , `grouping`) as Subcantidad,

			MOD(Cantidad , `grouping`) as Soll,
            
			ROUND((IF(Volumen > 0,Volumen,x * y * IF(z = 0, Medida + 10, z))) / Packing,0) as cm3,

			Costefijo + Comisionfija + Portefijo AS Cost,

			@porte := ROUND((IF(Volumen > 0,Volumen,x * y * IF(z = 0, Medida + 10, z))) * m3 / 1000000 / Packing ,3) AS Porte,

			@comision := ROUND((Costefijo + Comisionfija + Portefijo) * comision / 100 ,3) AS Comision,

			ROUND(@embalaje := (costeRetorno + IF(Retornable != 0, 0, Valor)) / packing ,3) AS Embalaje,

			@coste := IFNULL((Costefijo + Comisionfija + Portefijo),0) + IFNULL(@embalaje,0) + IFNULL(@porte,0) + IFNULL(@comision,0)  AS Coste,

			@t3 := ROUND(@coste / ( (100 - t3 - t.promo)/100),2) AS Tarifa3,
			
			ROUND(@t3 * (1 + ((t2 - t3)/100)),2) AS Tarifa2,
            
            0 selected
			
		FROM Traslados t 
			WHERE vis1 <> 0 OR dis1 <> 0 OR vis2 <> 0 OR dis2 <> 0
            ORDER BY tipo_id, Article, Medida, Categoria, Origen;

	DROP TEMPORARY TABLE IF EXISTS Traslados;
    DROP TEMPORARY TABLE IF EXISTS tmp_item;
	DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimateFromInterval;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `trasladoKk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `trasladoKk`(IN i_entrada INTEGER)
BEGIN
	DECLARE dateShipment DATE;
	DECLARE dateLanding DATE;
	DECLARE warehouseShipment INTEGER;
	DECLARE warehouseLanding INTEGER;
    DECLARE v_calc_available INTEGER;
	DECLARE v_calc_visible INTEGER;

	SELECT shipment, landing, warehouse_id_out, warehouse_id
	INTO  dateShipment, dateLanding, warehouseShipment, warehouseLanding
	FROM travel t JOIN Entradas e ON t.id = e.travel_id
	WHERE Id_Entrada = i_entrada;

	CALL buy_tarifas_table(i_entrada);

	-- Traslado en almacen origen

	DROP TEMPORARY TABLE IF EXISTS buy_edi_temp;

	CREATE TEMPORARY TABLE buy_edi_temp
		(KEY (Id_Article)) ENGINE = MEMORY
	
		SELECT * 
			FROM (SELECT c.Id_Article, c.Id_Compra
					FROM Compres c INNER JOIN Entradas e USING(Id_Entrada)
					INNER JOIN travel t ON t.id = e.travel_id
						WHERE t.landing BETWEEN date_inv() AND dateShipment
							AND c.Novincular = FALSE
							AND c.Tarifa2 >= 0
						ORDER BY (warehouseShipment = t.warehouse_id) DESC, t.landing DESC) t
		GROUP BY Id_Article;

	IF dateShipment >= CURDATE() THEN

        CALL availableTraslate(warehouseShipment, dateShipment,NULL);
		CALL `cache`.visible_refresh(v_calc_visible,TRUE,warehouseShipment);
		DROP TEMPORARY TABLE IF EXISTS tmp_item;
		CREATE TEMPORARY TABLE tmp_item (UNIQUE INDEX i USING HASH (item_id)) ENGINE = MEMORY
			SELECT item_id, visible,0 available FROM `cache`.visible WHERE calc_id = v_calc_visible;
		INSERT INTO tmp_item(item_id, available)
			SELECT a.item_id, a.available FROM availableTraslate a
			ON DUPLICATE KEY UPDATE available = a.available;
	ELSE
		CALL item_stock(warehouseShipment, dateShipment,NULL);
	END IF;

	DROP TEMPORARY TABLE IF EXISTS Traslados;
	CREATE TEMPORARY TABLE Traslados ENGINE MEMORY
		SELECT tp.Id_Tipo AS Tipo,
        
				tp.reino_id,
                
				ar.tipo_id,
                
				ar.Id_Article AS article_id,

				ar.Article,

				ar.Medida,

				ar.Categoria,

				ar.Color,

				Origen.abreviatura as Origen,

				CE.Cantidad,

				ar.Tallos,

				CAST(AIM.visible AS DECIMAL(10,0)) as vis1,

				CAST(AIM.available AS DECIMAL(10,0)) as dis1,

				0 as vis2,

				0 as dis2,
				
				IFNULL(CE.`grouping`,C.`grouping`) as `grouping`,
                
				IFNULL(CE.Packing,C.Packing) as Packing,
				
				IFNULL(CE.caja,C.caja) as caja,

				IFNULL(C.Productor, P2.Alias) AS Productor,

				C.Id_Cubo,

				1 Tinta,

				CE.Id_Compra,

				CE.Etiquetas,

				C.buy_edi_id,
                
                tp.Id_Trabajador,
                
                CB.Volumen,
                
                CB.x, CB.y, CB.z,
                
                IFNULL(C.Costefijo,0) Costefijo,
                
                IFNULL(C.Comisionfija,0) Comisionfija,
                
                IFNULL(C.Portefijo,0) Portefijo,
                
                A.m3,
                
                E.comision,
                
                CB.Retornable,
                
                IFNULL(CEB.Valor,CB.Valor) Valor,
                
                t3, t2, tp.promo,
                
                C.`grouping` groupingOrigin,
                
                C.Packing PackingOrigin,
                
                C.Id_Compra CompraOrigin,
                
                CB.costeRetorno
                
			FROM Articles ar
				LEFT JOIN tmp_item AIM  ON AIM.item_id = ar.Id_Article
				LEFT JOIN Tipos tp ON tp.tipo_id = ar.tipo_id
				LEFT JOIN Origen ON Origen.id = ar.id_origen
				LEFT JOIN buy_edi_temp lb ON lb.Id_Article = ar.Id_Article              
				LEFT JOIN Compres C ON C.Id_Compra = lb.Id_Compra
				LEFT JOIN Cubos CB ON CB.Id_Cubo = C.Id_Cubo
				LEFT JOIN Entradas E2 ON E2.Id_Entrada = C.Id_Entrada
				LEFT JOIN Proveedores P2 ON P2.Id_Proveedor = E2.Id_Proveedor
				LEFT JOIN Entradas E ON E.Id_Entrada = i_entrada
				LEFT JOIN travel TR ON TR.id = E.travel_id
				LEFT JOIN Agencias A ON A.Id_Agencia = TR.agency_id
				LEFT JOIN Compres CE ON CE.Id_Article = ar.Id_Article AND CE.Id_Entrada = i_entrada
				LEFT JOIN Cubos CEB ON CEB.Id_Cubo = CE.Id_Cubo
				LEFT JOIN tblTARIFAS ON TRUE
		WHERE tp.reino_id <> 6 AND tp.reino_id <> 8
		AND E.Redada = FALSE;
	
    CREATE INDEX tindex USING HASH ON Traslados (article_id);

-- Inventario en el warehouse destino
	IF dateShipment >= CURDATE() THEN

		CALL cache.visible_refresh(v_calc_visible, TRUE, warehouseLanding);
		CALL availableTraslate(warehouseLanding, dateLanding,warehouseShipment);

		UPDATE Traslados t
			LEFT JOIN availableTraslate a ON t.article_id = a.item_id
			LEFT JOIN `cache`.visible v ON v.calc_id = v_calc_visible AND t.article_id = v.item_id
		SET vis2 = v.visible, dis2 = a.available;
        
	END IF;
-- ---------------------------------------------

    SELECT t.*,
			
            Cantidad - MOD(Cantidad , `grouping`) as Subcantidad,

			MOD(Cantidad , `grouping`) as Soll,
            
			ROUND((IF(Volumen > 0,Volumen,x * y * IF(z = 0, Medida + 10, z))) / Packing,0) as cm3,

			Costefijo + Comisionfija + Portefijo AS Cost,

			@porte := ROUND((IF(Volumen > 0,Volumen,x * y * IF(z = 0, Medida + 10, z))) * m3 / 1000000 / Packing ,3) AS Porte,

			@comision := ROUND((Costefijo + Comisionfija + Portefijo) * comision / 100 ,3) AS Comision,

			ROUND(@embalaje := (costeRetorno + IF(Retornable != 0, 0, Valor)) / packing ,3) AS Embalaje,

			@coste := IFNULL((Costefijo + Comisionfija + Portefijo),0) + IFNULL(@embalaje,0) + IFNULL(@porte,0) + IFNULL(@comision,0)  AS Coste,

			@t3 := ROUND(@coste / ( (100 - t3 - t.promo)/100),2) AS Tarifa3,
			
			ROUND(@t3 * (1 + ((t2 - t3)/100)),2) AS Tarifa2,
            
            0 selected
			
		FROM Traslados t 
			WHERE vis1 <> 0 OR dis1 <> 0 OR vis2 <> 0 OR dis2 <> 0
            ORDER BY tipo_id, Article, Medida, Categoria, Origen;

	DROP TEMPORARY TABLE IF EXISTS Traslados;
    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 `trasladoTest` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `trasladoTest`(IN i_entrada INTEGER)
BEGIN
-- Lo esta probando JFP 2018-12-13
	DECLARE dateShipment DATE;
	DECLARE dateLanding DATE;
	DECLARE warehouseShipment INTEGER;
	DECLARE warehouseLanding INTEGER;
	DECLARE v_calc_visible INTEGER;
    DECLARE vInventoryDate DATE;

	SET vInventoryDate := date_inv();
	SELECT shipment, landing, warehouse_id_out, warehouse_id
	INTO  dateShipment, dateLanding, warehouseShipment, warehouseLanding
	FROM travel t JOIN Entradas e ON t.id = e.travel_id
	WHERE Id_Entrada = i_entrada;

	CALL buy_tarifas_table(i_entrada);

	-- Traslado en almacen origen

	DROP TEMPORARY TABLE IF EXISTS buy_edi_temp;
	CREATE TEMPORARY TABLE buy_edi_temp
			(KEY (Id_Article), INDEX(Id_Compra)) ENGINE = MEMORY
		SELECT * 
			FROM (SELECT c.Id_Article, c.Id_Compra
					FROM Compres c INNER JOIN Entradas e USING(Id_Entrada)
					INNER JOIN travel t ON t.id = e.travel_id
						WHERE t.landing BETWEEN vInventoryDate AND dateShipment
							AND c.Novincular = FALSE
							AND c.Tarifa2 >= 0
						ORDER BY (warehouseShipment = t.warehouse_id) DESC, t.landing DESC) t
		GROUP BY Id_Article;

	CALL vn.buyUltimateFromInterval(warehouseLanding,vInventoryDate,dateLanding);
        
	IF dateShipment >= CURDATE() THEN

        CALL availableTraslate(warehouseShipment, dateShipment,NULL);
		CALL `cache`.visible_refresh(v_calc_visible,TRUE,warehouseShipment);
        
		DROP TEMPORARY TABLE IF EXISTS tmp_item;
		CREATE TEMPORARY TABLE tmp_item (UNIQUE INDEX i USING HASH (item_id)) ENGINE = MEMORY
			SELECT item_id, visible,0 available FROM `cache`.visible WHERE calc_id = v_calc_visible;
		INSERT INTO tmp_item(item_id, available)
			SELECT a.item_id, a.available FROM availableTraslate a
			ON DUPLICATE KEY UPDATE available = a.available;
	ELSE
		CALL item_stock(warehouseShipment, dateShipment,NULL);
	END IF;

	DROP TEMPORARY TABLE IF EXISTS Traslados;
	CREATE TEMPORARY TABLE Traslados ENGINE MEMORY
		SELECT tp.Id_Tipo AS Tipo,
        
				tp.reino_id,
                
				ar.tipo_id,
                
				ar.Id_Article AS article_id,

				ar.Article,

				ar.Medida,

				ar.Categoria,

				ar.Color,

				Origen.abreviatura as Origen,

				CE.Cantidad,

				ar.Tallos,

				CAST(AIM.visible AS DECIMAL(10,0)) as vis1,

				CAST(AIM.available AS DECIMAL(10,0)) as dis1,

				0 as vis2,

				0 as dis2,
				
				COALESCE(cl.`grouping`, CE.`grouping`, C.`grouping`) as `grouping`,
                
				COALESCE(cl.Packing, CE.Packing, C.Packing) as Packing,
				
				COALESCE(cl.caja, CE.caja, C.caja) as caja,

				IFNULL(C.Productor, P2.Alias) AS Productor,

				C.Id_Cubo,

				1 Tinta,

				CE.Id_Compra,

				CE.Etiquetas,

				C.buy_edi_id,
                
                tp.Id_Trabajador,
                
                CB.Volumen,
                
                CB.x, CB.y, CB.z,
                
                IFNULL(C.Costefijo,0) Costefijo,
                
                IFNULL(C.Comisionfija,0) Comisionfija,
                
                IFNULL(C.Portefijo,0) Portefijo,
                
                A.m3,
                
                E.comision,
                
                CB.Retornable,
                
                IFNULL(CEB.Valor,CB.Valor) Valor,
                
                t3, t2, tp.promo,
                
                C.`grouping` groupingOrigin,
                
                C.Packing PackingOrigin,
                
                C.Id_Compra CompraOrigin,
                
                CB.costeRetorno
                
			FROM Articles ar
				LEFT JOIN tmp_item AIM  ON AIM.item_id = ar.Id_Article
				LEFT JOIN Tipos tp ON tp.tipo_id = ar.tipo_id
				LEFT JOIN Origen ON Origen.id = ar.id_origen
				LEFT JOIN buy_edi_temp lb ON lb.Id_Article = ar.Id_Article              
				LEFT JOIN Compres C ON C.Id_Compra = lb.Id_Compra
				LEFT JOIN Cubos CB ON CB.Id_Cubo = C.Id_Cubo
				LEFT JOIN Entradas E2 ON E2.Id_Entrada = C.Id_Entrada
				LEFT JOIN Proveedores P2 ON P2.Id_Proveedor = E2.Id_Proveedor
				LEFT JOIN Entradas E ON E.Id_Entrada = i_entrada
				LEFT JOIN travel TR ON TR.id = E.travel_id
				LEFT JOIN Agencias A ON A.Id_Agencia = TR.agency_id
				LEFT JOIN Compres CE ON CE.Id_Article = ar.Id_Article AND CE.Id_Entrada = i_entrada
				LEFT JOIN Cubos CEB ON CEB.Id_Cubo = CE.Id_Cubo
				LEFT JOIN tblTARIFAS ON TRUE
                LEFT JOIN tmp.buyUltimateFromInterval bufi ON bufi.itemFk = ar.Id_Article
                LEFT JOIN Compres cl ON cl.Id_Compra = bufi.buyFk
		WHERE tp.reino_id <> 6 AND tp.reino_id <> 8
		AND E.Redada = FALSE;
	
    CREATE INDEX tindex USING HASH ON Traslados (article_id);

-- Inventario en el warehouse destino
	IF dateShipment >= CURDATE() THEN

		CALL cache.visible_refresh(v_calc_visible, TRUE, warehouseLanding);
		CALL availableTraslate(warehouseLanding, dateLanding,warehouseShipment);

		UPDATE Traslados t
			LEFT JOIN availableTraslate a ON t.article_id = a.item_id
			LEFT JOIN `cache`.visible v ON v.calc_id = v_calc_visible AND t.article_id = v.item_id
		SET vis2 = v.visible, dis2 = a.available;
        
	END IF;
-- ---------------------------------------------

    SELECT t.*,
			
            Cantidad - MOD(Cantidad , `grouping`) as Subcantidad,

			MOD(Cantidad , `grouping`) as Soll,
            
			ROUND((IF(Volumen > 0,Volumen,x * y * IF(z = 0, Medida + 10, z))) / Packing,0) as cm3,

			Costefijo + Comisionfija + Portefijo AS Cost,

			@porte := ROUND((IF(Volumen > 0,Volumen,x * y * IF(z = 0, Medida + 10, z))) * m3 / 1000000 / Packing ,3) AS Porte,

			@comision := ROUND((Costefijo + Comisionfija + Portefijo) * comision / 100 ,3) AS Comision,

			ROUND(@embalaje := (costeRetorno + IF(Retornable != 0, 0, Valor)) / packing ,3) AS Embalaje,

			@coste := IFNULL((Costefijo + Comisionfija + Portefijo),0) + IFNULL(@embalaje,0) + IFNULL(@porte,0) + IFNULL(@comision,0)  AS Coste,

			@t3 := ROUND(@coste / ( (100 - t3 - t.promo)/100),2) AS Tarifa3,
			
			ROUND(@t3 * (1 + ((t2 - t3)/100)),2) AS Tarifa2,
            
            0 selected
			
		FROM Traslados t 
			WHERE vis1 <> 0 OR dis1 <> 0 OR vis2 <> 0 OR dis2 <> 0
            ORDER BY tipo_id, Article, Medida, Categoria, Origen;

	DROP TEMPORARY TABLE IF EXISTS Traslados;
    DROP TEMPORARY TABLE IF EXISTS tmp_item;
	-- DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimateFromInterval;

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

DECLARE intEntrada INTEGER;
DECLARE i_FV INTEGER;

SELECT FV INTO  i_FV 
FROM Articles a
JOIN Tipos tp ON tp.tipo_id = a.tipo_id
WHERE a.Id_Article = intArticle;

SET intEntrada  = IF(i_FV, i_entrada_FV,i_entrada_PCA);

SET intEntrada = IF(intEntrada = 0, i_entrada_PCA + i_entrada_FV, intEntrada);


	IF intEntrada > 0 THEN

		CALL buy_tarifas_table(intEntrada);

		INSERT INTO Compres (Id_Article, Etiquetas, Cantidad, Id_Entrada, Id_Cubo, Packing,`grouping`,caja,
			Costefijo, Portefijo, Embalajefijo, Comisionfija, novincular,buy_edi_id)
		SELECT 
			land.Id_Article,
			land.Etiquetas - IFNULL(ship.Etiquetas,0) - (IFNULL(Ventas,0) / land.Packing),
			land.Cantidad - IFNULL(ship.Cantidad,0) - IFNULL(Ventas,0),
			intEntrada,
			land.Id_Cubo,
			land.Packing,
			land.`grouping`,
			land.caja,
			@cost := ROUND(IFNULL(land.Costefijo, 0) + IFNULL(land.Comisionfija, 0) + IFNULL(land.Portefijo, 0),
					3) Costefij,
			@porte := ROUND((@cm3:= cm3_2(land.Id_Cubo, land.Id_Article)) * a.m3 / 1000000 / land.Packing,
					3) Porte,
			land.EmbalajeFijo AS Embalaje,
			@comision := ROUND(land.Costefijo * e2.comision / 100, 3) Comision,
			land.novincular,land.buy_edi_id
	FROM (
		select c_land.Id_Cubo,c_land.Packing,c_land.`grouping`,c_land.Costefijo,c_land.Comisionfija,c_land.Portefijo,c_land.caja,SUM(c_land.Etiquetas) Etiquetas,c_land.EmbalajeFijo,
				c_land.novincular,c_land.buy_edi_id,c_land.Id_Article,SUM(c_land.Cantidad) Cantidad
			from 
			-- Entradas que llegan a vnh
			Compres c_land 
				JOIN
			Entradas e_land ON c_land.Id_Entrada = e_land.Id_Entrada AND c_land.Id_Article = intArticle
				JOIN
			travel t_land ON t_land.id = e_land.travel_id
				JOIN
			Cubos cu ON cu.Id_Cubo = c_land.Id_Cubo 
				WHERE
			-- Entradas que llegan a vnh
			(t_land.warehouse_id = 7 AND t_land.landing = CURDATE())
		) land 
	LEFT JOIN -- Entradas que salen de vnh
			(SELECT SUM(c_ship.Etiquetas) Etiquetas,c_ship.Packing,SUM(c_ship.Cantidad) Cantidad
            FROM Compres c_ship
			LEFT JOIN Entradas e_ship ON c_ship.Id_Entrada = e_ship.Id_Entrada AND c_ship.Id_Article = intArticle
			LEFT JOIN travel t_ship ON t_ship.id = e_ship.travel_id
            WHERE t_ship.warehouse_id_out = 7 AND t_ship.shipment = CURDATE() 
				-- Entrada destino
            ) ship ON TRUE
	JOIN Entradas e2 ON e2.Id_Entrada = intEntrada
	JOIN travel t ON t.id = e2.travel_id
	JOIN Agencias a ON t.agency_id = a.Id_Agencia
            -- Ventas ese dia en VNH
	LEFT JOIN
            (SELECT sum(Cantidad) as Ventas
             FROM Movimientos m
			 JOIN Tickets t on t.Id_Ticket = m.Id_Ticket
             WHERE t.Fecha = CURDATE() AND m.Id_Article = intArticle AND t.warehouse_id = 7) v on true
		GROUP BY land.Id_Article;
	CALL buy_tarifas(LAST_INSERT_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 `traslado_ticket` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `traslado_ticket`(IN i_entrada INTEGER, IN i_ticket INTEGER)
BEGIN

	DECLARE intWarehouse INT;
	DECLARE datTicket DATE;

	SELECT warehouse_id, Fecha INTO intWarehouse,datTicket FROM Tickets WHERE Id_Ticket = i_ticket;

	CALL buy_tarifas_table(i_entrada); 
  
	CALL item_last_buy_(intWarehouse,datTicket);


	INSERT INTO Compres( Id_Article,
                       Cantidad,
                       Novincular,
                       Id_Entrada,
                       Id_Cubo,
                       Packing,
                       `grouping`,
                       caja,
                       Portefijo,
                       Comisionfija,
                       Embalajefijo,
                       Costefijo,
                       Productor,
                       Tarifa2,
                       Tarifa3
                       )

	SELECT   M.Id_Article,
			 IF(T.Id_Cliente IN (1625, 1118, 400), -1, 1) * M.Cantidad,
			 
			 IF(T.Id_Cliente IN (1625, 1118, 400), TRUE, FALSE),
			 i_entrada,
			 IFNULL(C.Id_Cubo,'--'),
			 C.Packing,
			 C.`grouping`,  
			 C.caja,
			@pf := ROUND(@cm3:=cm3_2(IFNULL(C.Id_Cubo,'--'), b.item_id) * AG.m3 / 1000000 /   C.Packing ,3) AS Porte,
			@cf := IFNULL(ROUND(C.Costefijo * E.comision / 100 ,3),0) AS Comision,
			@ef := ROUND(IF(CB.Retornable = FALSE,CB.Valor/ C.Packing,0) ,3) AS Embalaje,
			@cost := ROUND(IFNULL(C.Costefijo,0) + @cf + @ef + @pf,3),
			C.Productor,
			@t3 :=  ROUND(@cost / ((100 - TC.t3)/100),2) Tarifa3,
			@t2 :=  IF(@cost / ((100 - TC.t2)/100) <= @t3,@t3+0.01,@cost / ((100 - TC.t2)/100)) Tarifa2

	  FROM Movimientos M
		LEFT JOIN Tickets T USING(Id_Ticket)
        LEFT JOIN t_item_last_buy b ON M.Id_Article = b.item_id AND T.warehouse_id = b.warehouse_id
		LEFT JOIN Compres C ON C.Id_Compra = b.buy_id
		LEFT JOIN Cubos CB ON CB.Id_Cubo = C.Id_Cubo
		LEFT JOIN Entradas E ON E.Id_Entrada = i_entrada
		LEFT JOIN travel TR ON TR.id = E.travel_id
		LEFT JOIN Agencias AG ON AG.Id_Agencia = TR.agency_id
		LEFT JOIN Proveedores P ON P.Id_Proveedor = E.Id_Proveedor
		JOIN tblTARIFAS TC
		LEFT JOIN tblContadores ON TRUE
		JOIN (SELECT m3 as ZEL_PORT FROM Agencias WHERE Id_Agencia = 618) Z
    WHERE M.Id_Ticket = i_ticket;
    

    DROP TEMPORARY TABLE t_item_last_buy;

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

	DECLARE vDateFrom DATE DEFAULT TIMESTAMPADD(WEEK,-12,CURDATE());

	SELECT * FROM
		(
		SELECT 
				1 as IsTravel, 
				tr.id as travel, 
				NULL as Entrada, 
				ag.Agencia, 
				tr.ref, 
				tr.shipment, 
				wo.name as OrigenCajas, 
				tr.landing, 
				w.name as Destino, 
				sum(c.Etiquetas) as Etiquetas,
				NULL as Notas_Eva,
				kg,
				cast(sum(a.density * c.Etiquetas * IF(cb.Volumen, cb.Volumen, cb.X * cb.Y * cb.Z) / 1000000  ) as DECIMAL(10,0)) as loadedKg,
				cast(sum(167.5 * c.Etiquetas * IF(cb.Volumen, cb.Volumen, cb.X * cb.Y * cb.Z) / 1000000  ) as DECIMAL(10,0)) as volumeKg,
				NULL as loadPriority,
				NULL as Notas,
				pc.Alias as Carguera
			FROM travel tr
				LEFT JOIN Proveedores pc ON pc.Id_Proveedor = tr.cargoSupplierFk
				LEFT JOIN Entradas e ON e.travel_id = tr.id
				LEFT JOIN Compres c ON c.Id_Entrada = e.Id_Entrada
				LEFT JOIN Cubos cb ON cb.Id_Cubo = c.Id_Cubo
				LEFT JOIN Articles a ON a.Id_Article = c.Id_Article
				LEFT JOIN Tipos tp ON tp.tipo_id = a.tipo_id
				JOIN warehouse w ON w.id = tr.warehouse_id
				JOIN warehouse wo ON wo.id = tr.warehouse_id_out
				JOIN Agencias ag ON ag.Id_Agencia = tr.agency_id
			WHERE tr.landing >= vDateFrom AND (wo.name="Colombia" OR  wo.name="Ecuador")
			GROUP BY tr.id

		UNION ALL

		SELECT 
				0 as IsTravel, 
				e.travel_id as travel, 
				e.Id_Entrada, 
				p.Proveedor, 
				e.Referencia, 
				tr.shipment, 
				wo.name as OrigenCajas,
				tr.landing,   
				w.name as Destino, 
				sum(Etiquetas) as Etiquetas,
				e.Notas_Eva,
				NULL as kg,
				cast(sum(a.density * c.Etiquetas * IF(cb.Volumen, cb.Volumen, cb.X * cb.Y * cb.Z) / 1000000  ) as DECIMAL(10,0)) as loadedkg,
				   cast(sum(167.5 * c.Etiquetas * IF(cb.Volumen, cb.Volumen, cb.X * cb.Y * cb.Z) / 1000000  ) as DECIMAL(10,0)) as volumeKg,
				loadPriority,
				e.Notas,
				pc.Alias as carguera
				
			FROM Entradas e
				JOIN Compres c ON c.Id_Entrada = e.Id_Entrada
				JOIN Cubos cb ON cb.Id_Cubo = c.Id_Cubo
				JOIN Articles a ON a.Id_Article = c.Id_Article
				JOIN Tipos tp ON tp.tipo_id = a.tipo_id
				JOIN Proveedores p ON p.Id_Proveedor = e.Id_Proveedor
				JOIN travel tr ON tr.id = e.travel_id
				LEFT JOIN Proveedores pc ON pc.Id_Proveedor = tr.cargoSupplierFk
				JOIN warehouse w ON w.id = tr.warehouse_id
				JOIN warehouse wo ON wo.id = tr.warehouse_id_out
			WHERE tr.landing >= vDateFrom  AND (wo.name="Colombia" OR  wo.name="Ecuador")
			GROUP BY e.Id_Entrada
		) sub
	ORDER BY shipment, landing, travel, IsTravel DESC, (loadPriority > 0) DESC,loadPriority, Agencia, Notas_Eva ;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travel_tree_shipment` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `travel_tree_shipment`(v_date DATE, v_consigna INT, v_agency INT, v_warehouse INT)
BEGIN
/**
* DEPRECATED usar vn.agencyHourGetLanded
* 
 * Devuelve una tabla temporal con el dia de recepcion para v_date.
 *
 * @param v_date Fecha de preparacion de mercancia
 * @param v_consigna Id de consignatario, %NULL para recogida
 * @param v_agency Id agencia
 * @table travel_tree_shipment Datos de recepción
 */
	DROP TEMPORARY TABLE IF EXISTS travel_tree_shipment;
	CREATE TEMPORARY TABLE travel_tree_shipment
	ENGINE = MEMORY
		SELECT v_warehouse warehouse_id, v_envio landing FROM (
			SELECT * FROM (
				SELECT v_warehouse, TIMESTAMPADD(DAY, subtract_day, v_date) v_envio, subtract_day, ah.max_hour
					FROM agency_hour ah
					LEFT JOIN Consignatarios c ON c.Id_Consigna = v_consigna
						WHERE (week_day = weekday(TIMESTAMPADD(DAY, subtract_day, v_date)) OR week_day IS NULL) 
							AND (ah.agency_id = v_agency OR ah.agency_id IS NULL)
							AND ah.warehouse_id = v_warehouse
							AND (ah.province_id = c.province_id OR ah.province_id IS NULL OR v_consigna IS NULL)
							ORDER BY (
							(ah.week_day IS NOT NULL) +
							(ah.agency_id IS NOT NULL) +
                            (- ah.subtract_day) +
							((ah.province_id IS NOT NULL)*3)
						) DESC
			) t
			LIMIT 1
		) t
		WHERE IF(v_date = CURDATE(), max_hour > HOUR(NOW()), TRUE) AND subtract_day < 225;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `turnoClon` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `turnoClon`(IN vWeek INT, IN vYear INT)
BEGIN

DECLARE done BIT DEFAULT 0;
DECLARE myEntrada INT;
DECLARE myWeekday INT;
DECLARE myLanding DATE;
DECLARE myShipment DATE;
DECLARE myDateDiff INT;
DECLARE myTravel INT;
DECLARE myNuevaEntrada INT;
DECLARE myWH_IN INT;
DECLARE myWH_OUT INT;

DECLARE rs CURSOR FOR
SELECT Id_Entrada, weekDay FROM Entradas_turno;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

IF vWeek = 0 THEN 

	SET vWeek = WEEK(TIMESTAMPADD(WEEK,1,CURDATE()));
    SET vYear = YEAR(TIMESTAMPADD(WEEK,1,CURDATE()));

END IF;


OPEN rs;

FETCH rs INTO myEntrada, myWeekday;

WHILE NOT done DO

	SELECT DATEDIFF(landing,shipment), warehouse_id, warehouse_id_out INTO myDateDiff, myWH_IN, myWH_OUT
    FROM travel t
    JOIN Entradas e on e.travel_id = t.id
    WHERE Id_Entrada = myEntrada;
																			
	SELECT date, TIMESTAMPADD(DAY, - myDateDiff, date)
	INTO myLanding , myShipment 
    FROM time
	WHERE year = vYear AND week = vWeek
        AND WEEKDAY(date) = myWeekday;
																			        
	SELECT t.id INTO myTravel
    FROM travel t
    WHERE shipment = myShipment
    AND landing = myLanding
    AND warehouse_id = myWH_IN
    AND warehouse_id_out = myWH_OUT
    LIMIT 1;
																			    
    IF IFNULL(myTravel,0) = 0 THEN

		INSERT INTO travel(shipment, shipment_hour, landing,landing_hour, warehouse_id, warehouse_id_out,agency_id, ref)
		SELECT myShipment, shipment_hour, myLanding ,landing_hour, warehouse_id, warehouse_id_out,agency_id, ref
		FROM travel t
		JOIN Entradas e on e.travel_id = t.id
		WHERE Id_Entrada = myEntrada;
		
		SELECT LAST_INSERT_ID() INTO myTravel;
        																			
    
    END IF;

	INSERT INTO Entradas(Id_Proveedor,Referencia, Notas, Id_Moneda, empresa_id, travel_id)
    SELECT Id_Proveedor, Referencia, Notas, Id_Moneda, empresa_id, myTravel
    FROM Entradas 
    WHERE Id_Entrada = myEntrada;
    
	SELECT LAST_INSERT_ID() INTO myNuevaEntrada;
 																			
	INSERT INTO Compres(Id_Entrada, Id_Article, Cantidad, Costefijo, Portefijo, Embalajefijo, Novincular, Comisionfija, Etiquetas, Packing
						,`grouping`, caja, /*container_id, */ Nicho, Id_Cubo, Tarifa1,Tarifa2,Tarifa3, PVP, Productor)
	SELECT myNuevaEntrada, Id_Article, Cantidad, Costefijo, Portefijo, Embalajefijo, Novincular, Comisionfija, Etiquetas, Packing
						,`grouping`, caja,/* container_id, */ Nicho, Id_Cubo, Tarifa1,Tarifa2,Tarifa3, PVP, Productor
	FROM Compres 
    WHERE Id_Entrada = myEntrada;
   
   
    FETCH rs INTO myEntrada, myWeekday;
    
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 `turn_calculartiempomedio` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `turn_calculartiempomedio`()
BEGIN

DECLARE strTiempoAprox NVARCHAR(255);

SELECT 
CASE WHEN @min>45 THEN concat(@hora:=@hora+1,' horas ') 
WHEN @hora >0 THEN concat(@hora,' horas ') 
WHEN @min>=0 and @min<15 THEN '15 Minutos'  
WHEN @min<30 THEN '30 Minutos' 
WHEN @min<45 THEN '45 Minutos' 
ELSE '' and @hora=@hora+1 END AS tiempoaprox
INTO strTiempoAprox
FROM (
    select min(sub1.adate) as adate,max(sub1.bdate) as bdate,
    @hora:=ROUND((TIMESTAMPDIFF(HOUR,min(sub1.adate),max(sub1.bdate)) /10),0),
    @min:=ROUND((TIMESTAMPDIFF(MINUTE,min(sub1.adate),max(sub1.bdate)) mod 60)/10,0)
    from (
        select a.odbc_date as adate,b.odbc_date as bdate
        from turn a
        INNER JOIN turn b on a.number=(b.number-1)
        WHERE TIMESTAMPDIFF(HOUR,b.odbc_date,a.odbc_date)<1
        ORDER BY a.odbc_date DESC,b.odbc_date DESC
        LIMIT 10) sub1) sub2;

SELECT strTiempoAprox as TiempoAprox;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ubicator` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ubicator`(IN i_wh TINYINT, IN d_fecha DATE,IN filtro VARCHAR(255))
BEGIN


	DECLARE date_inv DATE;


DROP TEMPORARY TABLE IF EXISTS stock_actual;
DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_ubicator_stock;


SELECT FechaInventario INTO date_inv
		FROM tblContadores LIMIT 1;


CREATE TEMPORARY TABLE stock_actual
SELECT Id_Article article_id,SUM(Cantidad) amount FROM (
	SELECT 	Id_Article,Cantidad 
		FROM Compres c 
		JOIN Entradas e USING(Id_Entrada)
		JOIN travel t ON t.id = e.travel_id
		WHERE landing BETWEEN date_inv AND d_fecha
		AND warehouse_id = i_wh AND NOT Redada
		
	UNION ALL

	-- JGF Error cuando se pedia para una fecha futura 30/06/14
	/*SELECT Id_Article,-Cantidad
		FROM Compres c 
		JOIN Entradas e USING(Id_Entrada)
		JOIN travel t ON t.id = e.travel_id
		WHERE shipment BETWEEN date_inv AND timestampadd(DAY,-1,d_fecha)
		AND warehouse_id_out = i_wh AND NOT Redada*/
	SELECT Id_Article,-Cantidad
		FROM Compres c 
		JOIN Entradas e USING(Id_Entrada)
		JOIN travel t ON t.id = e.travel_id
		WHERE shipment BETWEEN date_inv AND CURDATE()
		AND warehouse_id_out = i_wh AND NOT Redada AND delivered
	UNION ALL

	-- JGF Error cuando se pedia para una fecha futura 30/06/14

	/*SELECT Id_Article, -Cantidad
		FROM Movimientos m
		JOIN Tickets t USING(Id_Ticket)
		WHERE Fecha BETWEEN date_inv AND timestampadd(DAY,-1,d_fecha)
		AND warehouse_id = i_wh */
	SELECT Id_Article, -Cantidad
		FROM Movimientos m
		JOIN Tickets t USING(Id_Ticket)
		WHERE Fecha BETWEEN date_inv AND CURDATE()
		AND warehouse_id = i_wh AND Etiquetasemitidas


) t GROUP BY article_id;

/*
SELECT * from stock_actual;*/

-- TEMPORARY
CALL util.exec (sql_printf('
            CREATE TEMPORARY TABLE IF NOT EXISTS vn2008.tmp_ubicator_stock AS
            SELECT  A.Id_Article,A.Article, T.Id_Cubo,IF(Z > 0,Z,0) as z,x,y,
               CEIL(S.Suma/T.packing) as etiquetas,A.Medida,A.Nicho
                FROM vn2008.Articles A
                INNER JOIN
                    (SELECT article_id, amount as SUMA 
                        FROM vn2008.stock_actual
                        WHERE amount > 0
                    ) as S ON S.article_id = A.Id_Article
                LEFT JOIN (
                    SELECT * FROM (
                        SELECT c.Id_Article item_id, c.Id_Compra id, c.Id_Cubo,c.packing
                        FROM vn2008.Compres c INNER JOIN vn2008.Entradas e USING(Id_Entrada)
                            INNER JOIN vn2008.travel t ON t.id = e.travel_id
                        WHERE t.landing BETWEEN vn2008.date_inv() AND %v
                            AND c.Novincular = FALSE
                            AND c.Tarifa2 >= 0 AND Id_Cubo IS NOT NULL
                        ORDER BY  1 = t.warehouse_id DESC, t.landing DESC
                    ) t1 GROUP BY item_id	
                ) as T ON T.item_id = A.Id_Article
                LEFT JOIN vn2008.Cubos C USING(Id_Cubo)
                WHERE %s AND CEIL(S.Suma/T.packing) > 0',d_fecha,filtro));
				

  
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ubicator_calcularhuecosvacios` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `ubicator_calcularhuecosvacios`(int_H int,int_X int,int_Y int,int_Z int,intId_Estanterias int,intId_Baldas int,contId_Estanterias int)
BEGIN
DECLARE intnumcubostotal,intnumcubosocup SMALLINT DEFAULT 0;
DECLARE posX,posY,posZ,intId_Article,x_cubo,y_cubo INT DEFAULT 0;
DECLARE strId_Cubo VARCHAR(10);
DECLARE strArticle,strmodelo VARCHAR(50) DEFAULT '---';
DECLARE intContador INT DEFAULT 1;

    SELECT COUNT(*) INTO intnumcubosocup FROM Ubicator_Cajas 
    WHERE W=int_X and D=int_Y and Id_Estanterias=intId_Estanterias and Id_Baldas=intId_Baldas and NumEstanterias=contId_Estanterias;
        
    SELECT W,D,H,Id_Cubo,Id_Article,modelo,Article,x,y
    INTO posX,posY,posZ,strId_Cubo,intId_Article,strmodelo,strArticle,x_cubo,y_cubo
    FROM Ubicator_Cajas
    WHERE W=int_X and D=int_Y and Id_Estanterias=intId_Estanterias and Id_Baldas=intId_Baldas and NumEstanterias=contId_Estanterias
    ORDER BY H DESC LIMIT 1;
    
   WHILE (int_Z*intContador<int_H) DO -- Numero de cubos que caben en altura.
        SET intnumcubostotal=intnumcubostotal+1,intContador=intContador+1;
   END WHILE;
   
    WHILE ((intnumcubostotal-intnumcubosocup)>0) DO 
        SET posZ=posZ+int_Z;
            -- INSERT INTO Ubicator_Cajas 
            -- (Id_Estanterias,NumEtiquetas,W ,D,H ,Id_Cubo ,Id_Article,POSX,POSY,POSZ,Id_Article_aux ,Id_Baldas,modelo,Article,Medida)
            -- VALUES (intId_Estanterias ,1,posX,posY,posZ,strId_Cubo ,intId_Article,0,0,0,0,intId_Baldas,strmodelo,'',int_Z);    
             INSERT INTO Ubicator_Cajas (Id_Estanterias,Id_Baldas,modelo,W ,D,H ,Id_Cubo,X,Y,Z,Medida,Id_Article,Article,numEstanterias) 
             VALUES (intId_Estanterias,intId_Baldas,strmodelo,posX,posY,posZ,strId_Cubo,x_cubo,y_cubo,int_Z,null,intId_Article,'',contId_Estanterias); 
        SET intnumcubosocup=intnumcubosocup+1;
    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 `ubicator_ordenacion` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ubicator_ordenacion`(date DATE,boolORDALFA TINYINT(1), intWAREHOUSE INT,strFILTRO NVARCHAR(255), boolESAPILABLE TINYINT(1),boolESABIERTO TINYINT(1),intCmNichoExtra SMALLINT,inEstanteria SMALLINT,strOrdenacion varchar(255))
BEGIN
-- Inicializo variables
-- boolESABIERTO --> permite apilar las cajas de diferentes articulos (cerrada) para aprovechar el espacio.
DECLARE intPOSX,intPOSY,intPOSZ,intSUMAH,intCMNICHO_EXTRA INT DEFAULT 0;
DECLARE intId_Estanterias,intW,intD,intId_Baldas,intH,intEtiquetas,
        intX,intY,intZ,ReturnX,ReturnY,ReturnZ,Cantidad,intId_Baldas_aux INT DEFAULT 0;
DECLARE strId_Cubo VARCHAR(10) DEFAULT '---';
DECLARE intId_Article,Id_Article_aux,alturabalda,intZ_aux INT DEFAULT 0;
DECLARE contId_Estanterias INT DEFAULT 1;
DECLARE strmodelo VARCHAR(255) DEFAULT '---';
DECLARE done BIT DEFAULT 0;
DECLARE strArticle VARCHAR(50);
DECLARE boolCabeCaja,boolPasarZ,boolPasarX,boolNoNextRecord,fin BOOLEAN DEFAULT FALSE;
DECLARE intMedida,intX_ant,intY_ant,IntZ_ant INT(10) DEFAULT 0;

-- ejemplo: call ubicator_ordenacion(CURDATE(),false,1,'tipo_id = 2',TRUE,FALSE,2,1)

-- Declaro el cursor para leer las estanterias y las baldas ordenadas por las baldas. (La primera es la de arriba).
DECLARE cursor_estanterias CURSOR FOR SELECT Id_Estanterias,w,d,modelo,Id_Baldas,h FROM Estanterias 
                            INNER JOIN Baldas USING (Id_Estanterias) WHERE Id_Estanterias=inEstanteria ORDER BY Id_Estanterias,Id_Baldas;

-- Declaro el cursor para leer el recorset de los cubos a colocar en las estanterias obteniendo las variables X,Y,Z del cubo. 
DECLARE cursor_ubicator CURSOR FOR SELECT Id_Cubo,Etiquetas,Id_Article,X,Y,Z,Article,Medida FROM ubicator_stock;
     -- Creo la tabla temporal donde devuelvo la ordenación de las cajas.

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; -- handler para el cursor de las estanterias y baldas

DROP TEMPORARY TABLE IF EXISTS Ubicator_Cajas;
/*
 CREATE TEMPORARY TABLE IF NOT EXISTS Ubicator_Cajas (Id_Estanterias INT,Id_Baldas SMALLINT,modelo varchar(255),
 W SMALLINT,D SMALLINT,H SMALLINT,Id_Cubo VARCHAR(10),X SMALLINT,Y SMALLINT,Z SMALLINT,Medida SMALLINT,Id_Article INT(11),Article varchar(50),NumEstanterias SMALLINT);
*/
  
   CREATE TEMPORARY TABLE IF NOT EXISTS Ubicator_Cajas(Id_Estanterias INT,Id_Baldas SMALLINT,modelo varchar(255),
   W SMALLINT,D SMALLINT,H SMALLINT,Id_Cubo VARCHAR(10),X SMALLINT,Y SMALLINT,Z SMALLINT,Medida SMALLINT,
   Id_Article INT(11),Article varchar(50),NumEstanterias SMALLINT,NumEtiquetas INT,POSX INT (11),POSY INT(11),
   POSZ INT(11),Id_Article_aux int(11));
  
-- Creo la tabla temporal donde voy a insertar las cajas que no caben en las estanterias.
DROP TEMPORARY TABLE IF EXISTS Ubicator_CajasNoCaben;
CREATE TEMPORARY TABLE IF NOT EXISTS Ubicator_CajasNoCaben (Id_Cubo VARCHAR(10),Id_Estanteria SMALLINT);

CALL ubicator (intWAREHOUSE,date,strFILTRO); -- Ejecuto el procedimiento de stock para recorrer los articulos con las cajas.
 
DROP TEMPORARY TABLE IF EXISTS ubicator_stock;

SET @SQL=CONCAT('CREATE TEMPORARY TABLE IF NOT EXISTS ubicator_stock SELECT Id_Cubo,Etiquetas,Id_Article,X,Y,IF(Z=0,Medida,Z) Z,Article,Medida,IF(LOWER(Article) like "%mix%",1,0) AS MIX FROM tmp_ubicator_stock 
    ORDER BY MIX,',strOrdenacion);

PREPARE stmt1 FROM @SQL;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

 -- IF (boolORDALFA) THEN
 --   CREATE TEMPORARY TABLE IF NOT EXISTS ubicator_stock SELECT Id_Cubo,Etiquetas,Id_Article,X,Y,IF(Z=0,Medida,Z) Z,Article,Medida FROM tmp_ubicator_stock 
 --   ORDER BY Article,Medida;
 -- ELSE
 --   CREATE TEMPORARY TABLE IF NOT EXISTS ubicator_stock SELECT Id_Cubo,Etiquetas,Id_Article,X,Y,IF(Z=0,Medida,Z) Z,Article,Medida FROM tmp_ubicator_stock 
 --    ORDER BY Id_Article;
 -- END IF;
 
-- Open Recordsets
OPEN cursor_estanterias;
OPEN cursor_ubicator; 

REPEAT
    FETCH cursor_estanterias INTO intId_Estanterias,intW,intD,strmodelo,intId_Baldas,intH;
    
    IF (done) THEN -- Si llega a la ultima balda, empieza de nuevo.
        CLOSE cursor_estanterias;
        SET done=FALSE;
        OPEN cursor_estanterias;
        SET contId_Estanterias=contId_Estanterias+1;
        FETCH cursor_estanterias INTO intId_Estanterias,intW,intD,strmodelo,intId_Baldas,intH;
    END IF;
    
    -- Obtengo la altura absoluta de la balda.
    SELECT CASE  WHEN (SUM(H)>=0) THEN SUM(H) ELSE 0 END As suma INTO intSUMAH 
    FROM Baldas WHERE Id_Estanterias=intId_Estanterias and Baldas.Id_Baldas>intId_Baldas;
    
    SELECT H INTO alturabalda
    FROM Baldas WHERE Id_Estanterias=intId_Estanterias and Baldas.Id_Baldas=intId_Baldas;
    
    SET intPOSX=0,intPOSY=0,intPOSZ=0,intId_Baldas_aux=0;
    
    ITERACION:WHILE NOT done DO
        IF (NOT boolNoNextRecord) THEN
            FETCH cursor_ubicator INTO strId_Cubo,intEtiquetas,intId_Article,intX,intY,intZ,strArticle,intMedida;
            IF (DONE) THEN
                LEAVE ITERACION;
            END IF;
            SELECT Id_Cubo,Etiquetas,Id_Article,X,Y,Z,Article,Medida FROM ubicator_stock ORDER BY Id_Article;
            SET Cantidad=0;
        END IF;
        -- SET Medida=intZ;
        -- 1. Compruebo que cabe la caja en la estanteria
    
         SELECT ubicator_cabecaja(intX,intY,intZ,intW,intD,intH) INTO boolCabeCaja;
          IF (NOT boolCabeCaja) THEN -- Compruebo si la caja cabe en la estanteria  sino la coloco en una tabla temporal.
            INSERT INTO Ubicator_CajasNoCaben (Id_Cubo,Id_Estanteria) VALUES (strId_Cubo,intId_Estanterias);
            SET Id_Article_aux=intId_Article,boolNoNextRecord=FALSE;
            ITERATE ITERACION;
        END IF;
   
        SET boolPasarX=FALSE,boolPasarZ=FALSE;
    -- Inicializo el contador
     REPEAT
        SET Cantidad=Cantidad+1;  -- Incremento el contador en 1
        IF (intId_Baldas_aux<>intId_Baldas) THEN 
            SET intId_Baldas_aux=intId_Baldas;
            SET intPOSX=0,intPOSY=0,intPOSZ=0;
        END IF;
        IF (boolESAPILABLE AND intPOSZ>0 AND intZ>0) THEN -- Es Apilable
               IF (boolESABIERTO) THEN  -- abierto  
                    -- SET intPOSX=intPOSX+intCmNichoExtra,intPOSZ=0,intPOSY=0,Id_Article_aux=intId_Article;
                    IF (intId_Article=Id_Article_aux) THEN -- mismo articulo
                        SET boolPasarX=FALSE,boolPasarZ=TRUE;
                        SET intPOSX=intPOSX-intX;
                    ELSE -- distinto articulo
                        SET boolPasarX=TRUE,boolPasarZ=TRUE;
                        SET intPOSY=intY,intPOSZ=intZ;
                        SET Id_Article_aux=intId_Article;
                         SET intPOSX=intPOSX+intCmNichoExtra; 
                    END IF;  
                ELSE -- cerrado
                    IF ((intZ=intZ_ant) AND (intY=intY_ant) AND (intX=intX_ant)) THEN -- tienen que ser del mismo tamaño
                        SET intPOSX=intPOSX-intX;
                        SET boolPasarX=FALSE,boolPasarZ=FALSE; 
                    ELSE
                        CALL ubicator_calcularhuecosvacios (alturabalda,ReturnX,ReturnY,intZ_aux,intId_Estanterias,intId_Baldas,contId_Estanterias); -- Calculo las cajas vacias
                        SET intPOSY=intY,intPOSZ=intZ;
                        SET boolPasarX=TRUE,boolPasarZ=TRUE;
                        SET intPOSX=intPOSX+intCmNichoExtra;
                    END IF; -- article
                 END IF;   
         ELSE -- No apilable or posz<>0
          IF (NOT boolESAPILABLE AND boolESABIERTO) THEN
				SET boolPasarX=FALSE,boolPasarZ=FALSE;
				-- @@@ cambio abierto no apilable
				SET intPOSZ=0; -- no se puede subir en altura
			    IF (intId_Article<>Id_Article_aux and Id_Article_aux<>0) THEN -- cambio @@@vicente, añado id_Article_aux<>0
					SET intPOSY=0;
				END IF;
          ELSE
               SET boolPasarX=TRUE,boolPasarZ=TRUE;
               SET intPOSY=intY,intPOSZ=intZ;
          END IF;
          
		-- @@@@ cambio
           IF (intPOSX>0) THEN -- SI ES EL PRIMER ELEMENTO (X=0) NO LE INCREMENTE LOS CM EXTRA DEL NICHO si la profundidad es menor no lo incrementa
                SET intPOSX=intPOSX+intCmNichoExtra;
           END IF;
        END IF; -- apilable
             
        Condicional:loop
        IF (NOT boolPasarX) THEN
          IF (NOT boolPasarZ) THEN
                IF (intD-intPOSY>intY) THEN -- cabe de profundo 
                   SET intPOSY=intPOSY+intY;
				  -- @@@@ULTIMO CAMBIO
				 IF (intPOSX>0) and (intId_Article=Id_Article_aux) THEN
				   IF (intPOSX-intX-intCmNichoExtra<0) THEN
						SET intPOSX=0,boolNoNextRecord=TRUE,Cantidad=Cantidad-1;
						LEAVE ITERACION;
					END IF;
						SET intPOSX=intPOSX-intX-intCmNichoExtra; -- cambio @@@vicente quito descomentando
				 END IF;
				-- @@@@ fin ultimo cambio
               ELSE
                   SET intPOSY=intY;
			   END IF;
           END IF; -- boolpasarz (depth)
          
            IF (intH-intPOSZ>intZ) THEN
				SET intPOSZ=intPOSZ+intZ;
            ELSE
              IF (intD-intPOSY>intY) THEN
                 SET boolPasarZ=FALSE,boolPasarX=FALSE,intPOSZ=intZ;
                 ITERATE Condicional;
              END IF;
              SET intPOSZ=intZ;
			  SET intPOSY=intY;
			  SET intPOSX=intPOSX+intX+intCmNichoExtra;
			END IF;
          END IF; -- boolpasarx
                         
            IF (intW-intPOSX>intX) THEN
				SET intPOSX=intPOSX+intX;
            ELSE
                SET intPOSX=0,boolNoNextRecord=TRUE,Cantidad=Cantidad-1;
                LEAVE ITERACION; 
            END IF;
            LEAVE Condicional;
        END loop Condicional;
       
        SET ReturnX=intPOSX-intX;           -- Anchura absoluta x del artículo
        SET ReturnZ=intSUMAH+intPOSZ-intZ;  -- Altura absoluta del cubo
        SET ReturnY=intPOSY-intY;           -- Profundidad absoluta del artículo

        SET boolPasarZ=FALSE,boolPasarX=FALSE;
        
		/*
        INSERT INTO Ubicator_Cajas (Id_Estanterias,Id_Baldas,modelo,W ,D,H ,Id_Cubo,X,Y,Z,Medida,Id_Article,Article,NumEstanterias) 
        VALUES (intId_Estanterias,intId_Baldas,strmodelo,ReturnX ,ReturnY,ReturnZ ,strId_Cubo,intX,intY,intZ,intMedida,intId_Article,strArticle,contId_Estanterias);
		*/
        
        INSERT INTO Ubicator_Cajas (Id_Estanterias,Id_Baldas,modelo,W ,D,H ,Id_Cubo,X,Y,Z,Medida,Id_Article,Article,NumEstanterias,
        NumEtiquetas,POSX,POSY,POSZ,Id_Article_aux)
           VALUES (intId_Estanterias,intId_Baldas,strmodelo,ReturnX ,ReturnY,ReturnZ ,strId_Cubo,intX,intY,intZ,intMedida,intId_Article,strArticle,contId_Estanterias,
        intEtiquetas,intPOSX,intPOSY,intPOSZ,Id_Article_aux);
        
        SET Id_Article_aux=intId_Article,intZ_aux=intZ,boolNoNextRecord=FALSE;
        -- Cambio
      SET intZ_ant=intZ,intY_ant=intY,intX_ant=intX;
      UNTIL Cantidad=intEtiquetas END REPEAT;
     END WHILE ITERACION;
     
     IF (done) THEN
        SET fin=TRUE;
     END IF;
UNTIL fin END REPEAT;
CLOSE cursor_ubicator;
CLOSE cursor_estanterias;

-- select * from Ubicator_Cajas;
-- select * from ubicator_stock;
-- select * from Ubicator_CajasNoCaben;


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ubicator_ordenacion_distrib` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ubicator_ordenacion_distrib`(date DATE,boolORDALFA TINYINT(1), intWAREHOUSE INT,strFILTRO NVARCHAR(255), boolESAPILABLE TINYINT(1),boolESABIERTO TINYINT(1),intCmNichoExtra SMALLINT,inEstant_distrib SMALLINT)
BEGIN
-- Inicializo variables
-- boolESABIERTO --> permite apilar las cajas de diferentes articulos (cerrada) para aprovechar el espacio.
DECLARE intPOSX,intPOSY,intPOSZ,intSUMAH,intCMNICHO_EXTRA INT DEFAULT 0;
DECLARE intId_Estanterias,intW,intD,intId_Baldas,intH,intEtiquetas,
        intX,intY,intZ,ReturnX,ReturnY,ReturnZ,Cantidad,intId_Baldas_aux INT DEFAULT 0;
DECLARE strId_Cubo VARCHAR(10) DEFAULT '---';
DECLARE intId_Article,Id_Article_aux,alturabalda,intZ_aux INT DEFAULT 0;
DECLARE contId_Estanterias INT DEFAULT 0;
DECLARE strmodelo VARCHAR(255) DEFAULT '---';
DECLARE done BIT DEFAULT 0;
DECLARE strArticle VARCHAR(50);
DECLARE boolCabeCaja,boolPasarZ,boolPasarX,boolNoNextRecord,fin BOOLEAN DEFAULT FALSE;
DECLARE intMedida,intX_ant,intY_ant,IntZ_ant ,intposinicial,intposfinal,auxintId_Estanterias,auxintposinicial,auxintposfinal,intnumdistrib,nestanterias INT(11) DEFAULT 0;

-- ejemplo: call ubicator_ordenacion(CURDATE(),false,1,'tipo_id = 2',TRUE,FALSE,2,1)

-- Declaro el cursor para leer las estanterias y las baldas ordenadas por las baldas. (La primera es la de arriba).
DECLARE cursor_estanterias CURSOR FOR SELECT Id_Estanterias,w,d,modelo,Id_Baldas,h,posinicial,posfinal FROM Estanterias 
                            INNER JOIN Baldas USING (Id_Estanterias) 
							INNER JOIN Estanterias_distri using (Id_Estanterias)
							WHERE IdEstanterias_distri=inEstant_distrib
							-- AND Id_Estanterias>nestanterias
							AND posinicial>auxintposinicial
							ORDER BY posinicial;

-- Declaro el cursor para leer el recorset de los cubos a colocar en las estanterias obteniendo las variables X,Y,Z del cubo. 
DECLARE cursor_ubicator CURSOR FOR SELECT Id_Cubo,Etiquetas,Id_Article,X,Y,Z,Article,Medida FROM ubicator_stock;
     -- Creo la tabla temporal donde devuelvo la ordenación de las cajas.

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; -- handler para el cursor de las estanterias y baldas

DROP TEMPORARY TABLE IF EXISTS Ubicator_Cajas;
CREATE TEMPORARY TABLE IF NOT EXISTS Ubicator_Cajas (Id_Estanterias INT,Id_Baldas SMALLINT,modelo varchar(255),
W SMALLINT,D SMALLINT,H SMALLINT,Id_Cubo VARCHAR(10),X SMALLINT,Y SMALLINT,Z SMALLINT,Medida SMALLINT,Id_Article INT(11),Article varchar(50),NumEstanterias SMALLINT);

  /*
   CREATE TEMPORARY TABLE IF NOT EXISTS Ubicator_Cajas(Id_Estanterias INT,Id_Baldas SMALLINT,modelo varchar(255),
   W SMALLINT,D SMALLINT,H SMALLINT,Id_Cubo VARCHAR(10),X SMALLINT,Y SMALLINT,Z SMALLINT,Medida SMALLINT,
   Id_Article INT(11),Article varchar(50),NumEstanterias SMALLINT,NumEtiquetas INT,POSX INT (11),POSY INT(11),
   POSZ INT(11),Id_Article_aux int(11));
   */
  
-- Creo la tabla temporal donde voy a insertar las cajas que no caben en las estanterias.
DROP TEMPORARY TABLE IF EXISTS Ubicator_CajasNoCaben;
CREATE TEMPORARY TABLE IF NOT EXISTS Ubicator_CajasNoCaben (Id_Cubo VARCHAR(10),Id_Estanteria SMALLINT);

CALL ubicator (intWAREHOUSE,date,strFILTRO); -- Ejecuto el procedimiento de stock para recorrer los articulos con las cajas.
 
DROP TEMPORARY TABLE IF EXISTS ubicator_stock;
IF (boolORDALFA) THEN
    CREATE TEMPORARY TABLE IF NOT EXISTS ubicator_stock SELECT Id_Cubo,Etiquetas,Id_Article,X,Y,Z,Article,Medida FROM tmp_ubicator_stock 
    ORDER BY Article,Medida;
ELSE
    CREATE TEMPORARY TABLE IF NOT EXISTS ubicator_stock SELECT Id_Cubo,Etiquetas,Id_Article,X,Y,Z,Article,Medida FROM tmp_ubicator_stock 
    ORDER BY Id_Article;
 END IF;
 
-- Open Recordsets
OPEN cursor_estanterias;
OPEN cursor_ubicator; 
SET contId_Estanterias=0;
REPEAT
    FETCH cursor_estanterias INTO intId_Estanterias,intW,intD,strmodelo,intId_Baldas,intH,intposinicial,intposfinal;
	
	IF (contId_Estanterias=0) THEN
		SET contId_Estanterias=1;
		SET auxintId_Estanterias=intId_Estanterias;
		SELECT (intposfinal-intposinicial+1)*Id_Baldas into auxintposfinal from Baldas where Id_Estanterias=intId_Estanterias order by Id_Baldas DESC limit 1;
	END IF;
    
   IF (done) THEN
		SELECT DISTINCT posinicial-1 INTO auxintposinicial
		FROM Estanterias_distri
		WHERE Id_Estanterias=auxintId_Estanterias;
        -- SET nestanterias=auxintId_Estanterias-1;
		
		CLOSE cursor_estanterias;
		OPEN cursor_estanterias;
        FETCH cursor_estanterias INTO intId_Estanterias,intW,intD,strmodelo,intId_Baldas,intH,intposinicial,intposfinal;
    END IF;

	IF (auxintId_Estanterias<>IFNULL(intId_Estanterias,auxintId_Estanterias)) THEN
		SET done=TRUE;
	END IF;
	SET intnumdistrib=intnumdistrib+1;

	 IF (done) THEN -- Si llega a la ultima balda, empieza de nuevo.
		IF (intnumdistrib<auxintposfinal) THEN
			CLOSE cursor_estanterias;
			OPEN cursor_estanterias;
			FETCH cursor_estanterias INTO intId_Estanterias,intW,intD,strmodelo,intId_Baldas,intH,intposinicial,intposfinal;
		ELSE
			SET intnumdistrib=1;
		END IF;
        SET done=FALSE;
        SET auxintId_Estanterias=intId_Estanterias;
        SET contId_Estanterias=contId_Estanterias+1;
	    SELECT (intposfinal-intposinicial+1)*Id_Baldas into auxintposfinal from Baldas where Id_Estanterias=intId_Estanterias order by Id_Baldas DESC limit 1;
    END IF;

    
    -- Obtengo la altura absoluta de la balda.
    SELECT CASE  WHEN (SUM(H)>=0) THEN SUM(H) ELSE 0 END As suma INTO intSUMAH 
    FROM Baldas WHERE Id_Estanterias=intId_Estanterias and Baldas.Id_Baldas>intId_Baldas;
    
    SELECT H INTO alturabalda
    FROM Baldas WHERE Id_Estanterias=intId_Estanterias and Baldas.Id_Baldas=intId_Baldas;
    
    SET intPOSX=0,intPOSY=0,intPOSZ=0,intId_Baldas_aux=0;
    
    ITERACION:WHILE NOT done DO
        IF (NOT boolNoNextRecord) THEN
            FETCH cursor_ubicator INTO strId_Cubo,intEtiquetas,intId_Article,intX,intY,intZ,strArticle,intMedida;
            IF (DONE) THEN
                LEAVE ITERACION;
            END IF;
            SELECT Id_Cubo,Etiquetas,Id_Article,X,Y,Z,Article,Medida FROM ubicator_stock ORDER BY Id_Article;
            SET Cantidad=0;
        END IF;
        -- SET Medida=intZ;
        -- 1. Compruebo que cabe la caja en la estanteria
    
         SELECT ubicator_cabecaja(intX,intY,intZ,intW,intD,intH) INTO boolCabeCaja;
          IF (NOT boolCabeCaja) THEN -- Compruebo si la caja cabe en la estanteria  sino la coloco en una tabla temporal.
            INSERT INTO Ubicator_CajasNoCaben (Id_Cubo,Id_Estanteria) VALUES (strId_Cubo,intId_Estanterias);
            SET Id_Article_aux=intId_Article,boolNoNextRecord=FALSE;
            ITERATE ITERACION;
        END IF;
   
        SET boolPasarX=FALSE,boolPasarZ=FALSE;
    -- Inicializo el contador
     REPEAT
        SET Cantidad=Cantidad+1;  -- Incremento el contador en 1
        IF (intId_Baldas_aux<>intId_Baldas) THEN 
            SET intId_Baldas_aux=intId_Baldas;
            SET intPOSX=0,intPOSY=0,intPOSZ=0;
        END IF;
        IF (boolESAPILABLE AND intPOSZ>0 AND intZ>0) THEN -- Es Apilable
               IF (boolESABIERTO) THEN  -- abierto  
                    -- SET intPOSX=intPOSX+intCmNichoExtra,intPOSZ=0,intPOSY=0,Id_Article_aux=intId_Article;
                    IF (intId_Article=Id_Article_aux) THEN -- mismo articulo
                        SET boolPasarX=FALSE,boolPasarZ=TRUE;
                        SET intPOSX=intPOSX-intX;
                    ELSE -- distinto articulo
                        SET boolPasarX=TRUE,boolPasarZ=TRUE;
                        SET intPOSY=intY,intPOSZ=intZ;
                        SET Id_Article_aux=intId_Article;
                        SET intPOSX=intPOSX+intCmNichoExtra;
                    END IF;  
                ELSE -- cerrado
                    IF ((intZ=intZ_ant) AND (intY=intY_ant) AND (intX=intX_ant)) THEN -- tienen que ser del mismo tamaño
                        SET intPOSX=intPOSX-intX;
                        SET boolPasarX=FALSE,boolPasarZ=FALSE; 
                    ELSE
                        CALL ubicator_calcularhuecosvacios (alturabalda,ReturnX,ReturnY,intZ_aux,intId_Estanterias,intId_Baldas,contId_Estanterias); -- Calculo las cajas vacias
                        SET intPOSY=intY,intPOSZ=intZ;
                        SET boolPasarX=TRUE,boolPasarZ=TRUE;
                        SET intPOSX=intPOSX+intCmNichoExtra;
                    END IF; -- article
                 END IF;   
         ELSE -- No apilable or posz<>0
          IF (NOT boolESAPILABLE AND boolESABIERTO) THEN
           SET boolPasarX=FALSE,boolPasarZ=FALSE;
            -- @@@ cambio abierto no apilable
		   SET intPOSZ=0; -- no se puede subir en altura
          ELSE
           SET boolPasarX=TRUE,boolPasarZ=TRUE;
           SET intPOSY=intY,intPOSZ=intZ;
          END IF;
          
           IF (intPOSX>0) THEN -- SI ES EL PRIMER ELEMENTO (X=0) NO LE INCREMENTE LOS CM EXTRA DEL NICHO
                SET intPOSX=intPOSX+intCmNichoExtra;
           END IF;
        END IF; -- apilable
             
        Condicional:loop
        IF (NOT boolPasarX) THEN
          IF (NOT boolPasarZ) THEN
                IF (intD-intPOSY>intY) THEN -- cabe de profundo 
                   SET intPOSY=intPOSY+intY;
               ELSE
                   SET intPOSY=intY;
                END IF;
           END IF; -- boolpasarz (depth)
          
            IF (intH-intPOSZ>intZ) THEN
              SET intPOSZ=intPOSZ+intZ;
            ELSE
              IF (intD-intPOSY>intY) THEN
                 SET boolPasarZ=FALSE,boolPasarX=FALSE,intPOSZ=intZ;
                 ITERATE Condicional;
              END IF;
              SET intPOSZ=intZ;
              SET intPOSY=intY, intPOSX=intPOSX+intX+intCmNichoExtra;
            END IF;
          END IF; -- boolpasarx
                         
            IF (intW-intPOSX>intX) THEN
              SET intPOSX=intPOSX+intX;
            ELSE
                SET intPOSX=0,boolNoNextRecord=TRUE,Cantidad=Cantidad-1;
                LEAVE ITERACION; 
            END IF;
            LEAVE Condicional;
        END loop Condicional;
       
        SET ReturnX=intPOSX-intX;           -- Anchura absoluta x del artículo
        SET ReturnZ=intSUMAH+intPOSZ-intZ;  -- Altura absoluta del cubo
        SET ReturnY=intPOSY-intY;           -- Profundidad absoluta del artículo

        SET boolPasarZ=FALSE,boolPasarX=FALSE;
            
        INSERT INTO Ubicator_Cajas (Id_Estanterias,Id_Baldas,modelo,W ,D,H ,Id_Cubo,X,Y,Z,Medida,Id_Article,Article,NumEstanterias) 
        VALUES (intId_Estanterias,intId_Baldas,strmodelo,ReturnX ,ReturnY,ReturnZ ,strId_Cubo,intX,intY,intZ,intMedida,intId_Article,strArticle,contId_Estanterias);
        /*
        INSERT INTO Ubicator_Cajas (Id_Estanterias,Id_Baldas,modelo,W ,D,H ,Id_Cubo,X,Y,Z,Medida,Id_Article,Article,NumEstanterias,
        NumEtiquetas,POSX,POSY,POSZ,Id_Article_aux)
           VALUES (intId_Estanterias,intId_Baldas,strmodelo,ReturnX ,ReturnY,ReturnZ ,strId_Cubo,intX,intY,intZ,intMedida,intId_Article,strArticle,contId_Estanterias,
        intEtiquetas,intPOSX,intPOSY,intPOSZ,Id_Article_aux);
        */
        SET Id_Article_aux=intId_Article,intZ_aux=intZ,boolNoNextRecord=FALSE;
        -- Cambio
      SET intZ_ant=intZ,intY_ant=intY,intX_ant=intX;
      UNTIL Cantidad=intEtiquetas END REPEAT;
     END WHILE ITERACION;
     
     IF (done) THEN
        SET fin=TRUE;
     END IF;

UNTIL fin END REPEAT;
CLOSE cursor_ubicator;
CLOSE cursor_estanterias;

-- select * from Ubicator_Cajas;
-- select * from ubicator_stock;
-- select * from Ubicator_CajasNoCaben;


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ubicator_test` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ubicator_test`(IN `i_wh` TINYINT, IN `d_fecha` DATE, IN `filtro` VARCHAR(255))
BEGIN


	DECLARE date_inv DATE;


DROP TEMPORARY TABLE IF EXISTS stock_actual;
DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_ubicator_stock;


SELECT FechaInventario INTO date_inv
		FROM tblContadores LIMIT 1;


CREATE TEMPORARY TABLE stock_actual
SELECT Id_Article article_id,SUM(Cantidad) amount FROM (
	SELECT 	Id_Article,Cantidad 
		FROM Compres c 
		JOIN Entradas e USING(Id_Entrada)
		JOIN travel t ON t.id = e.travel_id
		WHERE landing BETWEEN date_inv AND d_fecha
		AND warehouse_id = i_wh AND NOT Redada
		
	UNION ALL

	SELECT 	Id_Article,-Cantidad
		FROM Compres c 
		JOIN Entradas e USING(Id_Entrada)
		JOIN travel t ON t.id = e.travel_id
		WHERE shipment BETWEEN date_inv AND timestampadd(DAY,-1,d_fecha)
		AND warehouse_id_out = i_wh AND NOT Redada

	UNION ALL

	SELECT Id_Article, -Cantidad
		FROM Movimientos m
		JOIN Tickets t USING(Id_Ticket)
		WHERE Fecha BETWEEN date_inv AND timestampadd(DAY,-1,d_fecha)
		AND warehouse_id = i_wh 



) t GROUP BY article_id;

/*
SELECT * from stock_actual;*/

-- TEMPORARY
CALL util.exec (sql_printf('
            CREATE TEMPORARY TABLE IF NOT EXISTS vn2008.tmp_ubicator_stock AS
            SELECT  A.Id_Article,A.Article, T.Id_Cubo,IF(Z > 0,Z,0) as z,x,y,
               CEIL(S.Suma/T.`grouping`) as etiquetas,A.Medida,A.Nicho
                FROM vn2008.Articles A
                INNER JOIN
                    (SELECT article_id, amount as SUMA 
                        FROM vn2008.stock_actual
                        WHERE amount > 0
                    ) as S ON S.article_id = A.Id_Article
                LEFT JOIN (
                    SELECT * FROM (
                        SELECT c.Id_Article item_id, c.Id_Compra id, c.Id_Cubo,c.`grouping`
                        FROM vn2008.Compres c INNER JOIN vn2008.Entradas e USING(Id_Entrada)
                            INNER JOIN vn2008.travel t ON t.id = e.travel_id
                        WHERE t.landing BETWEEN vn2008.date_inv() AND CURDATE()
                            AND c.Novincular = FALSE
                            AND c.Tarifa2 >= 0 AND Id_Cubo IS NOT NULL
                        ORDER BY  1 = t.warehouse_id DESC, t.landing DESC
                    ) t1 GROUP BY item_id	
                ) as T ON T.item_id = A.Id_Article
                LEFT JOIN vn2008.Cubos C USING(Id_Cubo)
                WHERE %s AND CEIL(S.Suma/T.`grouping`) > 0',filtro));
				

  
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `unary_delete` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `unary_delete`(v_node INT, v_delete bool)
BEGIN
/**
 * Borra un nodo. Se puede indicar si se quieren mantener los hijos.
 * En este caso los hijos pasan al padre del nodo.
 * Si no tiene padre, los hijos pasaran a ser padres.
 * 
 * @v_node: Nodo que se quiere borrar.
 * @v_delete: Se indica si se borran los nodos.
 **/
 
	DECLARE v_parent INT;
    
    SELECT parent
    INTO v_parent
    FROM unary 
    WHERE id = v_node;
    
    IF(v_delete = FALSE) THEN
		UPDATE unary
		SET parent = v_parent
		WHERE parent = v_node;
	END IF;
        
    DELETE FROM unary
    WHERE id = v_node;
 
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `unary_insert` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `unary_insert`(OUT v_unary INT, v_parent INT)
BEGIN
	
    /**
	 * Inserta un nuevo nodo. Se puede indicar el padre.
	 * 
	 * @v_parent: Nodo padre.
	 * @v_unary: Id del nuevo nodo.
	 **/

	INSERT INTO unary(parent) VALUES(v_parent);
    
    SELECT last_insert_id() INTO v_unary;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `unary_leaves` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `unary_leaves`(v_top INT)
BEGIN
/**
 * A partir de un nodo devuelve todos sus descendientes.
 *
 * @table tmp.tree Tabla con los ids de los nodos descendientes;
 **/
	DECLARE v_count INT;
    DECLARE v_parent INT;
    DECLARE v_depth INT DEFAULT 0;
    
    DROP TEMPORARY TABLE IF EXISTS tmp.tree;
    CREATE TEMPORARY TABLE tmp.tree
		(INDEX (id))
        ENGINE = MEMORY
		SELECT v_top id, v_parent parent, v_depth depth;
        
	DROP TEMPORARY TABLE IF EXISTS tmp.parent;
    CREATE TEMPORARY TABLE tmp.parent
        ENGINE = MEMORY
		SELECT v_top id;

	l: LOOP
		
        SET v_depth = v_depth + 1;
		
		DROP TEMPORARY TABLE IF EXISTS tmp.child;
		CREATE TEMPORARY TABLE tmp.child
			ENGINE = MEMORY
			SELECT c.`id`, c.parent
				FROM `unary` c
                JOIN tmp.parent p ON c.`parent` = p.id;
                
		DROP TEMPORARY TABLE tmp.parent;
        CREATE TEMPORARY TABLE tmp.parent
			ENGINE = MEMORY
			SELECT c.id, c.parent
				FROM tmp.child c
                LEFT JOIN tmp.tree t ON t.id = c.id
					WHERE t.id IS NULL;
                    
		INSERT INTO tmp.tree
			SELECT id, parent, v_depth FROM tmp.parent;
            
		SELECT COUNT(*) INTO v_count
			FROM tmp.parent;
            
		IF v_count = 0 THEN
			LEAVE l;
		END IF;    
    END LOOP;
    
    DROP TEMPORARY TABLE
		tmp.parent,
        tmp.child;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `unary_scan_ident` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `unary_scan_ident`(v_top INT, v_space INT)
BEGIN
/**
 * A partir de un nodo devuelve el id y el nombre del nodod y sus hijos. 
 * El nombre viene identado segun el numero de espacios multiplicado por la profundiad del nodo.
 *
 * v_top: Id del nodo padre.
 * v_space: Spacios a dejar al identar,
 * @table tmp.tree_ident Tabla con los ids de los nodos descendientes y su nombre identado;
 **/
	
    DROP TEMPORARY TABLE IF EXISTS tmp.tree_ident;
    CALL tree_leaves(v_top);
    
    CREATE TEMPORARY TABLE tmp.tree_ident
        ENGINE = MEMORY
		SELECT t.id, 
        CONCAT( REPEAT(REPEAT(" ",v_space), t.depth), sp.name) AS name
        FROM tmp.tree t
        INNER JOIN unary_scan sp
        ON t.id = sp.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 `unary_scan_insert` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `unary_scan_insert`(v_name VARCHAR(45), v_parent INT, v_type VARCHAR(45))
BEGIN
	
    /**
	 * Inserta un nuevo nodo de tipo unary_scan. Se puede indicar el padre.
	 * 
	 * @v_name: Nombre del nodo.
     * @v_parent: Nodo padre.
	 * @v_type: Tipo del nodo a crear.
	 **/
    
    DECLARE v_unary INT;
    
    CALL unary_insert(v_unary, v_parent);
    
    INSERT INTO unary_scan(name, unary_id, type) VALUES(v_name, v_unary, v_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 `unary_tops` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `unary_tops`()
BEGIN
/**
 * Devuelve todos los nodos que no tienen padre.
 *
 * @table tmp.tree Tabla con los ids de los nodos que no tienen padre;
 **/
	
    DROP TEMPORARY TABLE IF EXISTS tmp.tree;
    CREATE TEMPORARY TABLE tmp.tree
        ENGINE = MEMORY
		SELECT s.`unary_id` AS id, s.name, s.odbc_date, s.type
				FROM `unary_scan` s
                INNER JOIN `unary` u ON s.unary_id = u.id
                WHERE u.parent 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 `unary_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 `unary_update`(v_node INT, v_new_parent INT, v_move bool)
BEGIN
/**
 * Cambia el padre de un nodo. Se puede indicar si se quieren mover los hijos.
 * En este caso los hijos pasan al padre del nodo.
 * Si no tiene padre, los hijos pasaran a ser padres.
 * 
 * @v_node: Nodo que se quiere mover.
 * @v_new_parent: Padre al que se quiere mover el nodo.
 * @v_move: Se indica si se mueven los nodos.
 **/
 
	DECLARE v_parent INT;
    
    SELECT parent
    INTO v_parent
    FROM unary 
    WHERE id = v_node;
    
    IF(v_move = TRUE) THEN
		UPDATE unary
		SET parent = v_parent
		WHERE parent = v_node;
	END IF;
        
    UPDATE unary
    SET parent = v_new_parent
    WHERE id = v_node;
 
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `valor_faltas` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!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 `valor_faltas`(IN intReino_id INT,IN dateDesde DATE,IN dateHasta DATE,IN wh INT)
BEGIN

	DROP TEMPORARY TABLE IF EXISTS item;

	CREATE TEMPORARY TABLE item
		SELECT Id_Article id,Id_Movimiento,Cantidad,Id_Tipo,Fecha
			FROM  Tickets t
				JOIN Movimientos m USING (Id_Ticket)
				JOIN Articles a USING (Id_Article)
				JOIN Tipos tip USING (tipo_id)
			WHERE
				Id_Cliente = 400
				AND Fecha BETWEEN dateDesde AND dateHasta
				AND reino_id = 4;

	CREATE INDEX pk USING HASH ON item (id);
	
	CALL item_buy		(wh, dateHasta);
	CALL item_buy_price	(1240,dateDesde,wh);

SELECT *,Cantidad * price as total FROM item; 

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

    DECLARE vLastInventoryDate DATE;

    SELECT landing INTO vLastInventoryDate
		FROM travel TR
			INNER JOIN Entradas E ON E.travel_id = TR.id
		WHERE landing <= vDate
			AND E.Id_Proveedor = 4
		ORDER BY landing DESC
		LIMIT 1;

	DROP TEMPORARY TABLE IF EXISTS inv;

	CREATE TEMPORARY TABLE inv 
		(warehouseFk SMALLINT,
		 itemFk BIGINT,
		 amount INT,	
		 cost DOUBLE DEFAULT 0,
		 total DOUBLE DEFAULT 0) 
	ENGINE = MEMORY;

	ALTER TABLE inv ADD PRIMARY KEY USING HASH (warehouseFk, itemFk);
	
    -- Valor del inventario
	INSERT INTO inv(warehouseFk, itemFk, amount)
		SELECT TR.warehouse_id, C.Id_Article, C.Cantidad
		FROM Compres C
			JOIN Articles A USING(Id_Article)
			JOIN Entradas E USING (Id_Entrada)
			JOIN travel TR ON TR.id = E.travel_id
			JOIN Tipos t USING(tipo_id)
			JOIN warehouse w ON w.id = TR.warehouse_id
		WHERE landing = vLastInventoryDate
			AND E.Id_Proveedor = 4
			AND reino_id NOT IN (7)
		ON DUPLICATE KEY UPDATE inv.amount = inv.amount + C.Cantidad;
    
    -- Añadimos compras
	INSERT INTO inv(warehouseFk, itemFk, amount)
	SELECT TR.warehouse_id, C.Id_Article, C.Cantidad
	FROM Compres C
	INNER JOIN Articles A USING(Id_Article)
	INNER JOIN Entradas E USING (Id_Entrada)
	INNER JOIN travel TR ON TR.id = E.travel_id
	INNER JOIN Tipos t USING(tipo_id)
	INNER JOIN warehouse w ON w.id = TR.warehouse_id
	WHERE landing BETWEEN vLastInventoryDate AND vDate
	AND NOT redada
	AND NOT w.fuente
	AND reino_id NOT IN (7)
	AND t.inventory
    AND E.Id_Proveedor <> 4
	ON DUPLICATE KEY UPDATE inv.amount = inv.amount + C.Cantidad;

	-- Restamos salidas
	INSERT INTO inv(warehouseFk, itemFk, amount)
	SELECT TR.warehouse_id_out, C.Id_Article, - C.Cantidad 
	FROM Compres C
	INNER JOIN Articles A USING(Id_Article)
	INNER JOIN Entradas E USING (Id_Entrada)
	INNER JOIN travel TR ON TR.id = E.travel_id
	INNER JOIN Tipos t USING(tipo_id)
	INNER JOIN warehouse w ON w.id = warehouse_id_out
	WHERE shipment BETWEEN vLastInventoryDate AND vDate
	AND NOT redada
	AND NOT w.fuente
	AND reino_id NOT IN (7)
	AND t.inventory
	ON DUPLICATE KEY UPDATE  inv.amount = inv.amount - C.Cantidad;
			
    -- Restamos ventas       
	INSERT INTO inv(warehouseFk, itemFk, amount)
	SELECT w.id, M.Id_Article, - M.Cantidad 
	FROM Movimientos M
	INNER JOIN Tickets T USING (Id_Ticket)
	INNER JOIN Clientes C USING(Id_Cliente)
	INNER JOIN Articles A USING(Id_Article)
	INNER JOIN Tipos t USING(tipo_id)
	INNER JOIN warehouse w ON w.id = warehouse_id
	WHERE T.Fecha BETWEEN vLastInventoryDate AND TIMESTAMPADD(DAY, -1 ,vDate)
	AND NOT w.fuente
	AND reino_id NOT IN (7)
	AND t.inventory
	ON DUPLICATE KEY UPDATE  inv.amount = inv.amount - M.Cantidad;

	-- Restamos el dia de hoy
	INSERT INTO inv(warehouseFk, itemFk, amount)
	SELECT w.id, M.Id_Article, - M.Cantidad  
	FROM Movimientos M
	INNER JOIN Tickets T USING (Id_Ticket)
	INNER JOIN Clientes C USING(Id_Cliente)
	INNER JOIN Articles A USING(Id_Article)
	INNER JOIN Tipos t USING(tipo_id)
	INNER JOIN warehouse w ON w.id = warehouse_id
	WHERE date(T.Fecha) = vDate
	AND  (vDate <> CURDATE()  or (M.OK <> 0 or T.Etiquetasemitidas <> 0 ))
	AND NOT w.fuente
	AND reino_id NOT IN (7)
	AND t.inventory
	ON DUPLICATE KEY UPDATE  inv.amount = inv.amount - M.Cantidad ;

	CALL item_last_buy_from_interval(NULL,vLastInventoryDate,vDate);
    
	UPDATE inv 
			JOIN tmp.item_last_buy_from_interval lb 
				ON inv.warehouseFk = lb.warehouse_id AND inv.itemFk = lb.item_id
			JOIN Compres C ON C.Id_Compra = lb.buy_id
		SET total = inv.amount * (ifnull(C.Costefijo,0) + IFNULL(C.Embalajefijo,0) + IFNULL(C.Portefijo,0) + IFNULL(C.Comisionfija,0)),
			cost = ifnull(C.Costefijo,0) + IFNULL(C.Embalajefijo,0) + IFNULL(C.Portefijo,0) + IFNULL(C.Comisionfija,0)
		WHERE inv.amount <> 0;

	DELETE FROM inv WHERE amount IS NULL or amount = 0;

	IF vIsItemised THEN

		SELECT inv.warehouseFk, a.Id_Article, a.Article, a.Medida, inv.amount, tp.Id_Tipo,
			tp.reino_id, inv.cost, cast(inv.total as decimal(10,2)) total, an.nicho
		FROM inv 
			JOIN warehouse w on w.id = inv.warehouseFk
			JOIN Articles a ON a.Id_Article = inv.itemFk
			JOIN Tipos tp ON tp.tipo_id = a.tipo_id
			JOIN Articles_nicho an ON an.Id_Article = a.Id_Article AND an.warehouse_id = w.id
		where w.valuatedInventory
		and inv.total > 0
		order by inv.total desc;

	ELSE

		SELECT w.name as Almacen, r.reino as Reino, cast(inv.total as decimal) as Euros
			FROM inv
				JOIN warehouse w ON w.id = inv.warehouseFk
				JOIN Articles A ON A.Id_Article = inv.itemFk
				JOIN Tipos t ON t.tipo_id = A.tipo_id
				JOIN reinos r ON r.id = t.reino_id
			WHERE w.valuatedInventory;

	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 `vips_in_a_week` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `vips_in_a_week`(vCondition VARCHAR(512))
BEGIN
	CALL util.exec (CONCAT(
		'SELECT C.Id_Cliente, C.Cliente, ROUND(SUM((M.Cantidad * M.Preu) * 100 - M.Descuento) / 100, 2) as Importe
			FROM vn2008.Clientes C 
				JOIN vn2008.Tickets T ON T.Id_Cliente = C.Id_Cliente
				JOIN vn2008.Movimientos M ON M.Id_Ticket = T.Id_Ticket
				JOIN vn2008.Articles A ON A.Id_Article = M.Id_Article
				JOIN vn2008.Tipos TP ON A.tipo_id = TP.tipo_id
				JOIN vn2008.Trabajadores TR ON TR.Id_Trabajador = TP.Id_Trabajador
			WHERE ', vCondition, ' 
			GROUP BY Id_Cliente
				HAVING Importe > 0
			ORDER BY Importe 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 `vips_in_a_week_by_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 ;;
CREATE DEFINER=`root`@`%` PROCEDURE `vips_in_a_week_by_client`(vCondition VARCHAR(512))
BEGIN
	CALL util.exec (CONCAT(
		'SELECT M.Id_Article, A.Article, A.Medida, A.Color, A.Categoria,
				SUM(M.Cantidad) Cantidad, M.Preu, M.Descuento,
				RED(SUM(M.Cantidad) * M.Preu * (100 - M.Descuento) / 100) as Importe
			FROM vn2008.Clientes C
				JOIN vn2008.Tickets T ON T.Id_Cliente = C.Id_Cliente
				JOIN vn2008.Movimientos M ON M.Id_Ticket = T.Id_Ticket
				JOIN vn2008.Articles A ON A.Id_Article = M.Id_Article
				JOIN vn2008.Tipos TP ON A.tipo_id = TP.tipo_id
				JOIN vn2008.Trabajadores TR ON TR.Id_Trabajador = TP.Id_Trabajador
			WHERE ', vCondition, ' 
			GROUP BY M.Id_Article, A.Article, A.Medida, A.Color, A.Categoria, M.Preu, M.Descuento'
	));
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `volumetricoReparto_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 `volumetricoReparto_kk`( IN IdTicket INT(11), OUT atot DOUBLE )
BEGIN

	DECLARE ticket INT(11);

	DECLARE rutaid INT(11);

	DECLARE art INT(11);

	DECLARE ax, ay, az, atot double;

	DECLARE CUR1 CURSOR FOR SELECT a.Id_Article FROM vn2008.Movimientos m, vn2008.Articles a 
		WHERE m.Id_Ticket = IdTicket AND m.Id_Article = a.Id_Article ;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET @atot = 0;
	
    set @atot = 0;

    OPEN CUR1;

    REPEAT 
    
	FETCH CUR1 INTO art ;

	SELECT  x, y, z into ax,ay,az
	FROM vn2008.Cubos cu, vn2008.Compres co 
	WHERE cu.Id_Cubo = co.Id_Cubo AND Id_Compra =
	(SELECT max(Id_Compra) FROM  vn2008.Compres c
		WHERE c.Id_Article = @art);
		
	set @atot = @atot +((@ax * @ay * @az)* 1,10);

    UNTIL done END REPEAT;
	CLOSE CUR1;
	
	
	select 'hola  ',@atot;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `weekly_sales_new` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `weekly_sales_new`(v_wh SMALLINT, v_date_ini DATETIME, v_date_end DATETIME)
BEGIN
    IF v_date_end IS NULL THEN
        SET v_date_end = v_date_ini;
    END IF;

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

    CREATE TEMPORARY TABLE weekly_ticket
        (INDEX idx USING HASH (Id_Ticket))
        ENGINE = MEMORY
        SELECT Id_Ticket, to_weeks (DATE(Fecha)) week, warehouse_id
            FROM Tickets t
            JOIN warehouse w ON w.id = t.warehouse_id
                WHERE Fecha >= v_date_ini AND Fecha < v_date_end
                AND Id_Cliente NOT IN (400, 200)
                AND NOT w.fuente
                AND v_wh IN (t.warehouse_id, 0);

    CREATE TEMPORARY TABLE weekly_sales
        ENGINE = MEMORY
        SELECT week, warehouse_id, a.Id_Article item_id, SUM(Cantidad) AS amount, 
        SUM(Cantidad * Preu * (100 - Descuento) / 100) AS price
            FROM Movimientos m
            JOIN weekly_ticket t USING (Id_Ticket)
            JOIN Articles a USING (Id_Article)
            INNER JOIN Tipos USING (tipo_id)
                WHERE reino_id != 6				
                GROUP BY week, warehouse_id, item_id;

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

UPDATE XDiario
SET EURODEBE = ROUND(EURODEBE,2),
    EUROHABER = ROUND(EUROHABER,2)
WHERE NOT enlazado;


UPDATE XDiario XD 
INNER JOIN
(
SELECT XD.id, SUBCTA, Quadre FROM XDiario XD
INNER JOIN (
SELECT ASIEN, SUM(IFNULL(ROUND(Eurodebe,2),0))- SUM(IFNULL(ROUND(EUROHABER,2),0)) as Quadre
FROM XDiario
WHERE enlazado = FALSE
GROUP BY ASIEN
HAVING Quadre != 0
) sub USING(ASIEN)
WHERE SUBCTA > '5999999999'
GROUP BY ASIEN
) sub2 USING(id)
SET Eurohaber = IF(IFNULL(Eurohaber,0) = 0, Eurohaber, Eurohaber + Quadre),
    Eurodebe =  IF(IFNULL(Eurodebe,0) = 0, Eurodebe, Eurodebe - Quadre);

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `__entradaCambioUpdate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `__entradaCambioUpdate`(IN vIdEntrada INT)
BEGIN

	DECLARE vMoneda INT;
    
    SELECT Id_Moneda INTO vMoneda FROM Entradas WHERE Id_Entrada = vIdEntrada;
            
	UPDATE Entradas 
        SET comision = getComision(vIdEntrada, vMoneda)
        WHERE Id_Entrada = vIdEntrada;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `__entryUpdateComision` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `__entryUpdateComision`(vIdEntrada INT)
BEGIN
	UPDATE Entradas 
		SET comision = getComision(vIdEntrada, Id_Moneda)
		WHERE Id_Entrada = vIdEntrada;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_cache_cleaner` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `__item_cache_cleaner`()
BEGIN
    DECLARE v_lifetime INT DEFAULT 80;
    DECLARE v_expired DATETIME DEFAULT TIMESTAMPADD(SECOND, -v_lifetime, NOW());

	IF (SELECT MAX(id) FROM`cache`) < 32000
	THEN
		UPDATE `cache` SET age = age + 1 WHERE stamp < v_expired ORDER BY age DESC;

		DELETE FROM `cache` WHERE stamp < TIMESTAMPADD(SECOND, -40, v_expired);

		IF ROW_COUNT() > 0
		THEN
			DELETE a
				FROM cache_a a
				LEFT JOIN `cache` c ON c.id = a.cache_id
					WHERE c.id IS NULL;
		END IF;
	ELSE
		TRUNCATE TABLE `cache`;
	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 `__proveedores_extracto` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `__proveedores_extracto`(IN idPROV INT, IN idMONEDA INT, IN idEMP INT)
BEGIN


SET @saldo_eur:= 0;
SET @saldo_div:= 0;

SELECT 
    *,
    @saldo_eur:= round(@saldo_eur + IFNULL(Pago_Euros, 0) - IFNULL(Fac_Euros, 0) ,2 ) AS saldo_eur,
    @saldo_div:= round(@saldo_div + IFNULL(Pago_Divisas, 0) - IFNULL(Fac_Divisas, 0) ,2 ) AS saldo_div
FROM
    (SELECT 
        *
    FROM
        (SELECT 
            'R',
            NULL as banco_id,
            r.empresa_id,
            r.serie,
            r.id,
            r.fecha,
            CONCAT('S/Fra ', r.sref) sref,
            if(r.moneda_id > 1,round(sum(divisa) / sum(cantidad),3),NULL) val_cambio,
            CAST(sum(cantidad) as DECIMAL(10,2)) as Fac_Euros,
            CAST(sum(divisa) as DECIMAL(10,2)) as Fac_Divisas,
            NULL AS Pago_Euros,
            NULL AS Pago_Divisas,
            r.moneda_id,
            r.contabilizada,
            Moneda,
            NULL as pago_sdc_id
    FROM
        recibida r
	JOIN recibida_vencimiento rv on rv.recibida_id = r.id
    JOIN Monedas m on m.Id_Moneda = r.moneda_id
    WHERE
        r.fecha > '2014-12-31'
            AND r.proveedor_id = idPROV 
            AND idMONEDA IN (r.moneda_id, 0)
            AND idEMP IN (r.empresa_id,0)
	GROUP BY r.id
            
            
            
            UNION ALL SELECT 
        
            'P',
            p.id_banco,
            p.empresa_id,
            NULL,
            p.id,
            Fecha,
            CONCAT(IFNULL(name, ''), IF(pre.concepto <> '', CONCAT(' : ', pre.concepto), '')),
            if(p.id_moneda > 1, p.divisa / importe, NULL) tip_cambio,
            NULL,
            NULL,
            p.importe,
            p.divisa,
            p.id_moneda,
            IFNULL(conciliado, 0),
            Moneda,
            pago_sdc_id
    FROM
        pago p
    LEFT JOIN Monedas ON Monedas.Id_Moneda = p.id_moneda
    LEFT JOIN Bancos ON p.id_banco = Bancos.Id_banco
    LEFT JOIN pay_met pm ON p.pay_met_id = pm.id
    LEFT JOIN Pagares pre ON pre.pago_id = p.id
    WHERE
        Fecha > '2014-12-31'
            AND p.Id_Proveedor = idPROV
            AND idMONEDA IN (p.id_moneda,0)
            AND idEMP IN (p.empresa_id,0)
            ) AS SUB
    ORDER BY fecha) t;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `__proveedores_extracto_vtos` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `__proveedores_extracto_vtos`(IN idPROV INT, IN idMONEDA INT, IN idEMP INT)
BEGIN


SET @saldo_eur:= 0;
SET @saldo_div:= 0;

SELECT 
    *,
    @saldo_eur:= round(@saldo_eur + IFNULL(Pago_Euros, 0) - IFNULL(Fac_Euros, 0) ,2 ) AS saldo_eur,
    @saldo_div:= round(@saldo_div + IFNULL(Pago_Divisas, 0) - IFNULL(Fac_Divisas, 0) ,2 ) AS saldo_div
FROM
    (SELECT 
        *
    FROM
        (SELECT 
            'V',
            NULL as banco_id,
            r.empresa_id,
            r.serie,
            r.id,
            rv.fecha,
            CONCAT('S/Fra ', r.sref) sref,
            if(r.moneda_id > 1,round(sum(divisa) / sum(cantidad),3),NULL) val_cambio,
            CAST(sum(cantidad) as DECIMAL(10,2)) as Fac_Euros,
            CAST(sum(divisa) as DECIMAL(10,2)) as Fac_Divisas,
            NULL AS Pago_Euros,
            NULL AS Pago_Divisas,
            r.moneda_id,
            r.contabilizada,
            Moneda,
            NULL as pago_sdc_id
    FROM
        recibida r
	JOIN recibida_vencimiento rv on rv.recibida_id = r.id
    JOIN Monedas m on m.Id_Moneda = r.moneda_id
    WHERE
        r.fecha > '2014-12-31'
            AND r.proveedor_id = idPROV 
            AND idMONEDA IN (r.moneda_id, 0)
            AND idEMP IN (r.empresa_id,0)
	GROUP BY rv.id
            
            
            
            UNION ALL SELECT 
        
            'P',
            p.id_banco,
            p.empresa_id,
            NULL,
            p.id,
            Fecha,
            CONCAT(IFNULL(name, ''), IF(pre.concepto <> '', CONCAT(' : ', pre.concepto), '')),
            if(p.id_moneda > 1, p.divisa / importe, NULL) tip_cambio,
            NULL,
            NULL,
            p.importe,
            p.divisa,
            p.id_moneda,
            IFNULL(conciliado, 0),
            Moneda,
            pago_sdc_id
    FROM
        pago p
    LEFT JOIN Monedas ON Monedas.Id_Moneda = p.id_moneda
    LEFT JOIN Bancos ON p.id_banco = Bancos.Id_banco
    LEFT JOIN pay_met pm ON p.pay_met_id = pm.id
    LEFT JOIN Pagares pre ON pre.pago_id = p.id
    WHERE
        Fecha > '2014-12-31'
            AND p.Id_Proveedor = idPROV
            AND idMONEDA IN (p.id_moneda,0)
            AND idEMP IN (p.empresa_id,0)
            ) AS SUB
    ORDER BY fecha, id) t;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `__radar` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `__radar`(IN `today` DATETIME, IN `worker` INT, IN `scopeDays` SMALLINT)
BEGIN

    DECLARE todayMidnight DATE DEFAULT TIMESTAMP(today,'23:59:59');
	DECLARE yesterday DATETIME;
	DECLARE maxDate DATETIME;
	DECLARE datBUF DATETIME;
	DECLARE warehouse INTEGER;
	DECLARE done BIT DEFAULT 0;
	DECLARE visible_calc INTEGER;
	DECLARE available_calc INTEGER;
    DECLARE dateStart DATE;

	SET dateStart = TIMESTAMPADD(MONTH, -2, CURDATE());
	SELECT TIMESTAMPADD(DAY, -1, today) INTO yesterday;
	-- lo quitamos despues de campañaA
	SELECT TIMESTAMP(TIMESTAMPADD(DAY, scopeDays, yesterday),'23:59:59') INTO maxDate;
	-- SELECT TIMESTAMP(TIMESTAMPADD(DAY, 14, yesterday),'23:59:59') INTO maxDate;
	-- Creamos una tabla con los Comerciales de los que se mostraran los tickets
    IF worker = 2 and curdate() between '2018-07-02' and '2018-07-09' then
    
		set worker = 43;
    
    end if;
    
	CALL subordinate(worker,TRUE);
    
	-- Se genera una tabla con los tickets representados
	DROP TEMPORARY TABLE IF EXISTS ticketRange;
	CREATE TEMPORARY TABLE ticketRange
	SELECT T.Id_Ticket, T.Id_Cliente, C.Id_Trabajador
		FROM Tickets T
				LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket
				INNER JOIN Clientes C on C.Id_Cliente = T.Id_Cliente 
				INNER JOIN subordinate s1 ON C.Id_Trabajador = s1.Id_Trabajador
		WHERE Fecha >=  yesterday
			AND Fecha <=  maxDate AND T.Factura Is NULL 
			AND IFNULL(tls.alertLevel,0) < 3
        
    UNION DISTINCT
			
	SELECT Id_Ticket, s.Id_Cliente, s.Id_Trabajador
		FROM sharingclient s
			INNER JOIN Tickets T USING(Id_Cliente)
			LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket
			INNER JOIN subordinate s2 ON s.Id_Trabajador = s2.Id_Trabajador
		WHERE maxDate >= datSTART 
			AND datEND >= yesterday
			AND date(Fecha) >= IF(yesterday > datSTART, yesterday, datSTART)
			AND date(Fecha) <= IF(datEND > maxDate, maxDate, datEND)
			AND IFNULL(tls.alertLevel,0) < 3
    
    UNION DISTINCT

	SELECT Id_Ticket, C.Id_Cliente, s.Id_Suplente
		FROM Clientes C       
			INNER JOIN Tickets T USING(Id_Cliente)
			LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket
			INNER JOIN sharingcart s ON s.Id_Trabajador = C.Id_Trabajador
			INNER JOIN subordinate su on su.Id_Trabajador=Id_Suplente
		WHERE maxDate >= datSTART 
			AND datEND >= yesterday
			AND date(Fecha) >= IF(yesterday > datSTART, yesterday, datSTART)
			AND date(Fecha) <= IF(datEND > maxDate, maxDate, datEND)
			AND IFNULL(tls.alertLevel,0) < 3
    
    UNION DISTINCT 
    
    SELECT Id_Ticket, C.Id_Cliente, C.Id_Trabajador
	FROM Clientes C       
		INNER JOIN Tickets T USING(Id_Cliente)
		LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket
		INNER JOIN workerTeamCollegues w ON w.collegueId = C.Id_Trabajador
	WHERE Fecha >=  yesterday
		AND Fecha <=  maxDate AND T.Factura Is NULL 
		AND IFNULL(tls.alertLevel,0) < 3
        AND w.workerId = worker;
		
	IF (SELECT COUNT(*) FROM ticketRange) THEN 
    
		-- Generamos varias auxiliares (ya podian los de mysql haber solucionado esto)

		DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
		CREATE TEMPORARY TABLE tmp.client_list
		(INDEX (Id_Cliente))
		ENGINE = MEMORY
			SELECT DISTINCT Id_Cliente FROM ticketRange;

		DROP TEMPORARY TABLE IF EXISTS cr5;
		CREATE TEMPORARY TABLE cr5
		(INDEX (Id_Cliente))
		ENGINE = MEMORY
			SELECT Id_Cliente FROM tmp.client_list;
			
		DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
		CREATE TEMPORARY TABLE tmp.ticket
			ENGINE = MEMORY
			SELECT t.Id_Ticket ticketFk FROM Tickets t
				STRAIGHT_JOIN tmp.client_list c ON t.Id_Cliente = c.Id_Cliente
			WHERE Fecha BETWEEN dateStart AND  maxDate 
			AND Factura IS NULL;

	CALL vn.ticketGetTotal();

	-- Generamos otra tabla temporal con los Tickets_iva
				
		DROP TEMPORARY TABLE IF EXISTS tt3;
		CREATE TEMPORARY TABLE tt3
		ENGINE = MEMORY
		SELECT t.ticketFk, tt.total, tr.* 
			FROM tmp.ticket t
				LEFT JOIN tmp.ticketTotal tt ON t.ticketFk = tt.ticketFk
				JOIN ticketRange tr ON tr.Id_Ticket = t.ticketFk;

		-- Generamos la lista de tickets y sus datos 
				
		DROP TEMPORARY TABLE IF EXISTS Radartest;

		CREATE TEMPORARY TABLE Radartest

		SELECT IF(C.Id_Trabajador = worker, 1, 0) as Propio,
				Credito,
				CAST(Riesgo AS DECIMAL (10,2)) Riesgo,
				-- Greuge,
				T.Id_Ticket,
				T.warehouse_id as wh,
				T.Fecha,
				T.Alias,
				-- T.Vista,
				REPEAT(' ',50) as problem,
				T.Agencia Tipo,
				-- C.Id_Trabajador,
                T.workerId AS Id_Trabajador,
				T.Solucion,
				T.Localizacion,
				IFNULL(state,'LIBRE') as Estado, 
                alertLevel,
				alertCode,
				Date(T.Fecha) as Fecha_Simple,
				CAST(T.Importe AS DECIMAL (10,2)) Importe,
				C.Descuento,
				C.calidad,
				C.Id_Cliente,
				p.`name` provincia
		 FROM Clientes C
		 INNER JOIN

				(

				SELECT T.* ,  A.Vista, A.Agencia, s.`name` as state, alertLevel, s.`code` AS alertCode, tt3.Id_Trabajador AS workerId,

					   tt3.total as Importe,

					   0 AS inacabable
					   
					   -- (-1 < ifnull(order_id,-1)) as isbionic

				  FROM Tickets T
				  LEFT JOIN vn.ticketState ts on ts.ticket = T.Id_Ticket
                  LEFT JOIN vn2008.state s on s.id = ts.state
				  
				INNER JOIN tt3 ON tt3.ticketFk = T.Id_Ticket
				
				-- LEFT JOIN (SELECT DISTINCT 1 as order_id, Id_Ticket FROM order_Tickets) o on o.Id_Ticket = T.Id_Ticket

				INNER JOIN Agencias A ON A.Id_Agencia = T.Id_Agencia
					
				-- WHERE T.Etiquetasemitidas = FALSE
					GROUP BY T.Id_Ticket

				) AS T ON T.Id_Cliente = C.Id_Cliente
				
			LEFT JOIN Consignatarios co ON co.Id_Consigna = T.Id_Consigna
			LEFT JOIN province p ON p.province_id = co.province_id

		  LEFT JOIN

				(

				SELECT TOTAL.Id_Cliente, ROUND(SUM(amount),2) as Riesgo FROM

					(SELECT cl.Id_Cliente, amount FROM bi.customer_risk cr
						INNER JOIN tmp.client_list cl ON cr.customer_id = cl.Id_Cliente

						UNION ALL

					SELECT t.Id_Cliente, tt.total FROM tmp.ticketTotal tt
						INNER JOIN Tickets t ON t.Id_Ticket = tt.ticketFk
						INNER JOIN cr5 C ON C.Id_Cliente = t.Id_Cliente
					WHERE t.Fecha BETWEEN dateStart AND  maxDate  
						AND t.Factura is null

					) as TOTAL GROUP BY TOTAL.Id_Cliente

				 ) AS Peligros ON Peligros.Id_Cliente = C.Id_Cliente
                 ;
			   -- Actualizamos el Riesgo con los tickets futuros
			   set @cliente:= 0;
			   SET @riesgo := 0;
			   
	   UPDATE Radartest  SET Riesgo =  
	   IF(@cliente <> @cliente:= Id_Cliente ,  - Importe + @riesgo:= - Riesgo + Importe , - Importe + @riesgo:= @riesgo + Importe)
	   order by Id_Cliente, Fecha_Simple DESC;
          
		DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list;
		
		CREATE TEMPORARY TABLE tmp.ticket_list
		SELECT Id_Ticket, Id_Cliente FROM Radartest;
		
		CALL prepare_client_list();
		CALL production_buffer_problems;

		UPDATE Radartest r
		JOIN (    
			SELECT Id_Ticket, GROUP_CONCAT(problem) problem
			FROM tmp.buffer_problems
			GROUP BY Id_Ticket
			) p on p.Id_Ticket = r.Id_Ticket
		SET r.problem = p.problem;

			

		SELECT R.*, Riesgo + Credito as Risk , CodigoTrabajador 
		FROM Radartest R
		INNER JOIN vn2008.Trabajadores trab on R.Id_Trabajador=trab.Id_Trabajador;
        
	END IF;
    
	DROP TEMPORARY TABLE IF EXISTS ticketRange;
	DROP TABLE IF EXISTS subordinate;
    DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
    DROP TEMPORARY TABLE IF EXISTS cr5;
    DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
    
  
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `__radarTest` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `__radarTest`(IN `today` DATETIME, IN `worker` INT, IN `scopeDays` SMALLINT)
BEGIN

    DECLARE todayMidnight DATE DEFAULT TIMESTAMP(today,'23:59:59');
	DECLARE yesterday DATETIME;
	DECLARE maxDate DATETIME;
	DECLARE datBUF DATETIME;
	DECLARE warehouse INTEGER;
	DECLARE done BIT DEFAULT 0;
	DECLARE visible_calc INTEGER;
	DECLARE available_calc INTEGER;
    DECLARE dateStart DATE;

	SET dateStart = TIMESTAMPADD(MONTH, -2, CURDATE());
	SELECT TIMESTAMPADD(DAY, -1, today) INTO yesterday;
	-- lo quitamos despues de campañaA
	SELECT TIMESTAMP(TIMESTAMPADD(DAY, scopeDays, yesterday),'23:59:59') INTO maxDate;
	-- SELECT TIMESTAMP(TIMESTAMPADD(DAY, 14, yesterday),'23:59:59') INTO maxDate;
	-- Creamos una tabla con los Comerciales de los que se mostraran los tickets
	CALL subordinate(worker,TRUE);
    
	-- Se genera una tabla con los tickets representados
	DROP TEMPORARY TABLE IF EXISTS ticketRange;
	CREATE TEMPORARY TABLE ticketRange
	SELECT T.Id_Ticket, T.Id_Cliente, C.Id_Trabajador
		FROM Tickets T
				LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket
				INNER JOIN Clientes C on C.Id_Cliente = T.Id_Cliente 
				INNER JOIN subordinate s1 ON C.Id_Trabajador = s1.Id_Trabajador
		WHERE Fecha >=  yesterday
			AND Fecha <=  maxDate AND T.Factura Is NULL 
			AND IFNULL(tls.alertLevel,0) < 3
        
    UNION DISTINCT
			
	SELECT Id_Ticket, s.Id_Cliente, s.Id_Trabajador
		FROM sharingclient s
			INNER JOIN Tickets T USING(Id_Cliente)
			LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket
			INNER JOIN subordinate s2 ON s.Id_Trabajador = s2.Id_Trabajador
		WHERE maxDate >= datSTART 
			AND datEND >= yesterday
			AND date(Fecha) >= IF(yesterday > datSTART, yesterday, datSTART)
			AND date(Fecha) <= IF(datEND > maxDate, maxDate, datEND)
			AND IFNULL(tls.alertLevel,0) < 3
    
    UNION DISTINCT

	SELECT Id_Ticket, C.Id_Cliente, s.Id_Suplente
		FROM Clientes C       
			INNER JOIN Tickets T USING(Id_Cliente)
			LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket
			INNER JOIN sharingcart s ON s.Id_Trabajador = C.Id_Trabajador
			INNER JOIN subordinate su on su.Id_Trabajador=Id_Suplente
		WHERE maxDate >= datSTART 
			AND datEND >= yesterday
			AND date(Fecha) >= IF(yesterday > datSTART, yesterday, datSTART)
			AND date(Fecha) <= IF(datEND > maxDate, maxDate, datEND)
			AND IFNULL(tls.alertLevel,0) < 3
    
    UNION DISTINCT 
    
    SELECT Id_Ticket, C.Id_Cliente, C.Id_Trabajador
	FROM Clientes C       
		INNER JOIN Tickets T USING(Id_Cliente)
		LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket
		INNER JOIN workerTeamCollegues w ON w.collegueId = C.Id_Trabajador
	WHERE Fecha >=  yesterday
		AND Fecha <=  maxDate AND T.Factura Is NULL 
		AND IFNULL(tls.alertLevel,0) < 3
        AND w.workerId = worker;
		
	IF (SELECT COUNT(*) FROM ticketRange) THEN 
    
		-- Generamos varias auxiliares (ya podian los de mysql haber solucionado esto)

		DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
		CREATE TEMPORARY TABLE tmp.client_list
		(INDEX (Id_Cliente))
		ENGINE = MEMORY
			SELECT DISTINCT Id_Cliente FROM ticketRange;

		DROP TEMPORARY TABLE IF EXISTS cr5;
		CREATE TEMPORARY TABLE cr5
		(INDEX (Id_Cliente))
		ENGINE = MEMORY
			SELECT Id_Cliente FROM tmp.client_list;
			
		DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
		CREATE TEMPORARY TABLE tmp.ticket
			ENGINE = MEMORY
			SELECT t.Id_Ticket ticketFk FROM Tickets t
				STRAIGHT_JOIN tmp.client_list c ON t.Id_Cliente = c.Id_Cliente
			WHERE Fecha BETWEEN dateStart AND  maxDate 
			AND Factura IS NULL;

	CALL vn.ticketGetTotal();

	-- Generamos otra tabla temporal con los Tickets_iva
				
		DROP TEMPORARY TABLE IF EXISTS tt3;
		CREATE TEMPORARY TABLE tt3
		ENGINE = MEMORY
		SELECT t.ticketFk, tt.total, tr.* 
			FROM tmp.ticket t
				LEFT JOIN tmp.ticketTotal tt ON t.ticketFk = tt.ticketFk
				JOIN ticketRange tr ON tr.Id_Ticket = t.ticketFk;

		-- Generamos la lista de tickets y sus datos 
				
		DROP TEMPORARY TABLE IF EXISTS Radartest;

		CREATE TEMPORARY TABLE Radartest

		SELECT IF(C.Id_Trabajador = worker, 1, 0) as Propio,
				Credito,
				CAST(Riesgo AS DECIMAL (10,2)) Riesgo,
				-- Greuge,
				T.Id_Ticket,
				T.warehouse_id as wh,
				T.Fecha,
				T.Alias,
				-- T.Vista,
				REPEAT(' ',50) as problem,
				T.Agencia Tipo,
				-- C.Id_Trabajador,
                T.workerId AS Id_Trabajador,
				T.Solucion,
				T.Localizacion,
				IFNULL(state,'LIBRE') as Estado, 
                alertLevel,
				alertCode,
				Date(T.Fecha) as Fecha_Simple,
				CAST(T.Importe AS DECIMAL (10,2)) Importe,
				C.Descuento,
				C.calidad,
				C.Id_Cliente,
				p.`name` provincia
		 FROM Clientes C
		 INNER JOIN

				(

				SELECT T.* ,  A.Vista, A.Agencia, s.`name` as state, alertLevel, s.`code` AS alertCode, tt3.Id_Trabajador AS workerId,

					   tt3.total as Importe,

					   0 AS inacabable
					   
					   -- (-1 < ifnull(order_id,-1)) as isbionic

				  FROM Tickets T
				  LEFT JOIN vn.ticketState ts on ts.ticket = T.Id_Ticket
                  LEFT JOIN vn2008.state s on s.id = ts.state
				  
				INNER JOIN tt3 ON tt3.ticketFk = T.Id_Ticket
				
				-- LEFT JOIN (SELECT DISTINCT 1 as order_id, Id_Ticket FROM order_Tickets) o on o.Id_Ticket = T.Id_Ticket

				INNER JOIN Agencias A ON A.Id_Agencia = T.Id_Agencia
					
				-- WHERE T.Etiquetasemitidas = FALSE
					GROUP BY T.Id_Ticket

				) AS T ON T.Id_Cliente = C.Id_Cliente
				
			LEFT JOIN Consignatarios co ON co.Id_Consigna = T.Id_Consigna
			LEFT JOIN province p ON p.province_id = co.province_id

		  LEFT JOIN

				(

				SELECT TOTAL.Id_Cliente, ROUND(SUM(amount),2) as Riesgo FROM

					(SELECT cl.Id_Cliente, amount FROM bi.customer_risk cr
						INNER JOIN tmp.client_list cl ON cr.customer_id = cl.Id_Cliente

						UNION ALL

					SELECT t.Id_Cliente, tt.total FROM tmp.ticketTotal tt
						INNER JOIN Tickets t ON t.Id_Ticket = tt.ticketFk
						INNER JOIN cr5 C ON C.Id_Cliente = t.Id_Cliente
					WHERE t.Fecha BETWEEN dateStart AND  maxDate  
						AND t.Factura is null

					) as TOTAL GROUP BY TOTAL.Id_Cliente

				 ) AS Peligros ON Peligros.Id_Cliente = C.Id_Cliente
                 ORDER BY C.Id_Cliente;
			   -- Actualizamos el Riesgo con los tickets futuros
			   set @cliente:= 0;
			   SET @riesgo := 0;
			   
				SELECT * FROM Radartest;
               
				UPDATE Radartest  SET Riesgo =  
					IF(@cliente <> @cliente:= Id_Cliente ,  
						- Importe + @riesgo:= - (Riesgo + Importe), 
                        - Importe + @riesgo := (@riesgo + Importe)),
					Propio = @riesgo
				order by Id_Cliente, Fecha_Simple DESC;
		  
		DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list;
		
		CREATE TEMPORARY TABLE tmp.ticket_list
		SELECT Id_Ticket, Id_Cliente FROM Radartest;
		-- select * from Radartest;
        
		CALL prepare_client_list();
		CALL production_buffer_problems;


		UPDATE Radartest r
		JOIN (    
			SELECT Id_Ticket, GROUP_CONCAT(problem) problem
			FROM tmp.buffer_problems
			GROUP BY Id_Ticket
			) p on p.Id_Ticket = r.Id_Ticket
		SET r.problem = p.problem;

			

		SELECT R.*, Riesgo + Credito as Risk , CodigoTrabajador 
		FROM Radartest R
		INNER JOIN vn2008.Trabajadores trab on R.Id_Trabajador=trab.Id_Trabajador;
        
	END IF;
    
	DROP TEMPORARY TABLE IF EXISTS ticketRange;
	DROP TABLE IF EXISTS subordinate;
    DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
    DROP TEMPORARY TABLE IF EXISTS cr5;
    DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
    
  
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `__saldos_bancos` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `__saldos_bancos`()
BEGIN

declare datEND DATE;

SET datEND = CURDATE() + INTERVAL 2 MONTH;

drop table if exists bi.saldos_bancos;


create table bi.saldos_bancos

	select Semana, Mes, Año, Entrada
				, Salida
				, @saldo :=   IF(@banco = Id_Banco and @emp = empresa_id, @saldo,0) + ifnull(Entrada,0)-ifnull(Salida,0) as Saldo
				, @banco := Id_Banco as Id_Banco
                , @emp := empresa_id as empresa_id
                , 'NUL' as Empresa
                
	from
    (
    select * from
	(
	select t.week as Semana, t.year as Año, t.month as Mes, b.Id_Banco, sum(Entrada) as Entrada, sum(Salida) as Salida, @banco := 0, @saldo := 0, @emp := 0, e.id as empresa_id
	from time t
	join Bancos b on b.entity_id = 1
    join empresa e on e.id IN (791,442)
	left join 
	(
	Select Id_Banco, Entrada, Salida, Cajafecha,empresa_id
	from Cajas 
	where Cajafecha >= '2015-01-01' 
    and Serie = 'MB'
	union all
	Select Id_Banco, NULL, importe, greatest(fecha,TIMESTAMPADD(DAY,1,CURDATE())),empresa_id
	from pago
	where conciliado = FALSE /*fecha between CURDATE() and datEND*/
	union all
	Select Id_Banco, Entregado, NULL, greatest(Fechacobro,TIMESTAMPADD(DAY,1,CURDATE())),empresa_id
	from Recibos
	where Fechacobro between CURDATE() and datEND
	union all
	Select IFNULL(Id_Banco,9999), Importe, NULL, Fecha,empresa_id
	from Saldos_Prevision
	where Fecha between CURDATE() and datEND
	) sub2 on t.date = sub2.Cajafecha and b.Id_Banco = sub2.Id_Banco and e.id = sub2.empresa_id

	where t.date between '2015-01-01' and datEND
	and b.cash != 1 
	group by b.Id_Banco, e.id,  t.year, t.week
	) sub3
    order by Id_Banco, empresa_id, Año, Mes, Semana
	) sub	
;

update bi.saldos_bancos s
join empresa e on e.id = s.empresa_id
set s.Empresa = abbreviation;

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

declare datEND DATE;

SET datEND = CURDATE() + INTERVAL 2 MONTH;

drop table if exists bi.saldos_bancos_pordia;


create table bi.saldos_bancos_pordia

	select Fecha, Entrada
				, Salida
				, @saldo :=   IF(@banco = Id_Banco and @emp = empresa_id, @saldo,0) + ifnull(Entrada,0)-ifnull(Salida,0) as Saldo
				, @banco := Id_Banco as Id_Banco
                , @emp := empresa_id as empresa_id
                , 'NUL' as Empresa
                , Año, Mes, Dia
                
	from
    (
    select * from
	(
	select t.day as Dia, t.month as Mes,t.year as Año, t.date as Fecha, b.Id_Banco, sum(Entrada) as Entrada, sum(Salida) as Salida, @banco := 0, @saldo := 0, @emp := 0, e.id as empresa_id
	from time t
	join Bancos b on b.entity_id = 1
    join empresa e on e.id IN (791,442)
	left join 
	(
	Select Id_Banco, Entrada, Salida, Cajafecha,empresa_id
	from Cajas 
	where Cajafecha >= '2015-01-01' 
    and Serie = 'MB'
	union all
	Select Id_Banco, NULL, importe, greatest(fecha,TIMESTAMPADD(DAY,1,CURDATE())),empresa_id
	from pago
	where conciliado = FALSE /*fecha between CURDATE() and datEND*/
	union all
	Select Id_Banco, Entregado, NULL, greatest(Fechacobro,TIMESTAMPADD(DAY,1,CURDATE())),empresa_id
	from Recibos
	where conciliado = FALSE  -- Fechacobro between CURDATE() and datEND
	union all
	Select IFNULL(Id_Banco,9999), Importe, NULL, Fecha,empresa_id
	from Saldos_Prevision
	where Fecha between CURDATE() and datEND
	) sub2 on t.date = sub2.Cajafecha and b.Id_Banco = sub2.Id_Banco and e.id = sub2.empresa_id

	where t.date between '2015-01-01' and datEND
	and b.cash != 1 
	group by b.Id_Banco, e.id, t.date
	) sub3
    order by Id_Banco, empresa_id, Fecha
	) sub	
;

update bi.saldos_bancos_pordia s
join empresa e on e.id = s.empresa_id
set s.Empresa = abbreviation;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `__subordinate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `__subordinate`(IN `idWORKER` INT, IN `CasoBase` INT)
BEGIN
	DECLARE auxWorker INT;
    DECLARE vCompanyId INT;
    
    SELECT empresa_id 
		INTO vCompanyId
        FROM Trabajadores
        WHERE Id_Trabajador = idWORKER;
	
    IF vCompanyId = 1381 THEN  -- ORNAMENTALES
    
		DROP TABLE IF EXISTS subordinate;
		CREATE TABLE subordinate
			(INDEX (Id_Trabajador)) ENGINE = MEMORY
			SELECT Id_Trabajador,TRUE visited,0 boss
            FROM Trabajadores
            WHERE empresa_id = vCompanyId;
    
    ELSE
    
    
    /* PAK 23/05/2016
    
		Guardia de domingos
        
        Los domingos viene Fran a hacer de comercial y necesita ver todos los radares
    
    
    
    IF dayofweek(curdate()) = 1 and idWORKER = 43 then  -- Domingo y Fran Natek
    
			DROP TABLE IF EXISTS subordinate;
            
			CREATE TABLE subordinate
			(INDEX (Id_Trabajador)) ENGINE = MEMORY
			SELECT Id_Trabajador,TRUE visited,0 boss
            FROM Trabajadores;
    
    
    else
    */
        
	IF CasoBase THEN
		SET @@max_sp_recursion_depth = 5 ;
		DROP TABLE IF EXISTS subordinate;
		CREATE TABLE subordinate
			(INDEX (Id_Trabajador)) ENGINE = MEMORY
			SELECT idWORKER Id_Trabajador,TRUE visited,0 boss;
	END IF;
		
	INSERT INTO subordinate
		SELECT Id_Trabajador,0,idWORKER FROM Trabajadores WHERE boss = idWORKER;
	IF (SELECT COUNT(*) FROM subordinate WHERE visited = 0 AND idWORKER = boss LIMIT 1) > 0 THEN
		SELECT Id_Trabajador into auxWorker FROM subordinate WHERE visited = 0 AND idWORKER = boss LIMIT 1;
		REPEAT 			
			CALL subordinate(auxWorker,FALSE);
			UPDATE subordinate SET visited = TRUE WHERE Id_Trabajador = auxWorker;
			SET auxWorker = 0;
			SELECT Id_Trabajador into auxWorker FROM subordinate WHERE visited = 0  AND idWORKER = boss LIMIT 1;
			UNTIL auxWorker = 0
		END REPEAT;
	END IF;
	
    /*
    end if;
    */
    
    END IF;
    
	IF idWorker = 2 THEN
		INSERT INTO subordinate(Id_Trabajador,visited,boss) VALUES (2,TRUE,2);
	-- 	INSERT INTO subordinate(Id_Trabajador,visited,boss) VALUES (43,TRUE,2);
    END IF;
    
    /*
    IF CasoBase THEN	
		SELECT * FROM subordinate;
	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 `__subordinate2` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `__subordinate2`(IN `idWORKER` INT, IN `CasoBase` INT)
BEGIN
	DECLARE auxWorker INT;
    DECLARE vCompanyId INT;
    
    SELECT empresa_id 
		INTO vCompanyId
        FROM Trabajadores
        WHERE Id_Trabajador = idWORKER;
	
    IF vCompanyId = 1381 THEN  -- ORNAMENTALES
    
		DROP TABLE IF EXISTS subordinate;
		CREATE TABLE subordinate
			(INDEX (Id_Trabajador)) ENGINE = MEMORY
			SELECT Id_Trabajador,TRUE visited,0 boss
            FROM Trabajadores
            WHERE empresa_id = vCompanyId;
    
    ELSE
    
    
    /* PAK 23/05/2016
    
		Guardia de domingos
        
        Los domingos viene Fran a hacer de comercial y necesita ver todos los radares
    
    
    
    IF dayofweek(curdate()) = 1 and idWORKER = 43 then  -- Domingo y Fran Natek
    
			DROP TABLE IF EXISTS subordinate;
            
			CREATE TABLE subordinate
			(INDEX (Id_Trabajador)) ENGINE = MEMORY
			SELECT Id_Trabajador,TRUE visited,0 boss
            FROM Trabajadores;
    
    
    else
    */
        
	IF CasoBase THEN
		SET @@max_sp_recursion_depth = 5 ;
		DROP TABLE IF EXISTS subordinate;
		CREATE TABLE subordinate
			(INDEX (Id_Trabajador)) ENGINE = MEMORY
			SELECT idWORKER Id_Trabajador,TRUE visited,0 boss;
	END IF;
		
	INSERT INTO subordinate
		SELECT Id_Trabajador,0,idWORKER FROM Trabajadores WHERE boss = idWORKER;
	IF (SELECT COUNT(*) FROM subordinate WHERE visited = 0 AND idWORKER = boss LIMIT 1) > 0 THEN
		SELECT Id_Trabajador into auxWorker FROM subordinate WHERE visited = 0 AND idWORKER = boss LIMIT 1;
		REPEAT 			
			CALL subordinate(auxWorker,FALSE);
			UPDATE subordinate SET visited = TRUE WHERE Id_Trabajador = auxWorker;
			SET auxWorker = 0;
			SELECT Id_Trabajador into auxWorker FROM subordinate WHERE visited = 0  AND idWORKER = boss LIMIT 1;
			UNTIL auxWorker = 0
		END REPEAT;
	END IF;
	
    /*
    end if;
    */
    
    END IF;
    
    IF idWorker = 2 THEN
		INSERT INTO subordinate(Id_Trabajador) VALUES (2);
    END IF;
    
    /*
    IF CasoBase THEN	
		SELECT * FROM subordinate;
	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: `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 `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`),
  KEY `inter_id` (`Id_Ticket`,`inter_id`) USING BTREE,
  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=17175179 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

	/* PAK 08/05/18 Los sacadores no deben de poner los tickets en revisión */
    /*
	DECLARE vIsSacador BOOLEAN;
    
	IF NEW.state_id = 6 THEN -- Revisión
		
        SELECT (COUNT(*) > 0) INTO vIsSacador
			FROM inter
			WHERE state_id = 5 -- Preparacion
				AND Id_Trabajador = NEW.Id_Trabajador
                AND Id_Ticket = NEW.Id_Ticket;
                
		IF vIsSacador THEN
        
			SET NEW.state_id = 5;
        
        END IF;
	
    END IF;
    */
    /* PAK 08/05/18 Los tickets no se pueden marcar como servidos en el futuro */
    IF NEW.state_id = 16 AND (SELECT date(landed) FROM vn.ticket WHERE id = NEW.Id_Ticket) > CURDATE() THEN -- Entregado
        
			SET NEW.state_id = 22; -- ¿ Fecha ?
 
    END IF;

	/* 08/05/18 PAK Este código parece fósil. Lo comento.
    
	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 -- Preparación
    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  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_unicode_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clean`()
BEGIN
    DECLARE vDate DATETIME DEFAULT TIMESTAMPADD(MONTH, -2, CURDATE());
    DELETE FROM inter WHERE odbc_date <= 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 */ ;

--
-- Current Database: `account`
--

USE `account`;

--
-- Final view structure for view `accountDovecot`
--

/*!50001 DROP VIEW IF EXISTS `accountDovecot`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `accountDovecot` AS select `u`.`name` AS `name`,`u`.`password` AS `password` from (`user` `u` join `account` `a` on((`a`.`id` = `u`.`id`))) where `u`.`active` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `accountPam`
--

/*!50001 DROP VIEW IF EXISTS `accountPam`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `accountPam` AS select `u`.`name` AS `name`,`u`.`password` AS `password` from (`user` `u` join `account` `a` on((`u`.`id` = `a`.`id`))) where (`u`.`active` <> 0) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `emailUser`
--

/*!50001 DROP VIEW IF EXISTS `emailUser`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `emailUser` AS select `u`.`id` AS `userFk`,concat(`u`.`name`,'@',`mc`.`domain`) AS `email` from (`user` `u` join `mailConfig` `mc`) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `myRole`
--

/*!50001 DROP VIEW IF EXISTS `myRole`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `myRole` AS select `r`.`inheritsFrom` AS `id` from (`roleRole` `r` join `user` `u` on((`u`.`role` = `r`.`role`))) where (`u`.`id` = `MYUSERGETID`()) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `myUser`
--

/*!50001 DROP VIEW IF EXISTS `myUser`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `myUser` AS select `u`.`id` AS `id`,`u`.`name` AS `name`,`u`.`active` AS `active`,`u`.`email` AS `email`,`u`.`nickname` AS `nickname`,`u`.`lang` AS `lang`,`u`.`role` AS `role`,`u`.`recoverPass` AS `recoverPass` from `user` `u` where (`u`.`name` = `myUserGetName`()) */
/*!50002 WITH CASCADED CHECK OPTION */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

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

USE `bi`;

--
-- Final view structure for view `analisis_grafico_ventas`
--

/*!50001 DROP VIEW IF EXISTS `analisis_grafico_ventas`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `analisis_grafico_ventas` AS select `analisis_ventas`.`Año` AS `Año`,`analisis_ventas`.`Semana` AS `Semana`,sum(`analisis_ventas`.`Importe`) AS `Importe` from `analisis_ventas` group by `analisis_ventas`.`Año`,`analisis_ventas`.`Semana` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `analisis_ventas_simple`
--

/*!50001 DROP VIEW IF EXISTS `analisis_ventas_simple`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `analisis_ventas_simple` AS select `analisis_ventas`.`Año` AS `Año`,`analisis_ventas`.`Semana` AS `Semana`,sum(`analisis_ventas`.`Importe`) AS `Importe` from `analisis_ventas` group by `analisis_ventas`.`Año`,`analisis_ventas`.`Semana` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `customerRiskOverdue`
--

/*!50001 DROP VIEW IF EXISTS `customerRiskOverdue`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `customerRiskOverdue` AS select `cr`.`customer_id` AS `customer_id`,`cr`.`amount` AS `amount`,`cr`.`company_id` AS `company_id` from (((`bi`.`customer_risk` `cr` join `vn`.`company` `co` on((`co`.`id` = `cr`.`company_id`))) join `vn`.`client` `c` on((`cr`.`customer_id` = `c`.`id`))) join `vn`.`payMethod` `pm` on((`pm`.`id` = `c`.`payMethodFk`))) where (`cr`.`amount` and `co`.`isDefaulter` and `pm`.`outstandingDebt` and (`c`.`typeFk` = 'normal')) union all select `i`.`clientFk` AS `Id_Cliente`,-(round(`i`.`amount`,2)) AS `importe`,`i`.`companyFk` AS `empresa_id` from (((`vn`.`invoiceOut` `i` join `vn`.`client` `c` on((`i`.`clientFk` = `c`.`id`))) join `vn`.`company` `co` on((`co`.`id` = `i`.`companyFk`))) join `vn`.`payMethod` `pm` on((`pm`.`id` = `c`.`payMethodFk`))) where ((`i`.`issued` > (curdate() + interval -(101) day)) and ((`i`.`dued` + interval `pm`.`graceDays` day) > curdate()) and (`i`.`amount` > 0) and `co`.`isDefaulter` and `pm`.`outstandingDebt` and (`c`.`typeFk` = 'normal')) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `last_Id_Cubo`
--

/*!50001 DROP VIEW IF EXISTS `last_Id_Cubo`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `last_Id_Cubo` AS select `C`.`Id_Compra` AS `Id_Compra`,`C`.`Id_Article` AS `Id_Article`,`tr`.`warehouse_id` AS `warehouse_id`,`C`.`Id_Cubo` AS `Id_Cubo`,`C`.`Packing` AS `Packing` from ((`vn2008`.`Compres` `C` join `vn2008`.`Entradas` `E` on((`C`.`Id_Entrada` = `E`.`Id_Entrada`))) join `vn2008`.`travel` `tr` on((`E`.`travel_id` = `tr`.`id`))) where ((`C`.`Id_Cubo` is not null) and (`C`.`Id_Cubo` <> '--') and (`tr`.`landing` > (curdate() - interval 18 month))) order by `C`.`Id_Compra` desc */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `rutas`
--

/*!50001 DROP VIEW IF EXISTS `rutas`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `rutas` AS select `tm`.`year` AS `year`,`tm`.`month` AS `month`,`a`.`warehouseFk` AS `warehouse_id`,`r`.`id` AS `Id_Ruta`,`ar`.`id` AS `Id_Agencia`,(`r`.`kmEnd` - `r`.`kmStart`) AS `km`,dayname(`r`.`created`) AS `Dia`,`r`.`created` AS `Fecha`,`r`.`cost` AS `cost`,if(`ap`.`isVolumetric`,(`vn2008`.`ticket_volumen`(`t`.`id`) / `ebv`.`m3`),`t`.`packages`) AS `Bultos`,`v`.`numberPlate` AS `Matricula`,if(isnull(`r`.`cost`),'P','A') AS `Tipo`,`ap`.`isVolumetric` AS `isVolumetric`,`t`.`id` AS `ticketFk` from (((((((((`vn`.`route` `r` join `vn`.`agencyMode` `ar` on((`ar`.`id` = `r`.`agencyModeFk`))) join `vn`.`agency` `a` on((`a`.`id` = `ar`.`agencyFk`))) join `vn`.`time` `tm` on((`tm`.`dated` = `r`.`created`))) join `vn`.`ticket` `t` on((`t`.`routeFk` = `r`.`id`))) join `vn`.`agencyMode` `am` on((`am`.`id` = `t`.`agencyModeFk`))) join `vn`.`address` `ad` on((`ad`.`id` = `t`.`addressFk`))) join `vn`.`agencyProvince` `ap` on(((`ap`.`warehouseFk` = `t`.`warehouseFk`) and (`ap`.`provinceFk` = `ad`.`provinceFk`) and (`ap`.`agencyFk` = `am`.`agencyFk`)))) join `vn`.`expeditionBoxVol` `ebv` on((`ebv`.`boxFk` = 71))) left join `vn`.`vehicle` `v` on((`v`.`id` = `r`.`vehicleFk`))) where ((`r`.`created` > '2016-01-01') and (`t`.`packages` > 0)) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `saleVolume`
--

/*!50001 DROP VIEW IF EXISTS `saleVolume`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `saleVolume` AS select `s`.`id` AS `saleFk`,sum((((`r`.`cm3` * `i`.`compression`) * `s`.`quantity`) / 1000000)) AS `m3` from (((`vn`.`ticket` `t` join `vn`.`sale` `s` on((`s`.`ticketFk` = `t`.`id`))) join `vn`.`item` `i` on((`i`.`id` = `s`.`itemFk`))) join `bi`.`rotacion` `r` on(((`r`.`Id_Article` = `i`.`id`) and (`r`.`warehouse_id` = `t`.`warehouseFk`)))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_clientes_jerarquia`
--

/*!50001 DROP VIEW IF EXISTS `v_clientes_jerarquia`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_clientes_jerarquia` AS select `c`.`id_cliente` AS `Id_Cliente`,`c`.`cliente` AS `Cliente`,`t`.`CodigoTrabajador` AS `Comercial`,`tj`.`CodigoTrabajador` AS `Jefe` from (((`vn2008`.`Clientes` `c` join `vn2008`.`Trabajadores` `t` on((`t`.`Id_Trabajador` = `c`.`Id_Trabajador`))) join `vn2008`.`jerarquia` on((`vn2008`.`jerarquia`.`worker_id` = `c`.`Id_Trabajador`))) join `vn2008`.`Trabajadores` `tj` on((`tj`.`Id_Trabajador` = `vn2008`.`jerarquia`.`boss_id`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_ventas_contables`
--

/*!50001 DROP VIEW IF EXISTS `v_ventas_contables`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_ventas_contables` AS select `vn2008`.`time`.`year` AS `year`,`vn2008`.`time`.`month` AS `month`,cast(sum((((`m`.`Cantidad` * `m`.`Preu`) * (100 - `m`.`Descuento`)) / 100)) as decimal(10,0)) AS `importe` from (((`vn2008`.`Tickets` `t` join `bi`.`f_tvc` on((`t`.`Id_Ticket` = `bi`.`f_tvc`.`Id_Ticket`))) join `vn2008`.`Movimientos` `m` on((`t`.`Id_Ticket` = `m`.`Id_Ticket`))) join `vn2008`.`time` on((`vn2008`.`time`.`date` = cast(`t`.`Fecha` as date)))) where (`t`.`Fecha` >= '2014-01-01') group by `vn2008`.`time`.`year`,`vn2008`.`time`.`month` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

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

USE `bs`;

--
-- Final view structure for view `VentasPorCliente`
--

/*!50001 DROP VIEW IF EXISTS `VentasPorCliente`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `VentasPorCliente` AS select `v`.`Id_Cliente` AS `Id_Cliente`,round(sum(`v`.`importe`),0) AS `VentaBasica`,`t`.`year` AS `year`,`t`.`month` AS `month` from (`vn2008`.`time` `t` join `bs`.`ventas` `v` on((`v`.`fecha` = `t`.`date`))) group by `v`.`Id_Cliente`,`t`.`year`,`t`.`month` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `horasSilla`
--

/*!50001 DROP VIEW IF EXISTS `horasSilla`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `horasSilla` AS select `wj`.`dated` AS `Fecha`,`d`.`name` AS `Departamento`,cast(sum(`wj`.`total`) as decimal(10,2)) AS `Horas`,cast(sum(((`wj`.`total` + `wj`.`lunch`) * `wj`.`priceOrdinaryHour`)) as decimal(10,2)) AS `Salarios` from ((`vn`.`workerJourney` `wj` join `postgresql`.`business_labour` `bl` on((`bl`.`business_id` = `wj`.`businessFk`))) join `vn2008`.`department` `d` on((`d`.`department_id` = `bl`.`department_id`))) where (`d`.`name` in ('CAMARA','ENCAJADO','PALETIZADORES','PRODUCCION','SACADORES')) group by `wj`.`dated`,`d`.`name` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `lastIndicators`
--

/*!50001 DROP VIEW IF EXISTS `lastIndicators`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `lastIndicators` AS select `i`.`updated` AS `updated`,`i`.`lastYearSales` AS `lastYearSales`,(`i`.`lastYearSales` - `yi`.`lastYearSales`) AS `incLastYearSales`,`i`.`totalGreuge` AS `totalGreuge`,(`i`.`totalGreuge` - `yi`.`totalGreuge`) AS `incTotalGreuge`,`i`.`latePaymentRate` AS `latePaymentRate`,(`i`.`latePaymentRate` - `yi`.`latePaymentRate`) AS `incLatePaymentRate`,`i`.`countEmployee` AS `countEmployee`,(`i`.`countEmployee` - `yi`.`countEmployee`) AS `incCountEmployee`,`i`.`averageMana` AS `averageMana`,(`i`.`averageMana` - `yi`.`averageMana`) AS `incAverageMana`,`i`.`bankingPool` AS `bankingPool`,(`i`.`bankingPool` - `yi`.`bankingPool`) AS `incbankingPool`,`i`.`lastMonthActiveClients` AS `lastMonthActiveClients`,(`i`.`lastMonthActiveClients` - `yi`.`lastMonthActiveClients`) AS `incLastMonthActiveClients`,`i`.`lastMonthLostClients` AS `lastMonthLostClients`,(`i`.`lastMonthLostClients` - `yi`.`lastMonthLostClients`) AS `incLastMonthLostClients`,`i`.`lastMonthNewClients` AS `lastMonthNewClients`,(`i`.`lastMonthNewClients` - `yi`.`lastMonthNewClients`) AS `incLastMonthNewClients`,`i`.`lastMonthWebBuyingRate` AS `lastMonthWebBuyingRate`,(`i`.`lastMonthWebBuyingRate` - `yi`.`lastMonthWebBuyingRate`) AS `incLastMonthWebBuyingRate`,`i`.`productionHours` AS `productionHours`,`i`.`dailyWorkersCost` AS `dailyWorkersCost`,`i`.`volumeM3` AS `volumeM3`,`i`.`salesValue` AS `salesValue`,`i`.`valueM3` AS `valueM3`,`i`.`hoursM3` AS `hoursM3`,`i`.`workerCostM3` AS `workerCostM3`,`i`.`salesWorkersCostRate` AS `salesWorkersCostRate`,`i`.`thisWeekSales` AS `thisWeekSales`,`i`.`lastYearWeekSales` AS `lastYearWeekSales` from (`indicators` `i` join `indicators` `yi` on((`yi`.`updated` = (select (max(`indicators`.`updated`) + interval -(1) day) from `indicators`)))) where (`i`.`updated` = (select max(`indicators`.`updated`) from `indicators`)) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `m3Silla`
--

/*!50001 DROP VIEW IF EXISTS `m3Silla`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `m3Silla` AS select `m3`.`fecha` AS `fecha`,`m3`.`year` AS `year`,`m3`.`month` AS `month`,`m3`.`week` AS `week`,`m3`.`day` AS `day`,`m3`.`dayName` AS `dayName`,cast(sum(`m3`.`m3`) as decimal(10,0)) AS `Volumen`,cast(sum(`m3`.`euros`) as decimal(10,0)) AS `Euros` from `m3` where (`m3`.`warehouseFk` in (1,44)) group by `m3`.`fecha` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `m3analisis`
--

/*!50001 DROP VIEW IF EXISTS `m3analisis`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `m3analisis` AS select `m`.`fecha` AS `fecha`,`m`.`year` AS `year`,`m`.`month` AS `month`,`m`.`week` AS `week`,`m`.`day` AS `day`,`m`.`dayName` AS `dayName`,`m`.`Volumen` AS `Volumen`,`m`.`Euros` AS `Euros`,`h`.`Departamento` AS `Departamento`,`h`.`Horas` AS `Horas`,`h`.`Salarios` AS `Salarios`,(`h`.`Horas` / `m`.`Volumen`) AS `tiempoM3`,(`m`.`Euros` / `m`.`Volumen`) AS `valorM3`,(`h`.`Salarios` / `m`.`Volumen`) AS `costeLaboralM3`,(`h`.`Salarios` / `m`.`Euros`) AS `costeEuros`,(`h`.`Salarios` / `h`.`Horas`) AS `precioHora` from (`bs`.`m3Silla` `m` join `bs`.`horasSilla` `h` on((`h`.`Fecha` = `m`.`fecha`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `manaSpellersExcluded`
--

/*!50001 DROP VIEW IF EXISTS `manaSpellersExcluded`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `manaSpellersExcluded` AS select `m`.`Id_Trabajador` AS `workerFk` from `mana_spellers_excluded` `m` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `productionIndicators`
--

/*!50001 DROP VIEW IF EXISTS `productionIndicators`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `productionIndicators` AS select `wj`.`dated` AS `dated`,cast(sum((`wj`.`total` + `wj`.`lunch`)) as decimal(10,1)) AS `productionHours`,cast(sum(((`wj`.`total` + `wj`.`lunch`) * `wj`.`priceOrdinaryHour`)) as decimal(10,0)) AS `dailyWorkersCost`,`ms`.`Volumen` AS `VolumeM3`,`ms`.`Euros` AS `salesValue`,cast((`ms`.`Euros` / `ms`.`Volumen`) as decimal(10,0)) AS `valueM3`,cast((sum((`wj`.`total` + `wj`.`lunch`)) / `ms`.`Volumen`) as decimal(5,2)) AS `hoursM3`,`ms`.`dayName` AS `Dia`,cast((sum(((`wj`.`total` + `wj`.`lunch`) * `wj`.`priceOrdinaryHour`)) / `ms`.`Volumen`) as decimal(10,1)) AS `workerCostM3`,cast((sum(((`wj`.`total` + `wj`.`lunch`) * `wj`.`priceOrdinaryHour`)) / `ms`.`Euros`) as decimal(10,2)) AS `salesWorkersCostRate` from (((`vn`.`workerJourney` `wj` join `postgresql`.`business_labour` `bl` on((`bl`.`business_id` = `wj`.`businessFk`))) join `vn2008`.`department` `d` on((`d`.`department_id` = `bl`.`department_id`))) join `bs`.`m3Silla` `ms` on((`ms`.`fecha` = `wj`.`dated`))) where (`d`.`production` and (`wj`.`dated` >= '2017-01-01')) group by `wj`.`dated` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_ventas`
--

/*!50001 DROP VIEW IF EXISTS `v_ventas`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_ventas` AS select (`bs`.`ventas`.`importe` * `vn2008`.`Movimientos`.`Cantidad`) AS `importe`,`bs`.`ventas`.`recargo` AS `recargo`,`vn2008`.`time`.`year` AS `year`,`vn2008`.`time`.`month` AS `month`,`vn2008`.`time`.`week` AS `week`,`vn2008`.`time`.`day` AS `day` from ((`bs`.`ventas` join `vn2008`.`time` on((`vn2008`.`time`.`date` = `bs`.`ventas`.`fecha`))) join `vn2008`.`Movimientos` on((`bs`.`ventas`.`Id_Movimiento` = `vn2008`.`Movimientos`.`Id_Movimiento`))) group by `vn2008`.`time`.`date` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `workerMana`
--

/*!50001 DROP VIEW IF EXISTS `workerMana`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `workerMana` AS select `m`.`Id_Trabajador` AS `workerFk`,`m`.`used` AS `amount` from `mana_spellers` `m` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

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

USE `cache`;

--
-- Current Database: `edi`
--

USE `edi`;

--
-- Final view structure for view `ekt`
--

/*!50001 DROP VIEW IF EXISTS `ekt`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ekt` AS select `vn2008`.`buy_edi`.`id` AS `id`,`vn2008`.`buy_edi`.`barcode` AS `barcode`,`vn2008`.`buy_edi`.`entry_year` AS `entry_year`,`vn2008`.`buy_edi`.`delivery_number` AS `delivery_number`,`vn2008`.`buy_edi`.`fec` AS `fec`,`vn2008`.`buy_edi`.`hor` AS `hor`,`vn2008`.`buy_edi`.`now` AS `now`,`vn2008`.`buy_edi`.`ptj` AS `ptj`,`vn2008`.`buy_edi`.`ref` AS `ref`,`vn2008`.`buy_edi`.`item` AS `item`,`vn2008`.`buy_edi`.`pac` AS `pac`,`vn2008`.`buy_edi`.`qty` AS `qty`,`vn2008`.`buy_edi`.`ori` AS `ori`,`vn2008`.`buy_edi`.`cat` AS `cat`,`vn2008`.`buy_edi`.`agj` AS `agj`,`vn2008`.`buy_edi`.`kop` AS `kop`,`vn2008`.`buy_edi`.`ptd` AS `ptd`,`vn2008`.`buy_edi`.`sub` AS `sub`,`vn2008`.`buy_edi`.`pro` AS `pro`,`vn2008`.`buy_edi`.`pri` AS `pri`,`vn2008`.`buy_edi`.`package` AS `package`,`vn2008`.`buy_edi`.`auction` AS `auction`,`vn2008`.`buy_edi`.`klo` AS `klo`,`vn2008`.`buy_edi`.`k01` AS `k01`,`vn2008`.`buy_edi`.`k02` AS `k02`,`vn2008`.`buy_edi`.`k03` AS `k03`,`vn2008`.`buy_edi`.`k04` AS `k04`,`vn2008`.`buy_edi`.`s1` AS `s1`,`vn2008`.`buy_edi`.`s2` AS `s2`,`vn2008`.`buy_edi`.`s3` AS `s3`,`vn2008`.`buy_edi`.`s4` AS `s4`,`vn2008`.`buy_edi`.`s5` AS `s5`,`vn2008`.`buy_edi`.`s6` AS `s6`,`vn2008`.`buy_edi`.`ok` AS `ok`,`vn2008`.`buy_edi`.`trolley_id` AS `trolley_id`,`vn2008`.`buy_edi`.`scanned` AS `scanned` from `vn2008`.`buy_edi` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `supplyOffer`
--

/*!50001 DROP VIEW IF EXISTS `supplyOffer`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `supplyOffer` AS select `di`.`ID` AS `diId`,`sr`.`ID` AS `srId`,`sr`.`Item_ArticleCode` AS `Item_ArticleCode`,`sr`.`VBNOmschrijving` AS `product_name`,`s`.`company_name` AS `company_name`,`sr`.`Price` AS `Price`,`sr`.`Quality` AS `Quality`,`sr`.`s1` AS `s1`,`sr`.`s2` AS `s2`,`sr`.`s3` AS `s3`,`sr`.`s4` AS `s4`,`sr`.`s5` AS `s5`,`sr`.`s6` AS `s6`,`sr`.`NumberOfUnits` AS `NumberOfUnits`,`sr`.`EmbalageCode` AS `EmbalageCode`,`di`.`LatestDeliveryDateTime` AS `LatestDeliveryDateTime`,`di`.`EarliestDespatchDateTime` AS `EarliestDespatchDateTime`,`di`.`FirstOrderDateTime` AS `FirstOrderDateTime`,`di`.`LatestOrderDateTime` AS `LatestOrderDateTime`,`sr`.`NumberOfItemsPerCask` AS `NumberOfItemsPerCask`,`sr`.`NumberOfLayersPerTrolley` AS `NumberOfLayersPerTrolley`,`sr`.`MinimumNumberToOrder` AS `MinimumNumberToOrder`,`sr`.`MaximumNumberToOrder` AS `MaximumNumberToOrder`,`sr`.`IncrementalOrderableQuantity` AS `IncrementalOrderableQuantity`,`sr`.`PackingPrice` AS `PackingPrice`,`sr`.`MarketPlaceID` AS `MarketPlaceID`,`sr`.`PictureReference` AS `PictureReference`,`mp`.`name` AS `marketPlace`,cast((`sr`.`MinimumNumberToOrder` * (case `sr`.`MinimumOrderUnitType` when 1 then 1 when 2 then (`sr`.`NumberOfItemsPerCask` / `sr`.`NumberBunchesPerCask`) when 3 then `sr`.`NumberOfItemsPerCask` when 4 then (floor(((128 * 56) / (`c`.`X` * `c`.`Y`))) * `sr`.`NumberOfItemsPerCask`) when 5 then ((floor(((128 * 56) / (`c`.`X` * `c`.`Y`))) * `sr`.`NumberOfItemsPerCask`) * `sr`.`NumberOfLayersPerTrolley`) end)) as decimal(10,0)) AS `OrderUnit`,cast((`sr`.`IncrementalOrderableQuantity` * (case `sr`.`IncrementalOrderableQuantityType` when 1 then 1 when 2 then (`sr`.`NumberOfItemsPerCask` / `sr`.`NumberBunchesPerCask`) when 3 then `sr`.`NumberOfItemsPerCask` when 4 then (floor(((128 * 56) / (`c`.`X` * `c`.`Y`))) * `sr`.`NumberOfItemsPerCask`) when 5 then ((floor(((128 * 56) / (`c`.`X` * `c`.`Y`))) * `sr`.`NumberOfItemsPerCask`) * `sr`.`NumberOfLayersPerTrolley`) end)) as decimal(10,0)) AS `IncrementalOrderUnit` from ((((((`edi`.`deliveryInformation` `di` join `edi`.`supplyResponse` `sr` on((`sr`.`ID` = `di`.`supplyResponseID`))) join `edi`.`supplier` `s` on((`s`.`glnAddressCode` = `sr`.`SupplierGLN`))) join `edi`.`bucket` `b` on((`b`.`bucket_id` = `sr`.`EmbalageCode`))) join `edi`.`item` `i` on((`i`.`id` = `sr`.`Item_ArticleCode`))) join `vn2008`.`Cubos` `c` on((`c`.`Id_Cubo` = `sr`.`EmbalageCode`))) left join `edi`.`marketPlace` `mp` on((`mp`.`id` = `sr`.`MarketPlaceID`))) where ((`sr`.`NumberOfUnits` > 0) and (now() between `di`.`FirstOrderDateTime` and `di`.`LatestOrderDateTime`)) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Current Database: `hedera`
--

USE `hedera`;

--
-- Final view structure for view `mainAccountBank`
--

/*!50001 DROP VIEW IF EXISTS `mainAccountBank`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `mainAccountBank` AS select `e`.`name` AS `name`,`a`.`iban` AS `iban` from ((`hedera`.`mainAccount` `c` join `vn`.`supplierAccount` `a` on((`a`.`id` = `c`.`accountFk`))) join `vn`.`bankEntity` `e` on((`e`.`id` = `a`.`bankEntityFk`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `myAddress`
--

/*!50001 DROP VIEW IF EXISTS `myAddress`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `myAddress` AS select `t`.`id` AS `id`,`t`.`clientFk` AS `clientFk`,`t`.`street` AS `street`,`t`.`city` AS `city`,`t`.`postalCode` AS `postalCode`,`t`.`provinceFk` AS `provinceFk`,`t`.`nickname` AS `nickname`,`t`.`isDefaultAddress` AS `isDefaultAddress`,`t`.`isActive` AS `isActive`,`t`.`longitude` AS `longitude`,`t`.`latitude` AS `latitude`,`t`.`warehouseFk` AS `warehouseFk`,`t`.`agencyModeFk` AS `agencyModeFk` from `vn`.`address` `t` where (`t`.`clientFk` = `account`.`myUserGetId`()) */
/*!50002 WITH CASCADED CHECK OPTION */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `myBasket`
--

/*!50001 DROP VIEW IF EXISTS `myBasket`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8mb4 */;
/*!50001 SET character_set_results     = utf8mb4 */;
/*!50001 SET collation_connection      = utf8mb4_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `myBasket` AS select `o`.`id` AS `id`,`o`.`date_make` AS `made`,`o`.`date_send` AS `sent`,`o`.`customer_id` AS `clientFk`,`o`.`delivery_method_id` AS `deliveryMethodFk`,`o`.`agency_id` AS `agencyModeFk`,`o`.`address_id` AS `addressFk`,`o`.`company_id` AS `companyFk`,`o`.`note` AS `notes` from `hedera`.`order` `o` where (`o`.`id` = `MYBASKET_GETID`()) */
/*!50002 WITH CASCADED CHECK OPTION */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `myBasketDefaults`
--

/*!50001 DROP VIEW IF EXISTS `myBasketDefaults`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8mb4 */;
/*!50001 SET character_set_results     = utf8mb4 */;
/*!50001 SET collation_connection      = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `myBasketDefaults` AS select coalesce(`dm`.`code`,`cm`.`code`) AS `deliveryMethod`,coalesce(`ad`.`agencyModeFk`,`oc`.`defaultAgencyFk`) AS `agencyModeFk`,`c`.`defaultAddressFk` AS `addressFk`,`oc`.`defaultAgencyFk` AS `defaultAgencyFk` from ((((((`hedera`.`orderConfig` `oc` join `vn`.`agencyMode` `ca` on((`ca`.`id` = `oc`.`defaultAgencyFk`))) join `vn`.`deliveryMethod` `cm` on((`cm`.`id` = `ca`.`deliveryMethodFk`))) left join `vn`.`client` `c` on((`c`.`id` = `account`.`myUserGetId`()))) left join `vn`.`address` `ad` on((`ad`.`id` = `c`.`defaultAddressFk`))) left join `vn`.`agencyMode` `a` on((`a`.`id` = `ad`.`agencyModeFk`))) left join `vn`.`deliveryMethod` `dm` on((`dm`.`id` = `a`.`deliveryMethodFk`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `myBasketItem`
--

/*!50001 DROP VIEW IF EXISTS `myBasketItem`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8mb4 */;
/*!50001 SET character_set_results     = utf8mb4 */;
/*!50001 SET collation_connection      = utf8mb4_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `myBasketItem` AS select `r`.`id` AS `id`,`r`.`orderFk` AS `orderFk`,`r`.`warehouseFk` AS `warehouseFk`,`r`.`itemFk` AS `itemFk`,`r`.`amount` AS `amount`,`r`.`price` AS `price` from `hedera`.`orderRow` `r` where (`r`.`orderFk` = `MYBASKET_GETID`()) */
/*!50002 WITH CASCADED CHECK OPTION */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `myClient`
--

/*!50001 DROP VIEW IF EXISTS `myClient`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `myClient` AS select `c`.`id` AS `id`,`c`.`isToBeMailed` AS `isToBeMailed`,`c`.`defaultAddressFk` AS `defaultAddressFk`,`c`.`credit` AS `credit` from `vn`.`client` `c` where (`c`.`id` = `account`.`myUserGetId`()) */
/*!50002 WITH CASCADED CHECK OPTION */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `myInvoice`
--

/*!50001 DROP VIEW IF EXISTS `myInvoice`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8mb4 */;
/*!50001 SET character_set_results     = utf8mb4 */;
/*!50001 SET collation_connection      = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `myInvoice` AS select `i`.`id` AS `id`,`i`.`ref` AS `ref`,`i`.`issued` AS `issued`,`i`.`amount` AS `amount`,`i`.`pdf` AS `pdf` from `vn`.`invoiceOut` `i` where (`i`.`clientFk` = `account`.`myUserGetId`()) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `myMenu`
--

/*!50001 DROP VIEW IF EXISTS `myMenu`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `myMenu` AS select `t`.`id` AS `id`,`t`.`path` AS `path`,`t`.`description` AS `description`,`t`.`parentFk` AS `parentFk` from (`hedera`.`menu` `t` join `account`.`myRole` `r` on((`r`.`id` = `t`.`roleFk`))) order by `t`.`parentFk`,`t`.`displayOrder`,`t`.`id` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `myOrder`
--

/*!50001 DROP VIEW IF EXISTS `myOrder`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `myOrder` AS select `o`.`id` AS `id`,`o`.`date_send` AS `landed`,`o`.`customer_id` AS `clientFk`,`o`.`delivery_method_id` AS `deliveryMethodFk`,`o`.`agency_id` AS `agencyModeFk`,`o`.`address_id` AS `addressFk`,`o`.`company_id` AS `companyFk`,`o`.`note` AS `note`,`o`.`source_app` AS `sourceApp`,`o`.`confirmed` AS `isConfirmed`,`o`.`date_make` AS `created`,`o`.`first_row_stamp` AS `firstRowStamp`,`o`.`confirm_date` AS `confirmed` from `hedera`.`order` `o` where (`o`.`customer_id` = `account`.`myUserGetId`()) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `myOrderMyTicket`
--

/*!50001 DROP VIEW IF EXISTS `myOrderMyTicket`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `myOrderMyTicket` AS select `o`.`id` AS `orderFk`,`ot`.`ticketFk` AS `ticketFk` from (`hedera`.`myOrder` `o` join `hedera`.`orderTicket` `ot` on((`ot`.`orderFk` = `o`.`id`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `myOrderRow`
--

/*!50001 DROP VIEW IF EXISTS `myOrderRow`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `myOrderRow` AS select `orw`.`id` AS `id`,`orw`.`order_id` AS `Fk`,`orw`.`item_id` AS `itemFk`,`orw`.`warehouse_id` AS `warehouseFk`,`orw`.`shipment` AS `shipped`,`orw`.`amount` AS `amount`,`orw`.`price` AS `price`,`orw`.`rate` AS `rate`,`orw`.`created` AS `created`,`orw`.`Id_Movimiento` AS `saleFk` from (`hedera`.`order_row` `orw` join `hedera`.`myOrder` `o` on((`o`.`id` = `orw`.`order_id`))) */
/*!50002 WITH CASCADED CHECK OPTION */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `myTicket`
--

/*!50001 DROP VIEW IF EXISTS `myTicket`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `myTicket` AS select `t`.`id` AS `id`,`t`.`clientFk` AS `clientFk`,`t`.`warehouseFk` AS `warehouseFk`,`t`.`shipped` AS `shipped`,`t`.`landed` AS `landed`,`t`.`nickname` AS `nickname`,`t`.`agencyModeFk` AS `agencyModeFk`,`t`.`refFk` AS `refFk`,`t`.`addressFk` AS `addressFk`,`t`.`location` AS `location`,`t`.`companyFk` AS `companyFk` from `vn`.`ticket` `t` where (`t`.`clientFk` = `account`.`myUserGetId`()) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `myTicketRow`
--

/*!50001 DROP VIEW IF EXISTS `myTicketRow`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `myTicketRow` AS select `s`.`id` AS `id`,`s`.`itemFk` AS `itemFk`,`s`.`ticketFk` AS `ticketFk`,`s`.`concept` AS `concept`,`s`.`quantity` AS `quantity`,`s`.`price` AS `price`,`s`.`discount` AS `discount`,`s`.`reserved` AS `reserved`,`s`.`isPicked` AS `isPicked` from (`vn`.`sale` `s` join `hedera`.`myTicket` `t` on((`s`.`ticketFk` = `t`.`id`))) */
/*!50002 WITH CASCADED CHECK OPTION */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `myTicketState`
--

/*!50001 DROP VIEW IF EXISTS `myTicketState`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `myTicketState` AS select `t`.`id` AS `id`,`t`.`clientFk` AS `clientFk`,`t`.`warehouseFk` AS `warehouseFk`,`t`.`shipped` AS `shipped`,`t`.`landed` AS `landed`,`t`.`nickname` AS `nickname`,`t`.`agencyModeFk` AS `agencyModeFk`,`t`.`refFk` AS `refFk`,`t`.`addressFk` AS `addressFk`,`t`.`location` AS `location`,`t`.`companyFk` AS `companyFk`,`ts`.`alertLevel` AS `alertLevel`,`ts`.`code` AS `code` from (`vn`.`ticket` `t` left join `vn`.`ticketState` `ts` on((`ts`.`ticketFk` = `t`.`id`))) where (`t`.`clientFk` = `account`.`myUserGetId`()) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `myTpvTransaction`
--

/*!50001 DROP VIEW IF EXISTS `myTpvTransaction`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `myTpvTransaction` AS select `t`.`id` AS `id`,`t`.`merchantFk` AS `merchantFk`,`t`.`clientFk` AS `clientFk`,`t`.`receiptFk` AS `receiptFk`,`t`.`amount` AS `amount`,`t`.`response` AS `response`,`t`.`status` AS `status`,`t`.`created` AS `created` from `hedera`.`tpvTransaction` `t` where (`t`.`clientFk` = `account`.`myUserGetId`()) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `orderTicket`
--

/*!50001 DROP VIEW IF EXISTS `orderTicket`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `orderTicket` AS select `b`.`order_id` AS `orderFk`,`b`.`Id_Ticket` AS `ticketFk` from `vn2008`.`order_Tickets` `b` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `order_component`
--

/*!50001 DROP VIEW IF EXISTS `order_component`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `order_component` AS select `t`.`rowFk` AS `order_row_id`,`t`.`componentFk` AS `component_id`,`t`.`price` AS `price` from `orderRowComponent` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `order_row`
--

/*!50001 DROP VIEW IF EXISTS `order_row`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `order_row` AS select `t`.`id` AS `id`,`t`.`orderFk` AS `order_id`,`t`.`itemFk` AS `item_id`,`t`.`warehouseFk` AS `warehouse_id`,`t`.`shipment` AS `shipment`,`t`.`amount` AS `amount`,`t`.`price` AS `price`,`t`.`rate` AS `rate`,`t`.`created` AS `created`,`t`.`saleFk` AS `Id_Movimiento` from `orderRow` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Current Database: `nst`
--

USE `nst`;

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

USE `pbx`;

--
-- Final view structure for view `cdrConf`
--

/*!50001 DROP VIEW IF EXISTS `cdrConf`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `cdrConf` AS select `c`.`call_date` AS `calldate`,`c`.`clid` AS `clid`,`c`.`src` AS `src`,`c`.`dst` AS `dst`,`c`.`dcontext` AS `dcontext`,`c`.`channel` AS `channel`,`c`.`dst_channel` AS `dstchannel`,`c`.`last_app` AS `lastapp`,`c`.`last_data` AS `lastdata`,`c`.`duration` AS `duration`,`c`.`billsec` AS `billsec`,`c`.`disposition` AS `disposition`,`c`.`ama_flags` AS `amaflags`,`c`.`account_code` AS `accountcode`,`c`.`unique_id` AS `uniqueid`,`c`.`user_field` AS `userfield` from `cdr` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `followmeConf`
--

/*!50001 DROP VIEW IF EXISTS `followmeConf`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `followmeConf` AS select `f`.`extension` AS `name`,`c`.`music` AS `music`,`c`.`context` AS `context`,`c`.`takeCall` AS `takecall`,`c`.`declineCall` AS `declinecall` from (`followme` `f` join `followmeConfig` `c`) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `followmeNumberConf`
--

/*!50001 DROP VIEW IF EXISTS `followmeNumberConf`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `followmeNumberConf` AS select `f`.`extension` AS `name`,1 AS `ordinal`,`f`.`phone` AS `phonenumber`,`c`.`timeout` AS `timeout` from (`followme` `f` join `followmeConfig` `c`) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `queueConf`
--

/*!50001 DROP VIEW IF EXISTS `queueConf`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `queueConf` AS select `q`.`name` AS `name`,`c`.`strategy` AS `strategy`,`c`.`timeout` AS `timeout`,`c`.`retry` AS `retry`,`c`.`weight` AS `weight`,`c`.`maxLen` AS `maxlen`,`c`.`ringInUse` AS `ringinuse` from (`queue` `q` join `queueConfig` `c` on((`q`.`config` = `c`.`id`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `queueMemberConf`
--

/*!50001 DROP VIEW IF EXISTS `queueMemberConf`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8mb4 */;
/*!50001 SET character_set_results     = utf8mb4 */;
/*!50001 SET collation_connection      = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `queueMemberConf` AS select `m`.`id` AS `uniqueid`,`m`.`queue` AS `queue_name`,concat('SIP/',`m`.`extension`) AS `interface`,0 AS `paused` from `queueMember` `m` union all select `p`.`id` AS `id`,`p`.`queue` AS `queue`,concat('Local/',`p`.`phone`,'@outgoing') AS `phone`,0 AS `paused` from `queuePhone` `p` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `sipConf`
--

/*!50001 DROP VIEW IF EXISTS `sipConf`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8mb4 */;
/*!50001 SET character_set_results     = utf8mb4 */;
/*!50001 SET collation_connection      = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `sipConf` AS select `s`.`user_id` AS `id`,`s`.`extension` AS `name`,NULL AS `callbackextension`,`s`.`secret` AS `secret`,`s`.`caller_id` AS `callerid`,`c`.`host` AS `host`,`c`.`deny` AS `deny`,`c`.`permit` AS `permit`,`c`.`type` AS `type`,`c`.`context` AS `context`,`c`.`incomingLimit` AS `incominglimit`,`c`.`pickupGroup` AS `pickupgroup`,`c`.`careInvite` AS `careinvite`,`c`.`insecure` AS `insecure`,`r`.`ipAddr` AS `ipaddr`,`r`.`regSeconds` AS `regseconds`,`r`.`port` AS `port`,`r`.`defaultUser` AS `defaultuser`,`r`.`userAgent` AS `useragent`,`r`.`lastMs` AS `lastms`,`r`.`fullContact` AS `fullcontact`,`r`.`regServer` AS `regserver` from ((`sip` `s` left join `sipReg` `r` on((`s`.`user_id` = `r`.`userId`))) join `sipConfig` `c`) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Current Database: `postgresql`
--

USE `postgresql`;

--
-- Final view structure for view `currentWorkersStats`
--

/*!50001 DROP VIEW IF EXISTS `currentWorkersStats`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `currentWorkersStats` AS select `b`.`business_id` AS `business_id`,`p`.`sex` AS `sex`,`p`.`name` AS `name`,`p`.`firstname` AS `firstname`,`d`.`name` AS `department`,`pc`.`category_name` AS `category_name`,`pl`.`level_name` AS `level_name`,cast(((40 * `blp`.`importepactado`) / `clt`.`hours_week`) as decimal(10,2)) AS `salarioMedio` from ((((((((`postgresql`.`person` `p` join `postgresql`.`profile` `pr` on((`pr`.`person_id` = `p`.`person_id`))) join `postgresql`.`business` `b` on((`b`.`client_id` = `pr`.`profile_id`))) join `postgresql`.`business_labour` `bl` on((`bl`.`business_id` = `b`.`business_id`))) join `vn2008`.`department` `d` on((`d`.`department_id` = `bl`.`department_id`))) join `postgresql`.`professional_category` `pc` on((`pc`.`professional_category_id` = `bl`.`professional_category_id`))) join `postgresql`.`professional_levels` `pl` on((`pl`.`professional_levels_id` = `pc`.`professional_levels_id`))) join `postgresql`.`business_labour_payroll` `blp` on((`blp`.`business_id` = `b`.`business_id`))) join `postgresql`.`calendar_labour_type` `clt` on((`clt`.`calendar_labour_type_id` = `bl`.`calendar_labour_type_id`))) where ((`b`.`date_start` <= curdate()) and (ifnull(`b`.`date_end`,curdate()) >= curdate()) and (`b`.`provider_id` = 442)) order by `blp`.`importepactado` desc */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

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

USE `salix`;

--
-- Final view structure for view `Account`
--

/*!50001 DROP VIEW IF EXISTS `Account`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `Account` AS select `u`.`id` AS `id`,`u`.`name` AS `name`,`u`.`password` AS `password`,`u`.`role` AS `roleFk`,`u`.`active` AS `active`,`u`.`email` AS `email`,`u`.`created` AS `created`,`u`.`updated` AS `updated` from `account`.`user` `u` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `Role`
--

/*!50001 DROP VIEW IF EXISTS `Role`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `Role` AS select `r`.`id` AS `id`,`r`.`name` AS `name`,`r`.`description` AS `description`,`r`.`created` AS `created`,`r`.`modified` AS `modified` from `account`.`role` `r` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `RoleMapping`
--

/*!50001 DROP VIEW IF EXISTS `RoleMapping`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `RoleMapping` AS select ((`u`.`id` * 1000) + `r`.`inheritsFrom`) AS `id`,'USER' AS `principalType`,`u`.`id` AS `principalId`,`r`.`inheritsFrom` AS `roleId` from (`account`.`user` `u` join `account`.`roleRole` `r` on((`r`.`role` = `u`.`role`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Current Database: `stock`
--

USE `stock`;

--
-- Current Database: `util`
--

USE `util`;

--
-- Current Database: `vn`
--

USE `vn`;

--
-- Final view structure for view `absenceType`
--

/*!50001 DROP VIEW IF EXISTS `absenceType`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `absenceType` AS select `cs`.`calendar_state_id` AS `id`,`cs`.`type` AS `name`,`cs`.`rgb` AS `rgb` from `postgresql`.`calendar_state` `cs` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `accounting`
--

/*!50001 DROP VIEW IF EXISTS `accounting`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `accounting` AS select `b`.`Id_Banco` AS `id`,`b`.`Banco` AS `bank`,`b`.`Cuenta` AS `account`,`b`.`cash` AS `accountingTypeFk`,`b`.`entity_id` AS `entityFk`,`b`.`activo` AS `isActive` from `vn2008`.`Bancos` `b` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `address`
--

/*!50001 DROP VIEW IF EXISTS `address`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `address` AS select `t`.`id_consigna` AS `id`,`t`.`Id_cliente` AS `clientFk`,`t`.`domicilio` AS `street`,`t`.`poblacion` AS `city`,`t`.`codPostal` AS `postalCode`,`t`.`province_id` AS `provinceFk`,`t`.`telefono` AS `phone`,`t`.`movil` AS `mobile`,`t`.`consignatario` AS `nickname`,`t`.`predeterminada` AS `isDefaultAddress`,`t`.`longitude` AS `longitude`,`t`.`latitude` AS `latitude`,`t`.`warehouse_id` AS `warehouseFk`,`t`.`Id_Agencia` AS `agencyModeFk`,`t`.`isEqualizated` AS `isEqualizated`,`t`.`active` AS `isActive` from `vn2008`.`Consignatarios` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `addressObservation`
--

/*!50001 DROP VIEW IF EXISTS `addressObservation`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `addressObservation` AS select `co`.`consignatarios_observation_id` AS `id`,`co`.`Id_Consigna` AS `addressFk`,`co`.`observation_type_id` AS `observationTypeFk`,`co`.`text` AS `description` from `vn2008`.`consignatarios_observation` `co` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `agency`
--

/*!50001 DROP VIEW IF EXISTS `agency`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `agency` AS select `a`.`agency_id` AS `id`,`a`.`name` AS `name`,`a`.`warehouse_id` AS `warehouseFk`,`a`.`por_volumen` AS `isVolumetric`,`a`.`Id_Banco` AS `bankFk`,`a`.`warehouse_alias_id` AS `warehouseAliasFk`,`a`.`propios` AS `isOwn`,`a`.`zone_label` AS `labelZone` from `vn2008`.`agency` `a` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `agencyHour`
--

/*!50001 DROP VIEW IF EXISTS `agencyHour`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `agencyHour` AS select `h`.`agency_hour_id` AS `id`,`h`.`agency_id` AS `agencyFk`,`h`.`week_day` AS `weekDay`,`h`.`warehouse_id` AS `warehouseFk`,`h`.`province_id` AS `provinceFk`,`h`.`subtract_day` AS `substractDay`,`h`.`max_hour` AS `maxHour` from `vn2008`.`agency_hour` `h` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `agencyMode`
--

/*!50001 DROP VIEW IF EXISTS `agencyMode`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `agencyMode` AS select `a`.`Id_Agencia` AS `id`,`a`.`Agencia` AS `name`,`a`.`description` AS `description`,`a`.`Vista` AS `deliveryMethodFk`,`a`.`m3` AS `m3`,`a`.`cod71` AS `cod71`,`a`.`web` AS `web`,`a`.`agency_id` AS `agencyFk`,`a`.`agency_service_id` AS `agencyServiceFk`,`a`.`inflacion` AS `inflation`,`a`.`is_volumetric` AS `isVolumetric`,`a`.`send_mail` AS `reportMail`,`a`.`tpv` AS `isActive`,`a`.`code` AS `code` from `vn2008`.`Agencias` `a` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `agencyModeZone`
--

/*!50001 DROP VIEW IF EXISTS `agencyModeZone`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `agencyModeZone` AS select `a`.`Id_Agencia` AS `agencyModeFk`,`a`.`zona` AS `zone`,`a`.`price` AS `price`,`a`.`Id_Article` AS `itemFk`,`a`.`warehouse_id` AS `warehouseFk`,`a`.`porte_minimo` AS `minimCost`,`a`.`inflacion` AS `inflation` from `vn2008`.`Agencias_zonas` `a` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `agencyProvince`
--

/*!50001 DROP VIEW IF EXISTS `agencyProvince`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `agencyProvince` AS select `a`.`province_id` AS `provinceFk`,`a`.`agency_id` AS `agencyFk`,`a`.`zona` AS `zone`,`a`.`warehouse_id` AS `warehouseFk`,`a`.`isVolumetric` AS `isVolumetric` from `vn2008`.`Agencias_province` `a` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `agencyWarehouse`
--

/*!50001 DROP VIEW IF EXISTS `agencyWarehouse`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `agencyWarehouse` AS select `a`.`agency_id` AS `agencyFk`,`a`.`warehouse_id` AS `warehouseFk`,`a`.`Vista` AS `agencyType` from `vn2008`.`agency_warehouse` `a` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `agencyWeekDayBonus`
--

/*!50001 DROP VIEW IF EXISTS `agencyWeekDayBonus`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `agencyWeekDayBonus` AS select `a`.`id` AS `id`,`a`.`warehouse_id` AS `warehouseFk`,`a`.`agency_id` AS `agencyFk`,`a`.`weekDay` AS `weekDay`,`a`.`zona` AS `zone`,`a`.`bonus` AS `bonus` from `vn2008`.`agency_weekday_bonus` `a` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `annualAverageInvoiced`
--

/*!50001 DROP VIEW IF EXISTS `annualAverageInvoiced`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `annualAverageInvoiced` AS select `e`.`Id_Cliente` AS `clientFk`,`e`.`Consumo` AS `invoiced` from `bi`.`facturacion_media_anual` `e` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `awb`
--

/*!50001 DROP VIEW IF EXISTS `awb`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `awb` AS select `a`.`id` AS `id`,`a`.`codigo` AS `code`,`a`.`bultos` AS `package`,`a`.`peso` AS `weight`,`a`.`MYSQL_TIME` AS `created`,`a`.`transitario_id` AS `transitoryFk`,`a`.`iva_id` AS `taxFk`,`a`.`gestdoc_id` AS `docFk`,`a`.`importe` AS `amount`,`a`.`carguera_id` AS `freightFk`,`a`.`m3` AS `m3`,`a`.`stems` AS `stems`,`a`.`flight_id` AS `flightFk`,`a`.`volume_weight` AS `volumeWeight`,`a`.`hb` AS `hb`,`a`.`rate` AS `rate`,`a`.`booked` AS `booked`,`a`.`issued` AS `issued`,`a`.`operated` AS `operated`,`a`.`bookEntried` AS `bookEntried`,`a`.`invoiceInFk` AS `invoiceInFk`,`a`.`isChecked` AS `isChecked` from `vn2008`.`awb` `a` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `bank`
--

/*!50001 DROP VIEW IF EXISTS `bank`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `bank` AS select `b`.`Id_Banco` AS `id`,`b`.`Banco` AS `bank`,`b`.`Cuenta` AS `account`,`b`.`cash` AS `cash`,`b`.`entity_id` AS `entityFk`,`b`.`activo` AS `isActive`,`b`.`currencyFk` AS `currencyFk` from `vn2008`.`Bancos` `b` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `bankEntity`
--

/*!50001 DROP VIEW IF EXISTS `bankEntity`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `bankEntity` AS select `e`.`entity_id` AS `id`,`e`.`pais_id` AS `countryFk`,`e`.`description` AS `name`,`e`.`bic` AS `bic` from `vn2008`.`entity` `e` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `botanicExport`
--

/*!50001 DROP VIEW IF EXISTS `botanicExport`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `botanicExport` AS select `be`.`botanic_export_id` AS `id`,`be`.`edi_genus_id` AS `ediGenusFk`,`be`.`edi_specie_id` AS `ediSpecieFk`,`be`.`Id_Paises` AS `countryFk`,`be`.`restriction` AS `restriction`,`be`.`description` AS `description`,`be`.`isProtectedZone` AS `isProtectedZone` from `vn2008`.`botanic_export` `be` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `businessReasonEnd`
--

/*!50001 DROP VIEW IF EXISTS `businessReasonEnd`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `businessReasonEnd` AS select `b`.`id` AS `id`,`b`.`reason` AS `reason` from `vn2008`.`businessReasonEnd` `b` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `buy`
--

/*!50001 DROP VIEW IF EXISTS `buy`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `buy` AS select `c`.`Id_Compra` AS `id`,`c`.`Id_Entrada` AS `entryFk`,`c`.`Id_Article` AS `itemFk`,`c`.`Costefijo` AS `buyingValue`,`c`.`Cantidad` AS `quantity`,`c`.`Id_Cubo` AS `packageFk`,`c`.`Etiquetas` AS `stickers`,`c`.`Portefijo` AS `freightValue`,`c`.`Embalajefijo` AS `packageValue`,`c`.`Comisionfija` AS `comissionValue`,`c`.`Packing` AS `packing`,`c`.`grouping` AS `grouping`,`c`.`caja` AS `groupingMode`,`c`.`Nicho` AS `location`,`c`.`Tarifa1` AS `price1`,`c`.`Tarifa2` AS `price2`,`c`.`Tarifa3` AS `price3`,`c`.`PVP` AS `minPrice`,`c`.`Productor` AS `producer`,`c`.`Vida` AS `printedStickers`,`c`.`punteo` AS `isChecked`,`c`.`buy_edi_id` AS `ektFk`,`c`.`odbc_date` AS `created`,`c`.`Novincular` AS `isIgnored`,`c`.`isPickedOff` AS `isPickedOff` from `vn2008`.`Compres` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `city`
--

/*!50001 DROP VIEW IF EXISTS `city`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `city` AS select `c`.`city_id` AS `id`,`c`.`name` AS `name`,`c`.`province_id` AS `provinceFk` from `vn2008`.`city` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `claim`
--

/*!50001 DROP VIEW IF EXISTS `claim`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `claim` AS select `c`.`id` AS `id`,`c`.`Fecha` AS `ticketCreated`,`c`.`cl_est_id` AS `claimStateFk`,`c`.`notas` AS `observation`,`c`.`Id_Cliente` AS `clientFk`,`c`.`Id_Trabajador` AS `workerFk`,`c`.`sensib` AS `responsibility`,`c`.`mana` AS `isChargedToMana`,`c`.`ticketFk` AS `ticketFk`,`c`.`odbc_date` AS `created` from `vn2008`.`cl_main` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `claimBeginning`
--

/*!50001 DROP VIEW IF EXISTS `claimBeginning`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `claimBeginning` AS select `c`.`id` AS `id`,`c`.`cl_main_id` AS `claimFk`,`c`.`Id_Movimiento` AS `saleFk`,`c`.`numero` AS `quantity` from `vn2008`.`cl_det` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `claimDestination`
--

/*!50001 DROP VIEW IF EXISTS `claimDestination`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `claimDestination` AS select `c`.`id` AS `id`,`c`.`solucion` AS `description`,`c`.`addressFk` AS `addressFk` from `vn2008`.`cl_sol` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `claimDevelopment`
--

/*!50001 DROP VIEW IF EXISTS `claimDevelopment`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `claimDevelopment` AS select `c`.`id` AS `id`,`c`.`cl_main_id` AS `claimFk`,`c`.`cl_res_id` AS `claimResponsibleFk`,`c`.`Id_Trabajador` AS `workerFk`,`c`.`cl_mot_id` AS `claimReasonFk`,`c`.`cl_con_id` AS `claimResultFk`,`c`.`cl_dev` AS `claimRedeliveryFk`,`c`.`cl_sol` AS `claimDestinationFk` from `vn2008`.`cl_cau` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `claimEnd`
--

/*!50001 DROP VIEW IF EXISTS `claimEnd`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `claimEnd` AS select `c`.`id` AS `id`,`c`.`Id_Movimiento` AS `saleFk`,`c`.`cl_main_id` AS `claimFk`,`c`.`Id_Trabajador` AS `workerFk`,`c`.`cl_sol_id` AS `claimDestinationFk` from `vn2008`.`cl_act` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `claimRatio`
--

/*!50001 DROP VIEW IF EXISTS `claimRatio`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `claimRatio` AS select `bi`.`claims_ratio`.`Id_Cliente` AS `clientFk`,`bi`.`claims_ratio`.`Consumo` AS `yearSale`,`bi`.`claims_ratio`.`Reclamaciones` AS `claimAmount`,`bi`.`claims_ratio`.`Ratio` AS `claimingRate`,`bi`.`claims_ratio`.`recobro` AS `priceIncreasing`,`bi`.`claims_ratio`.`inflacion` AS `packingRate` from `bi`.`claims_ratio` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `claimReason`
--

/*!50001 DROP VIEW IF EXISTS `claimReason`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `claimReason` AS select `c`.`id` AS `id`,`c`.`motivo` AS `description` from `vn2008`.`cl_mot` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `claimRedelivery`
--

/*!50001 DROP VIEW IF EXISTS `claimRedelivery`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `claimRedelivery` AS select `e`.`id` AS `id`,`e`.`devolucion` AS `description` from `vn2008`.`cl_dev` `e` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `claimResponsible`
--

/*!50001 DROP VIEW IF EXISTS `claimResponsible`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `claimResponsible` AS select `c`.`id` AS `id`,`c`.`responsable` AS `description`,`c`.`sensibility` AS `responsability` from `vn2008`.`cl_res` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `claimResult`
--

/*!50001 DROP VIEW IF EXISTS `claimResult`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `claimResult` AS select `c`.`id` AS `id`,`c`.`consecuencia` AS `description` from `vn2008`.`cl_con` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `claimState`
--

/*!50001 DROP VIEW IF EXISTS `claimState`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `claimState` AS select `c`.`id` AS `id`,`c`.`estado` AS `description` from `vn2008`.`cl_est` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `client`
--

/*!50001 DROP VIEW IF EXISTS `client`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `client` AS select `c`.`id_cliente` AS `id`,`c`.`cliente` AS `name`,`c`.`if` AS `fi`,`c`.`razonSocial` AS `socialName`,`c`.`contacto` AS `contact`,`c`.`domicilio` AS `street`,`c`.`poblacion` AS `city`,`c`.`codPostal` AS `postcode`,`c`.`telefono` AS `phone`,`c`.`movil` AS `mobile`,`c`.`fax` AS `fax`,`c`.`real` AS `isRelevant`,`c`.`e-mail` AS `email`,`c`.`iban` AS `iban`,`c`.`vencimiento` AS `dueDay`,`c`.`Cuenta` AS `accountingAccount`,`c`.`RE` AS `isEqualizated`,`c`.`province_id` AS `provinceFk`,`c`.`invoice` AS `hasToInvoice`,`c`.`credito` AS `credit`,`c`.`Id_Pais` AS `countryFk`,`c`.`activo` AS `isActive`,`c`.`gestdoc_id` AS `gestdocFk`,`c`.`calidad` AS `quality`,`c`.`pay_met_id` AS `payMethodFk`,`c`.`created` AS `created`,`c`.`mail` AS `isToBeMailed`,`c`.`chanel_id` AS `contactChannelFk`,`c`.`sepaVnl` AS `hasSepaVnl`,`c`.`coreVnl` AS `hasCoreVnl`,`c`.`coreVnh` AS `hasCoreVnh`,`c`.`hasLcr` AS `hasLcr`,`c`.`default_address` AS `defaultAddressFk`,`c`.`risk_calculated` AS `riskCalculated`,`c`.`clientes_tipo_id` AS `clientTypeFk`,`c`.`mail_address` AS `mailAddress`,`c`.`cplusTerIdNifFk` AS `cplusTerIdNifFk`,`c`.`invoiceByAddress` AS `hasToInvoiceByAddress`,`c`.`contabilizado` AS `isTaxDataChecked`,`c`.`congelado` AS `isFreezed`,`c`.`creditInsurance` AS `creditInsurance`,`c`.`isCreatedAsServed` AS `isCreatedAsServed`,`c`.`hasInvoiceSimplified` AS `hasInvoiceSimplified`,`c`.`Id_Trabajador` AS `salesPersonFk`,`c`.`vies` AS `isVies`,`c`.`EYPBC` AS `eypbc`,`c`.`bankEntityFk` AS `bankEntityFk`,`c`.`typeFk` AS `typeFk` from `vn2008`.`Clientes` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `clientCredit`
--

/*!50001 DROP VIEW IF EXISTS `clientCredit`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `clientCredit` AS select `c`.`id` AS `id`,`c`.`Id_Cliente` AS `clientFk`,`c`.`Id_Trabajador` AS `workerFk`,`c`.`amount` AS `amount`,`c`.`odbc_date` AS `created` from `vn2008`.`credit` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `clientDefaultCompany`
--

/*!50001 DROP VIEW IF EXISTS `clientDefaultCompany`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `clientDefaultCompany` AS select `t`.`Id_Clientes_empresa` AS `id`,`t`.`Id_Cliente` AS `clientFk`,`t`.`empresa_id` AS `companyFk`,`t`.`fecha_ini` AS `started`,`t`.`fecha_fin` AS `finished` from `vn2008`.`Clientes_empresa` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `clientManaCache`
--

/*!50001 DROP VIEW IF EXISTS `clientManaCache`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `clientManaCache` AS select `mc`.`Id_Cliente` AS `clientFk`,`mc`.`Mana` AS `mana`,`mc`.`dated` AS `dated` from `bs`.`manaCustomer` `mc` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `clientObservation`
--

/*!50001 DROP VIEW IF EXISTS `clientObservation`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `clientObservation` AS select `t`.`client_observation_id` AS `id`,`t`.`Id_Cliente` AS `clientFk`,`t`.`Id_Trabajador` AS `workerFk`,`t`.`text` AS `text`,`t`.`odbc_date` AS `created` from `vn2008`.`client_observation` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `clientRisk`
--

/*!50001 DROP VIEW IF EXISTS `clientRisk`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `clientRisk` AS select `c`.`customer_id` AS `clientFk`,`c`.`company_id` AS `companyFk`,`c`.`amount` AS `amount` from `bi`.`customer_risk` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `clientSample`
--

/*!50001 DROP VIEW IF EXISTS `clientSample`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `clientSample` AS select `e`.`id` AS `id`,`e`.`Id_Cliente` AS `clientFk`,`e`.`escritos_id` AS `typeFk`,`e`.`fecha` AS `created`,`e`.`Id_Trabajador` AS `workerFk`,`e`.`userFk` AS `userFk`,`e`.`empresa_id` AS `companyFk` from `vn2008`.`escritos_det` `e` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `clientType`
--

/*!50001 DROP VIEW IF EXISTS `clientType`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `clientType` AS select `ct`.`clientes_tipo_id` AS `id`,`ct`.`code` AS `code`,`ct`.`tipo` AS `type`,`ct`.`isCreatedAsServed` AS `isCreatedAsServed` from `vn2008`.`clientes_tipo` `ct` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `color`
--

/*!50001 DROP VIEW IF EXISTS `color`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `color` AS select `c`.`Id_Color` AS `id`,`c`.`Color` AS `name` from `vn2008`.`Colores` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `company`
--

/*!50001 DROP VIEW IF EXISTS `company`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `company` AS select `e`.`id` AS `id`,`e`.`abbreviation` AS `code`,`e`.`Id_Proveedores_account` AS `supplierAccountFk`,`e`.`gerente_id` AS `workerManagerFk`,`e`.`digito_factura` AS `sage200Company`,`e`.`footnotes` AS `footnotes`,`e`.`phytosanitary` AS `phytosanitary`,`e`.`CodigoEmpresa` AS `companyCode`,`e`.`morosidad` AS `isDefaulter`,`e`.`baja` AS `expired` from `vn2008`.`empresa` `e` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `comparative`
--

/*!50001 DROP VIEW IF EXISTS `comparative`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `comparative` AS select `c`.`Periodo` AS `timePeriod`,`c`.`Id_Article` AS `itemFk`,`c`.`warehouse_id` AS `warehouseFk`,`c`.`Cantidad` AS `quantity`,`c`.`price` AS `price` from `vn2008`.`Comparativa` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `comparativeFilter`
--

/*!50001 DROP VIEW IF EXISTS `comparativeFilter`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `comparativeFilter` AS select `f`.`id` AS `id`,`f`.`name` AS `name`,`f`.`sql` AS `whereSql` from `vn2008`.`filtros` `f` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `componentRate`
--

/*!50001 DROP VIEW IF EXISTS `componentRate`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `componentRate` AS select `t`.`Id_Componente` AS `id`,`t`.`Componente` AS `name`,`t`.`tarifa_componentes_series_id` AS `componentTypeRate`,`t`.`tarifa_class` AS `classRate`,`t`.`tax` AS `tax`,`t`.`is_renewable` AS `isRenewable` from `bi`.`tarifa_componentes` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `componentTypeRate`
--

/*!50001 DROP VIEW IF EXISTS `componentTypeRate`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `componentTypeRate` AS select `t`.`tarifa_componentes_series_id` AS `id`,`t`.`Serie` AS `type`,`t`.`base` AS `base` from `bi`.`tarifa_componentes_series` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `contactChannel`
--

/*!50001 DROP VIEW IF EXISTS `contactChannel`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `contactChannel` AS select `c`.`chanel_id` AS `id`,`c`.`name` AS `name` from `vn2008`.`chanel` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `coolerPath`
--

/*!50001 DROP VIEW IF EXISTS `coolerPath`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `coolerPath` AS select `c`.`cooler_path_id` AS `id`,`c`.`description` AS `description` from `vn2008`.`cooler_path` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `coolerPathDetail`
--

/*!50001 DROP VIEW IF EXISTS `coolerPathDetail`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `coolerPathDetail` AS select `c`.`cooler_path_detail_id` AS `id`,`c`.`cooler_path_id` AS `coolerPathFk`,`c`.`pasillo` AS `hallway` from `vn2008`.`cooler_path_detail` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `country`
--

/*!50001 DROP VIEW IF EXISTS `country`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `country` AS select `p`.`Id` AS `id`,`p`.`Pais` AS `country`,`p`.`CEE` AS `CEE`,`p`.`isUeeMember` AS `isUeeMember`,`p`.`Codigo` AS `code`,`p`.`Id_Moneda` AS `currencyFk`,`p`.`Id_Paisreal` AS `politicalCountryFk`,`p`.`geoFk` AS `geoFk` from `vn2008`.`Paises` `p` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `currency`
--

/*!50001 DROP VIEW IF EXISTS `currency`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `currency` AS select `m`.`Id_Moneda` AS `id`,`m`.`Moneda` AS `code`,`m`.`Descripcion` AS `name` from `vn2008`.`Monedas` `m` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `defaulter`
--

/*!50001 DROP VIEW IF EXISTS `defaulter`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `defaulter` AS select `d`.`client` AS `clientFk`,`d`.`date` AS `created`,`d`.`amount` AS `amount`,`d`.`defaulterSince` AS `defaulterSinced`,`d`.`hasChanged` AS `hasChanged` from `bi`.`defaulters` `d` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `deliveryMethod`
--

/*!50001 DROP VIEW IF EXISTS `deliveryMethod`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `deliveryMethod` AS select `d`.`vista_id` AS `id`,`d`.`code` AS `code`,`d`.`vista` AS `description` from `vn2008`.`Vistas` `d` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `department`
--

/*!50001 DROP VIEW IF EXISTS `department`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `department` AS select `b`.`department_id` AS `id`,`b`.`name` AS `name`,`b`.`father_id` AS `fatherFk`,`b`.`production` AS `isProduction`,`b`.`lft` AS `lft`,`b`.`rgt` AS `rgt`,`b`.`isSelected` AS `isSelected`,`b`.`depth` AS `depth`,`b`.`sons` AS `sons` from `vn2008`.`department` `b` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `departmentTree`
--

/*!50001 DROP VIEW IF EXISTS `departmentTree`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `departmentTree` AS select `node`.`id` AS `id`,concat(repeat(repeat(' ',5),(count(`parent`.`id`) - 1)),`node`.`name`) AS `dep` from (`vn`.`department` `node` join `vn`.`department` `parent`) where (`node`.`lft` between `parent`.`lft` and `parent`.`rgt`) group by `node`.`id` order by `node`.`lft` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `dms`
--

/*!50001 DROP VIEW IF EXISTS `dms`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `dms` AS select `g`.`id` AS `id`,`g`.`gesttip_id` AS `dmsTypeFk`,`g`.`file` AS `file`,`g`.`trabajador_id` AS `workerFk`,`g`.`warehouse_id` AS `warehouseFk`,`g`.`emp_id` AS `companyFk`,`g`.`orden` AS `priority`,`g`.`file` AS `hasFile`,`g`.`sref` AS `reference`,`g`.`brief` AS `description`,`g`.`odbc_date` AS `created` from `vn2008`.`gestdoc` `g` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `dmsType`
--

/*!50001 DROP VIEW IF EXISTS `dmsType`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `dmsType` AS select `g`.`id` AS `id`,`g`.`tipo` AS `name`,`g`.`path` AS `path`,`g`.`readRoleFk` AS `readRoleFk`,`g`.`writeRoleFk` AS `writeRoleFk` from `vn2008`.`gesttip` `g` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `doc`
--

/*!50001 DROP VIEW IF EXISTS `doc`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `doc` AS select `g`.`id` AS `id`,`g`.`sref` AS `sref`,`g`.`brief` AS `brief`,`g`.`emp_id` AS `companyFk`,`g`.`orden` AS `order`,`g`.`file` AS `file`,`g`.`original` AS `original`,`g`.`trabajador_id` AS `workerFk`,`g`.`odbc_date` AS `created`,`g`.`warehouse_id` AS `warehouseFk` from `vn2008`.`gestdoc` `g` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `ediGenus`
--

/*!50001 DROP VIEW IF EXISTS `ediGenus`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ediGenus` AS select `g`.`genus_id` AS `id`,`g`.`latin_genus_name` AS `latinGenusName`,`g`.`entry_date` AS `entried`,`g`.`expiry_date` AS `dued`,`g`.`change_date_time` AS `modified` from `edi`.`genus` `g` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `ediSpecie`
--

/*!50001 DROP VIEW IF EXISTS `ediSpecie`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ediSpecie` AS select `s`.`specie_id` AS `id`,`s`.`genus_id` AS `genusFk`,`s`.`latin_species_name` AS `latinSpeciesName`,`s`.`entry_date` AS `entried`,`s`.`expiry_date` AS `dued`,`s`.`change_date_time` AS `modified` from `edi`.`specie` `s` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `entity`
--

/*!50001 DROP VIEW IF EXISTS `entity`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `entity` AS select `e`.`entity_id` AS `id`,`e`.`description` AS `description`,`e`.`pais_id` AS `countryFk`,`e`.`bic` AS `bic` from `vn2008`.`entity` `e` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `entry`
--

/*!50001 DROP VIEW IF EXISTS `entry`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `entry` AS select `e`.`Id_Entrada` AS `id`,`e`.`Id_Proveedor` AS `supplierFk`,`e`.`Referencia` AS `ref`,`e`.`Inventario` AS `isInventory`,`e`.`Confirmada` AS `isConfirmed`,`e`.`Pedida` AS `isOrdered`,`e`.`Redada` AS `isRaid`,`e`.`comision` AS `commission`,`e`.`odbc_date` AS `created`,`e`.`Notas_Eva` AS `evaNotes`,`e`.`travel_id` AS `travelFk`,`e`.`Id_Moneda` AS `currencyFk`,`e`.`empresa_id` AS `companyFk`,`e`.`gestdoc_id` AS `gestDocFk`,`e`.`recibida_id` AS `invoiceInFk` from `vn2008`.`Entradas` `e` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `especialPrice`
--

/*!50001 DROP VIEW IF EXISTS `especialPrice`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `especialPrice` AS select `p`.`Id_PrecioEspecial` AS `id`,`p`.`Id_Cliente` AS `clientFk`,`p`.`Id_Article` AS `itemFk`,`p`.`PrecioEspecial` AS `value` from `vn2008`.`PreciosEspeciales` `p` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `exchangeInsurance`
--

/*!50001 DROP VIEW IF EXISTS `exchangeInsurance`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `exchangeInsurance` AS select `vn2008`.`pago_sdc`.`pago_sdc_id` AS `id`,`vn2008`.`pago_sdc`.`importe` AS `amount`,`vn2008`.`pago_sdc`.`fecha` AS `dated`,`vn2008`.`pago_sdc`.`vencimiento` AS `finished`,`vn2008`.`pago_sdc`.`entity_id` AS `entityFk`,`vn2008`.`pago_sdc`.`ref` AS `ref`,`vn2008`.`pago_sdc`.`rate` AS `rate`,`vn2008`.`pago_sdc`.`empresa_id` AS `companyFk`,`vn2008`.`pago_sdc`.`financialProductTypefk` AS `financialProductTypefk`,`vn2008`.`pago_sdc`.`upperBarrier` AS `upperBarrier`,`vn2008`.`pago_sdc`.`lowerBarrier` AS `lowerBarrier`,`vn2008`.`pago_sdc`.`strike` AS `strike` from `vn2008`.`pago_sdc` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `exchangeInsuranceEntry`
--

/*!50001 DROP VIEW IF EXISTS `exchangeInsuranceEntry`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `exchangeInsuranceEntry` AS select max(`tr`.`landed`) AS `dated`,cast(sum(((`b`.`buyingValue` + `b`.`freightValue`) * `b`.`quantity`)) as decimal(10,2)) AS `Dolares`,cast((sum(((`b`.`buyingValue` + `b`.`freightValue`) * `b`.`quantity`)) / sum(((((100 + `e`.`commission`) / 100) * (`b`.`buyingValue` + `b`.`freightValue`)) * `b`.`quantity`))) as decimal(10,4)) AS `rate` from ((`vn`.`entry` `e` join `vn`.`buy` `b` on((`e`.`id` = `b`.`entryFk`))) join `vn`.`travel` `tr` on((`tr`.`id` = `e`.`travelFk`))) where ((`tr`.`landed` between '2016-01-31' and curdate()) and (`e`.`commission` < 0) and (`e`.`currencyFk` = 2)) group by month(`tr`.`landed`),year(`tr`.`landed`) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `exchangeInsuranceIn`
--

/*!50001 DROP VIEW IF EXISTS `exchangeInsuranceIn`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `exchangeInsuranceIn` AS select `exchangeInsuranceInPrevious`.`dated` AS `dated`,sum(`exchangeInsuranceInPrevious`.`amount`) AS `amount`,cast((sum((`exchangeInsuranceInPrevious`.`amount` * `exchangeInsuranceInPrevious`.`rate`)) / sum(`exchangeInsuranceInPrevious`.`amount`)) as decimal(10,4)) AS `rate` from `vn`.`exchangeInsuranceInPrevious` group by `exchangeInsuranceInPrevious`.`dated` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `exchangeInsuranceInPrevious`
--

/*!50001 DROP VIEW IF EXISTS `exchangeInsuranceInPrevious`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `exchangeInsuranceInPrevious` AS select `ei`.`finished` AS `dated`,`ei`.`amount` AS `amount`,`ei`.`rate` AS `rate` from `vn`.`exchangeInsurance` `ei` where (`ei`.`amount` and (`ei`.`financialProductTypefk` = 'SC')) union all select `ei`.`finished` AS `vencimiento`,`ard`.`amount` AS `amount`,`ei`.`rate` AS `rate` from ((`vn2008`.`accumulatorsReadingDate` `ard` join `vn`.`exchangeInsurance` `ei` on((`ei`.`id` = `ard`.`pagoSdcfk`))) join `vn2008`.`financialProductType` `fpt` on((`fpt`.`id` = `ei`.`financialProductTypefk`))) where (`ard`.`amount` and `fpt`.`isAcumulattor`) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `exchangeInsuranceOut`
--

/*!50001 DROP VIEW IF EXISTS `exchangeInsuranceOut`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `exchangeInsuranceOut` AS select `p`.`received` AS `received`,sum(`p`.`divisa`) AS `divisa`,(sum(`p`.`divisa`) / sum(`p`.`amount`)) AS `rate` from (`vn`.`payment` `p` join `vn`.`bank` `b` on((`b`.`id` = `p`.`bankFk`))) where ((`p`.`currencyFk` = 2) and (`b`.`cash` = 0) and (`p`.`supplierFk` <> 2213)) group by `p`.`received` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `exchangeReportSource`
--

/*!50001 DROP VIEW IF EXISTS `exchangeReportSource`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `exchangeReportSource` AS select `e`.`dated` AS `dated`,cast(sum(`e`.`amountIn`) as decimal(10,2)) AS `amountIn`,cast(sum(`e`.`rateIn`) as decimal(10,4)) AS `rateIn`,cast(sum(`e`.`amountOut`) as decimal(10,2)) AS `amountOut`,cast(sum(`e`.`rateOut`) as decimal(10,4)) AS `rateOut`,cast(sum(`e`.`amountEntry`) as decimal(10,2)) AS `amountEntry`,cast(sum(`e`.`rateEntry`) as decimal(10,4)) AS `rateEntry`,cast(ifnull(`rr`.`value`,`rrc`.`simulatedValue`) as decimal(10,4)) AS `rateECB` from ((`vn`.`exchangeReportSourcePrevious` `e` left join `vn`.`referenceRate` `rr` on((`rr`.`dated` = `e`.`dated`))) join `vn`.`referenceRateConfig` `rrc` on(1)) group by `e`.`dated` order by `e`.`dated` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `exchangeReportSourcePrevious`
--

/*!50001 DROP VIEW IF EXISTS `exchangeReportSourcePrevious`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `exchangeReportSourcePrevious` AS select `exchangeInsuranceIn`.`dated` AS `dated`,`exchangeInsuranceIn`.`amount` AS `amountIn`,`exchangeInsuranceIn`.`rate` AS `rateIn`,0.00 AS `amountOut`,0.00 AS `rateOut`,0.00 AS `amountEntry`,0.00 AS `rateEntry` from `vn`.`exchangeInsuranceIn` union all select `exchangeInsuranceOut`.`received` AS `received`,0.00 AS `amountIn`,0.00 AS `ratedIn`,`exchangeInsuranceOut`.`divisa` AS `amountOut`,`exchangeInsuranceOut`.`rate` AS `ratedOut`,0.00 AS `amountEntry`,0.00 AS `rateEntry` from `vn`.`exchangeInsuranceOut` union all select `exchangeInsuranceEntry`.`dated` AS `dated`,0.00 AS `amountIn`,0.00 AS `ratedIn`,0.00 AS `amountOut`,0.00 AS `ratedOut`,`exchangeInsuranceEntry`.`Dolares` AS `amountEntry`,`exchangeInsuranceEntry`.`rate` AS `rateEntry` from `vn`.`exchangeInsuranceEntry` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `expedition`
--

/*!50001 DROP VIEW IF EXISTS `expedition`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `expedition` AS select `e`.`expeditions_id` AS `id`,`e`.`agency_id` AS `agencyModeFk`,`e`.`ticket_id` AS `ticketFk`,`e`.`EsBulto` AS `isBox`,`e`.`odbc_date` AS `created`,`e`.`Id_Article` AS `itemFk`,`e`.`counter` AS `counter`,`e`.`checked` AS `checked`,`e`.`workerFk` AS `workerFk`,`e`.`externalId` AS `externalId` from `vn2008`.`expeditions` `e` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `expence`
--

/*!50001 DROP VIEW IF EXISTS `expence`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `expence` AS select `g`.`Id_Gasto` AS `id`,`g`.`iva_tipo_id` AS `taxTypeFk`,`g`.`Gasto` AS `name`,`g`.`isWithheld` AS `isWithheld` from `vn2008`.`Gastos` `g` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `firstTicketShipped`
--

/*!50001 DROP VIEW IF EXISTS `firstTicketShipped`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `firstTicketShipped` AS select min(`ticket`.`shipped`) AS `shipped`,`ticket`.`clientFk` AS `clientFk` from `vn`.`ticket` where (`ticket`.`shipped` > '2001-01-01') group by `ticket`.`clientFk` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `floraHollandBuyedItems`
--

/*!50001 DROP VIEW IF EXISTS `floraHollandBuyedItems`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `floraHollandBuyedItems` AS select `b`.`itemFk` AS `itemFk`,`i`.`longName` AS `longName`,`b`.`quantity` AS `quantity`,`b`.`buyingValue` AS `buyingValue`,`tr`.`landed` AS `landed`,`e`.`companyFk` AS `companyFk` from (((((`vn`.`buy` `b` join `vn`.`item` `i` on((`b`.`itemFk` = `i`.`id`))) join `vn`.`itemType` `it` on((`it`.`id` = `i`.`typeFk`))) join `vn`.`itemCategory` `ic` on((`ic`.`id` = `it`.`categoryFk`))) join `vn`.`entry` `e` on((`e`.`id` = `b`.`entryFk`))) join `vn`.`travel` `tr` on(((`tr`.`id` = `e`.`travelFk`) and (`ic`.`id` not in (8,6)) and (`b`.`buyingValue` <> 0) and (`b`.`quantity` <> 0) and (`e`.`supplierFk` in (1664,1665,1666,1465,1433))))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `grant`
--

/*!50001 DROP VIEW IF EXISTS `grant`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `grant` AS select `vn2008`.`Permisos`.`Id_Grupo` AS `group`,`vn2008`.`Permisos`.`Id_Trabajador` AS `worker`,`vn2008`.`Permisos`.`empresa_id` AS `company` from `vn2008`.`Permisos` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `grantGroup`
--

/*!50001 DROP VIEW IF EXISTS `grantGroup`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `grantGroup` AS select `vn2008`.`Grupos`.`id` AS `id`,`vn2008`.`Grupos`.`Grupo` AS `description`,`vn2008`.`Grupos`.`observation_type_id` AS `observationType` from `vn2008`.`Grupos` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `greuge`
--

/*!50001 DROP VIEW IF EXISTS `greuge`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `greuge` AS select `g`.`Id` AS `id`,`g`.`Id_Cliente` AS `clientFk`,`g`.`Comentario` AS `description`,`g`.`Importe` AS `amount`,`g`.`Fecha` AS `shipped`,`g`.`odbc_date` AS `created`,`g`.`Greuges_type_id` AS `greugeTypeFk`,`g`.`Id_Ticket` AS `ticketFk` from `vn2008`.`Greuges` `g` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `greugeType`
--

/*!50001 DROP VIEW IF EXISTS `greugeType`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `greugeType` AS select `gt`.`Greuges_type_id` AS `id`,`gt`.`name` AS `name` from `vn2008`.`Greuges_type` `gt` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `holiday`
--

/*!50001 DROP VIEW IF EXISTS `holiday`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `holiday` AS select `cl`.`calendar_labour_legend_id` AS `holidayDetailFk`,`cl`.`calendar_free_id` AS `holidayTypeFk`,`cl`.`workcenter_id` AS `workCenterFk`,`cl`.`day` AS `dated` from `postgresql`.`calendar_labour` `cl` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `holidayDetail`
--

/*!50001 DROP VIEW IF EXISTS `holidayDetail`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `holidayDetail` AS select `cll`.`calendar_labour_legend_id` AS `id`,`cll`.`descripcion` AS `description` from `postgresql`.`calendar_labour_legend` `cll` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `holidayLegend`
--

/*!50001 DROP VIEW IF EXISTS `holidayLegend`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `holidayLegend` AS select `cll`.`calendar_labour_legend_id` AS `id`,`cll`.`descripcion` AS `description` from `postgresql`.`calendar_labour_legend` `cll` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `holidayType`
--

/*!50001 DROP VIEW IF EXISTS `holidayType`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `holidayType` AS select `cf`.`calendar_free_id` AS `id`,`cf`.`type` AS `name`,`cf`.`rgb` AS `rgb` from `postgresql`.`calendar_free` `cf` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `ink`
--

/*!50001 DROP VIEW IF EXISTS `ink`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ink` AS select `c`.`Id_Tinta` AS `id`,`c`.`name` AS `name`,`c`.`Tinta` AS `picture`,`c`.`Orden` AS `showOrder` from `vn2008`.`Tintas` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `inkL10n`
--

/*!50001 DROP VIEW IF EXISTS `inkL10n`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `inkL10n` AS select `k`.`id` AS `id`,ifnull(`i`.`name`,`k`.`name`) AS `name` from (`vn`.`ink` `k` left join `vn`.`inkI18n` `i` on(((`i`.`inkFk` = `k`.`id`) and (`i`.`lang` = `util`.`lang`())))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `intrastat`
--

/*!50001 DROP VIEW IF EXISTS `intrastat`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `intrastat` AS select `i`.`Codintrastat` AS `id`,`i`.`Definicion` AS `description`,`i`.`iva_group_id` AS `taxClassFk`,`i`.`iva_codigo_id` AS `taxCodeFk` from `vn2008`.`Intrastat` `i` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `invoiceCorrection`
--

/*!50001 DROP VIEW IF EXISTS `invoiceCorrection`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `invoiceCorrection` AS select `ic`.`correctingFk` AS `correctingFk`,`ic`.`correctedFk` AS `correctedFk`,`ic`.`cplusRectificationTypeFk` AS `cplusRectificationTypeFk`,`ic`.`cplusInvoiceType477Fk` AS `cplusInvoiceType477Fk`,`ic`.`invoiceCorrectionTypeFk` AS `invoiceCorrectionTypeFk` from `vn2008`.`invoiceCorrection` `ic` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `invoiceCorrectionDataSource`
--

/*!50001 DROP VIEW IF EXISTS `invoiceCorrectionDataSource`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `invoiceCorrectionDataSource` AS select `s`.`itemFk` AS `itemFk`,`s`.`quantity` AS `quantity`,`s`.`concept` AS `concept`,`s`.`price` AS `price`,`s`.`discount` AS `discount`,`t`.`refFk` AS `refFk`,`s`.`id` AS `saleFk`,`t`.`shipped` AS `shipped` from (`vn`.`sale` `s` join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `invoiceIn`
--

/*!50001 DROP VIEW IF EXISTS `invoiceIn`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `invoiceIn` AS select `r`.`id` AS `id`,`r`.`num_recibida` AS `serialNumber`,`r`.`serie` AS `serial`,`r`.`proveedor_id` AS `supplierFk`,`r`.`fecha` AS `issued`,`r`.`sref` AS `supplierRef`,`r`.`contabilizada` AS `isBooked`,`r`.`moneda_id` AS `currencyFk`,`r`.`MYSQL_TIME` AS `created`,`r`.`empresa_id` AS `companyFk`,`r`.`gestdoc_id` AS `docFk`,`r`.`dateBooking` AS `booked`,`r`.`dateOperation` AS `operated`,`r`.`cplusInvoiceType472Fk` AS `cplusInvoiceType472Fk`,`r`.`cplusRectificationTypeFk` AS `cplusRectificationTypeFk`,`r`.`cplusSubjectOpFk` AS `cplusSubjectOpFk`,`r`.`cplusTaxBreakFk` AS `cplusTaxBreakFk`,`r`.`cplusTrascendency472Fk` AS `cplusTrascendency472Fk`,`r`.`bookEntried` AS `bookEntried`,`r`.`isVatDeductible` AS `isVatDeductible` from `vn2008`.`recibida` `r` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `invoiceInAwb`
--

/*!50001 DROP VIEW IF EXISTS `invoiceInAwb`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `invoiceInAwb` AS select `a`.`recibida_id` AS `invoiceInFk`,`a`.`awb_id` AS `awbFk`,`a`.`dua` AS `dua` from `vn2008`.`awb_recibida` `a` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `invoiceInDueDay`
--

/*!50001 DROP VIEW IF EXISTS `invoiceInDueDay`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `invoiceInDueDay` AS select `r`.`id` AS `id`,`r`.`recibida_id` AS `invoiceInFk`,`r`.`fecha` AS `dueDated`,`r`.`banco_id` AS `bankFk`,`r`.`cantidad` AS `amount`,`r`.`divisa` AS `foreignValue`,`r`.`stamp` AS `created` from `vn2008`.`recibida_vencimiento` `r` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `invoiceInEntry`
--

/*!50001 DROP VIEW IF EXISTS `invoiceInEntry`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `invoiceInEntry` AS select `i`.`recibida_entrada_id` AS `id`,`i`.`recibida_id` AS `invoiceInFk`,`i`.`Id_Entrada` AS `entryFk`,`i`.`percentage` AS `percentage`,`i`.`awb_recibida` AS `invoiceInAwbFk`,`i`.`Contabilizado` AS `isBooked` from `vn2008`.`recibida_entrada` `i` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `invoiceInIntrastat`
--

/*!50001 DROP VIEW IF EXISTS `invoiceInIntrastat`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `invoiceInIntrastat` AS select `r`.`recibida_id` AS `invoiceInFk`,`r`.`Codintrastat` AS `intrastatFk`,`r`.`importe` AS `amount` from `vn2008`.`recibida_intrastat` `r` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `invoiceInTax`
--

/*!50001 DROP VIEW IF EXISTS `invoiceInTax`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `invoiceInTax` AS select `r`.`id` AS `id`,`r`.`recibida_id` AS `invoiceInFk`,`r`.`iva_id` AS `taxCodeFk`,`r`.`bi` AS `taxableBase`,`r`.`gastos_id` AS `expenceFk`,`r`.`divisa` AS `foreignValue`,`r`.`MYSQL_TIME` AS `created` from `vn2008`.`recibida_iva` `r` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `invoiceOut`
--

/*!50001 DROP VIEW IF EXISTS `invoiceOut`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `invoiceOut` AS select `f`.`factura_id` AS `id`,`f`.`Id_Factura` AS `ref`,`f`.`Serie` AS `serial`,`f`.`Fecha` AS `issued`,`f`.`Importe` AS `amount`,`f`.`Id_Cliente` AS `clientFk`,`f`.`odbc_date` AS `created`,`f`.`empresa_id` AS `companyFk`,`f`.`Vencimiento` AS `dued`,`f`.`booked` AS `booked`,`f`.`Id_Banco` AS `bankFk`,`f`.`cplusInvoiceType477Fk` AS `cplusInvoiceType477Fk`,`f`.`cplusTaxBreakFk` AS `cplusTaxBreakFk`,`f`.`cplusSubjectOpFk` AS `cplusSubjectOpFk`,`f`.`cplusTrascendency477Fk` AS `cplusTrascendency477Fk`,`f`.`pdf` AS `pdf` from `vn2008`.`Facturas` `f` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `item`
--

/*!50001 DROP VIEW IF EXISTS `item`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `item` AS select `t`.`Id_Article` AS `id`,`t`.`Article` AS `name`,`t`.`tipo_id` AS `typeFk`,`t`.`Medida` AS `size`,`t`.`Color` AS `inkFk`,`t`.`Categoria` AS `category`,`t`.`Tallos` AS `stems`,`t`.`id_origen` AS `originFk`,`t`.`description` AS `description`,`t`.`producer_id` AS `producerFk`,`t`.`Codintrastat` AS `intrastatFk`,`t`.`offer` AS `isOnOffer`,`t`.`caja` AS `box`,`t`.`expenceFk` AS `expenceFk`,`t`.`bargain` AS `isBargain`,`t`.`comments` AS `comment`,`t`.`relevancy` AS `relevancy`,`t`.`Foto` AS `image`,`t`.`generic` AS `generic`,`t`.`density` AS `density`,`t`.`iva_group_id` AS `taxClassFk`,`t`.`PVP` AS `minPrice`,`t`.`Min` AS `hasMinPrice`,`t`.`isActive` AS `isActive`,`t`.`longName` AS `longName`,`t`.`subName` AS `subName`,`t`.`tag5` AS `tag5`,`t`.`value5` AS `value5`,`t`.`tag6` AS `tag6`,`t`.`value6` AS `value6`,`t`.`tag7` AS `tag7`,`t`.`value7` AS `value7`,`t`.`tag8` AS `tag8`,`t`.`value8` AS `value8`,`t`.`tag9` AS `tag9`,`t`.`value9` AS `value9`,`t`.`tag10` AS `tag10`,`t`.`value10` AS `value10`,`t`.`minimum` AS `minimum`,`t`.`upToDown` AS `upToDown`,`t`.`compression` AS `compression` from `vn2008`.`Articles` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemBarcode`
--

/*!50001 DROP VIEW IF EXISTS `itemBarcode`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemBarcode` AS select `vn2008`.`barcodes`.`id` AS `id`,`vn2008`.`barcodes`.`Id_Article` AS `itemFk`,`vn2008`.`barcodes`.`code` AS `code` from `vn2008`.`barcodes` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemBotanical`
--

/*!50001 DROP VIEW IF EXISTS `itemBotanical`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemBotanical` AS select `ab`.`Id_Article` AS `itemFk`,`ab`.`botanical` AS `botanical`,`ab`.`genus_id` AS `genusFk`,`ab`.`specie_id` AS `specieFk` from `vn2008`.`Articles_botanical` `ab` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemBotanicalWithGenus`
--

/*!50001 DROP VIEW IF EXISTS `itemBotanicalWithGenus`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemBotanicalWithGenus` AS select `ib`.`itemFk` AS `itemFk`,ifnull(`ib`.`botanical`,concat(`g`.`latinGenusName`,' ',ifnull(`s`.`latinSpeciesName`,''))) AS `ediBotanic` from ((`vn`.`itemBotanical` `ib` left join `vn`.`ediGenus` `g` on((`g`.`id` = `ib`.`genusFk`))) left join `vn`.`ediSpecie` `s` on((`s`.`id` = `ib`.`specieFk`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemCategory`
--

/*!50001 DROP VIEW IF EXISTS `itemCategory`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemCategory` AS select `r`.`id` AS `id`,`r`.`reino` AS `name`,`r`.`display` AS `display`,`r`.`color` AS `color`,`r`.`icon` AS `icon`,`r`.`mercancia` AS `merchandise`,`r`.`orden` AS `order`,`r`.`efimero` AS `shortLife` from `vn2008`.`reinos` `r` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemCategoryL10n`
--

/*!50001 DROP VIEW IF EXISTS `itemCategoryL10n`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemCategoryL10n` AS select `c`.`id` AS `id`,ifnull(`i`.`name`,`c`.`name`) AS `name` from (`vn`.`itemCategory` `c` left join `vn`.`itemCategoryI18n` `i` on(((`i`.`categoryFk` = `c`.`id`) and (`i`.`lang` = `util`.`lang`())))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemPlacement`
--

/*!50001 DROP VIEW IF EXISTS `itemPlacement`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemPlacement` AS select `an`.`id` AS `id`,`an`.`Id_Article` AS `itemFk`,`an`.`warehouse_id` AS `warehouseFk`,`an`.`nicho` AS `code`,`an`.`reserve` AS `reserve`,`an`.`pickable` AS `pickable`,`an`.`modificationDate` AS `modificationDate` from `vn2008`.`Articles_nicho` `an` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemPlacementSupplyList`
--

/*!50001 DROP VIEW IF EXISTS `itemPlacementSupplyList`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemPlacementSupplyList` AS select `ips`.`id` AS `id`,`ips`.`itemFk` AS `itemFk`,`ips`.`quantity` AS `quantity`,`ips`.`priority` AS `priority`,`ips`.`created` AS `created`,`ips`.`userFk` AS `userFk`,`ips`.`repoUserFk` AS `repoUserFk`,(`ips`.`quantity` - sum(ifnull(`isps`.`quantity`,0))) AS `saldo`,concat(`i`.`longName`,' ',`i`.`size`) AS `longName`,`i`.`subName` AS `subName`,`i`.`size` AS `size`,`w`.`code` AS `workerCode`,`rw`.`code` AS `repoCode`,`p`.`code` AS `parking` from (((((((`vn`.`itemPlacementSupply` `ips` join `vn`.`itemShelving` `ish` on((`ish`.`itemFk` = `ips`.`itemFk`))) join `vn`.`item` `i` on((`i`.`id` = `ish`.`itemFk`))) left join `vn`.`worker` `w` on((`w`.`userFk` = `ips`.`userFk`))) left join `vn`.`worker` `rw` on((`rw`.`userFk` = `ips`.`repoUserFk`))) left join `vn`.`itemShelvingPlacementSupply` `isps` on((`isps`.`itemPlacementSupplyFk` = `ips`.`id`))) left join `vn`.`shelving` `s` on((`ish`.`shelvingFk` = `s`.`code`))) left join `vn`.`parking` `p` on((`s`.`parkingFk` = `p`.`id`))) where (`ips`.`created` >= curdate()) group by `ips`.`priority`,`ips`.`id` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemShelvingAvailable`
--

/*!50001 DROP VIEW IF EXISTS `itemShelvingAvailable`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemShelvingAvailable` AS select `s`.`id` AS `saleFk`,`tst`.`updated` AS `Modificado`,`s`.`ticketFk` AS `ticketFk`,`stk`.`isChecked` AS `isPicked`,`s`.`itemFk` AS `itemFk`,`s`.`quantity` AS `quantity`,`s`.`concept` AS `concept`,`i`.`size` AS `size`,`st`.`name` AS `Estado`,`st`.`sectorProdPriority` AS `sectorProdPriority`,`its`.`available` AS `available`,`pk`.`sectorFk` AS `sectorFk`,`sh`.`code` AS `matricula`,`pk`.`id` AS `parking`,`its`.`id` AS `itemShelving`,`am`.`name` AS `Agency`,`t`.`shipped` AS `shipped`,`its`.`grouping` AS `grouping`,`its`.`packing` AS `packing` from ((((((((((`vn`.`sale` `s` join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `vn`.`agencyMode` `am` on((`am`.`id` = `t`.`agencyModeFk`))) join `vn`.`ticketStateToday` `tst` on((`tst`.`ticket` = `t`.`id`))) join `vn`.`state` `st` on((`st`.`id` = `tst`.`state`))) join `vn`.`item` `i` on((`i`.`id` = `s`.`itemFk`))) join `vn`.`itemShelving` `its` on((`its`.`itemFk` = `s`.`itemFk`))) join `vn`.`shelving` `sh` on((`sh`.`code` = `its`.`shelvingFk`))) join `vn`.`parking` `pk` on((`pk`.`id` = `sh`.`parkingFk`))) join `vn`.`sector` `sc` on(((`sc`.`id` = `pk`.`sectorFk`) and (`sc`.`warehouseFk` = `t`.`warehouseFk`)))) left join `vn`.`saleTracking` `stk` on(((`stk`.`saleFk` = `s`.`id`) and (`stk`.`stateFk` = 26)))) where ((`t`.`shipped` between `util`.`yesterday`() and `util`.`dayend`(curdate())) and (`its`.`available` > 0) and (`sh`.`code` <> 'FUE') and (`its`.`grouping` <= `s`.`quantity`) and `st`.`sectorProdPriority`) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemShelvingAvailableKk`
--

/*!50001 DROP VIEW IF EXISTS `itemShelvingAvailableKk`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemShelvingAvailableKk` AS select `s`.`id` AS `saleFk`,`tst`.`updated` AS `Modificado`,`s`.`ticketFk` AS `ticketFk`,`s`.`isPicked` AS `isPicked`,`s`.`itemFk` AS `itemFk`,`s`.`quantity` AS `quantity`,`s`.`concept` AS `concept`,`i`.`size` AS `size`,`st`.`name` AS `Estado`,`st`.`sectorProdPriority` AS `sectorProdPriority`,`its`.`available` AS `available`,`pk`.`sectorFk` AS `sectorFk`,`sh`.`code` AS `matricula`,`pk`.`id` AS `parking`,`its`.`id` AS `itemShelving`,`am`.`name` AS `Agency`,`t`.`shipped` AS `shipped`,`its`.`grouping` AS `grouping`,`its`.`packing` AS `packing` from (((((((((`vn`.`sale` `s` join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `vn`.`agencyMode` `am` on((`am`.`id` = `t`.`agencyModeFk`))) join `vn`.`ticketStateToday` `tst` on((`tst`.`ticket` = `t`.`id`))) join `vn`.`state` `st` on((`st`.`id` = `tst`.`state`))) join `vn`.`item` `i` on((`i`.`id` = `s`.`itemFk`))) join `vn`.`itemShelving` `its` on((`its`.`itemFk` = `s`.`itemFk`))) join `vn`.`shelving` `sh` on((`sh`.`code` = `its`.`shelvingFk`))) join `vn`.`parking` `pk` on((`pk`.`id` = `sh`.`parkingFk`))) join `vn`.`sector` `sc` on(((`sc`.`id` = `pk`.`sectorFk`) and (`sc`.`warehouseFk` = `t`.`warehouseFk`)))) where ((`t`.`shipped` between `util`.`yesterday`() and `util`.`dayend`(curdate())) and (`its`.`available` > 0) and (`sh`.`code` <> 'FUE') and (`its`.`grouping` <= `s`.`quantity`) and `st`.`sectorProdPriority`) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemShelvingList`
--

/*!50001 DROP VIEW IF EXISTS `itemShelvingList`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemShelvingList` AS select `ish`.`shelvingFk` AS `shelvingFk`,`ish`.`visible` AS `visible`,`ish`.`created` AS `created`,`pk`.`code` AS `parking`,`ish`.`itemFk` AS `itemFk`,`i`.`longName` AS `longName`,`i`.`size` AS `size`,`i`.`subName` AS `subName`,`sh`.`parked` AS `parked` from (((`vn`.`itemShelving` `ish` join `vn`.`shelving` `sh` on((`sh`.`code` = `ish`.`shelvingFk`))) join `vn`.`item` `i` on((`i`.`id` = `ish`.`itemFk`))) left join `vn`.`parking` `pk` on((`pk`.`id` = `sh`.`parkingFk`))) order by `ish`.`created` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemShelvingPlacementSupplyStock`
--

/*!50001 DROP VIEW IF EXISTS `itemShelvingPlacementSupplyStock`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemShelvingPlacementSupplyStock` AS select `ish`.`id` AS `itemShelvingFk`,`ish`.`itemFk` AS `itemFk`,`ish`.`quantity` AS `quantity`,`ish`.`packing` AS `packing`,`ish`.`visible` AS `stock`,`i`.`longName` AS `longName`,`i`.`size` AS `size`,`i`.`subName` AS `subName`,`sh`.`code` AS `shelving`,`p`.`code` AS `parking`,`ish`.`created` AS `created`,ifnull(`sh`.`priority`,1) AS `priority` from (((((`vn`.`itemShelving` `ish` join `vn`.`shelving` `sh` on((`sh`.`code` = `ish`.`shelvingFk`))) left join `vn`.`parking` `p` on((`p`.`id` = `sh`.`parkingFk`))) join `vn`.`item` `i` on((`i`.`id` = `ish`.`itemFk`))) left join `vn`.`itemShelvingSale` `iss` on((`iss`.`itemShelvingFk` = `ish`.`id`))) left join `vn`.`itemShelvingPlacementSupply` `isps` on((`isps`.`itemShelvingFk` = `ish`.`id`))) group by `ish`.`id` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemShelvingStock`
--

/*!50001 DROP VIEW IF EXISTS `itemShelvingStock`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemShelvingStock` AS select `ish`.`itemFk` AS `itemFk`,sum(`ish`.`visible`) AS `visible`,min(`ish`.`packing`) AS `packing`,`s`.`description` AS `sector`,sum(`ish`.`visible`) AS `visibleOriginal`,sum(`issr`.`removed`) AS `removed` from ((((`itemShelving` `ish` join `shelving` `sh` on((`sh`.`code` = `ish`.`shelvingFk`))) join `parking` `p` on((`p`.`id` = `sh`.`parkingFk`))) join `sector` `s` on((`s`.`id` = `p`.`sectorFk`))) left join `itemShelvingStockRemoved` `issr` on((`issr`.`itemShelvingFk` = `ish`.`id`))) where (`s`.`warehouseFk` = 1) group by `ish`.`itemFk` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemShelvingStockRemoved`
--

/*!50001 DROP VIEW IF EXISTS `itemShelvingStockRemoved`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemShelvingStockRemoved` AS select `ish`.`id` AS `itemShelvingFk`,`ish`.`itemFk` AS `itemFk`,(sum(ifnull(`iss`.`quantity`,0)) + sum(ifnull(`isps`.`quantity`,0))) AS `removed` from ((`itemShelving` `ish` left join `itemShelvingSale` `iss` on((`iss`.`itemShelvingFk` = `ish`.`id`))) left join `itemShelvingPlacementSupply` `isps` on((`isps`.`itemShelvingFk` = `ish`.`id`))) group by `ish`.`id` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemShelvingStock_beta`
--

/*!50001 DROP VIEW IF EXISTS `itemShelvingStock_beta`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemShelvingStock_beta` AS select `ish`.`itemFk` AS `itemFk`,(sum(`ish`.`visible`) - `issr`.`removed`) AS `visible`,min(`ish`.`packing`) AS `packing`,`s`.`description` AS `sector`,sum(`ish`.`visible`) AS `visibleOriginal`,`issr`.`removed` AS `removed` from ((((`itemShelving` `ish` join `shelving` `sh` on((`sh`.`code` = `ish`.`shelvingFk`))) join `parking` `p` on((`p`.`id` = `sh`.`parkingFk`))) join `sector` `s` on((`s`.`id` = `p`.`sectorFk`))) left join `itemShelvingStockRemoved` `issr` on((`issr`.`itemShelvingFk` = `ish`.`id`))) where (`s`.`warehouseFk` = 1) group by `ish`.`itemFk` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemShelvingStock_old`
--

/*!50001 DROP VIEW IF EXISTS `itemShelvingStock_old`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemShelvingStock_old` AS select `ish`.`itemFk` AS `itemFk`,sum(`ish`.`visible`) AS `visible`,min(`ish`.`packing`) AS `packing` from (((`itemShelving` `ish` join `shelving` `sh` on((`sh`.`code` = `ish`.`shelvingFk`))) join `parking` `p` on((`p`.`id` = `sh`.`parkingFk`))) join `sector` `s` on((`s`.`id` = `p`.`sectorFk`))) where (`s`.`warehouseFk` = 1) group by `ish`.`itemFk` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemTagged`
--

/*!50001 DROP VIEW IF EXISTS `itemTagged`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemTagged` AS select distinct `itemTag`.`itemFk` AS `itemFk` from `itemTag` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemTaxCountrySpain`
--

/*!50001 DROP VIEW IF EXISTS `itemTaxCountrySpain`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemTaxCountrySpain` AS select `t`.`Id_Article` AS `id`,`t`.`Article` AS `name`,`t`.`tipo_id` AS `typeFk`,`t`.`Tallos` AS `stems`,`t`.`description` AS `description`,`t`.`Codintrastat` AS `intrastatFk`,`t`.`expenceFk` AS `expenceFk`,`t`.`comments` AS `comment`,`t`.`relevancy` AS `relevancy`,`t`.`Foto` AS `image`,`t`.`generic` AS `generic`,`itc`.`taxClassFk` AS `taxClassFk` from (`vn2008`.`Articles` `t` join `vn`.`itemTaxCountry` `itc` on((`t`.`Id_Article` = `itc`.`itemFk`))) where (`itc`.`countryFk` = 1) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemType`
--

/*!50001 DROP VIEW IF EXISTS `itemType`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8mb4 */;
/*!50001 SET character_set_results     = utf8mb4 */;
/*!50001 SET collation_connection      = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemType` AS select `t`.`tipo_id` AS `id`,`t`.`Id_Tipo` AS `code`,`t`.`Tipo` AS `name`,`t`.`reino_id` AS `categoryFk`,`t`.`life` AS `life`,`t`.`Id_Trabajador` AS `workerFk`,`t`.`warehouseFk` AS `warehouseFk`,`t`.`isPackaging` AS `isPackaging`,`t`.`density` AS `density`,`t`.`Orden` AS `order` from `vn2008`.`Tipos` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemTypeL10n`
--

/*!50001 DROP VIEW IF EXISTS `itemTypeL10n`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemTypeL10n` AS select `t`.`id` AS `id`,ifnull(`i`.`name`,`t`.`name`) AS `name` from (`vn`.`itemType` `t` left join `vn`.`itemTypeI18n` `i` on(((`i`.`typeFk` = `t`.`id`) and (`i`.`lang` = `util`.`LANG`())))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `mail`
--

/*!50001 DROP VIEW IF EXISTS `mail`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `mail` AS select `vn2008`.`mail`.`id` AS `id`,`vn2008`.`mail`.`senderFk` AS `senderFk`,`vn2008`.`mail`.`recipientFk` AS `recipientFk`,`vn2008`.`mail`.`to` AS `sender`,`vn2008`.`mail`.`reply_to` AS `replyTo`,`vn2008`.`mail`.`subject` AS `subject`,`vn2008`.`mail`.`text` AS `body`,`vn2008`.`mail`.`plainTextBody` AS `plainTextBody`,`vn2008`.`mail`.`path` AS `attachment`,`vn2008`.`mail`.`DATE_ODBC` AS `creationDate`,`vn2008`.`mail`.`sent` AS `sent`,`vn2008`.`mail`.`error` AS `status` from `vn2008`.`mail` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `manaSpellers`
--

/*!50001 DROP VIEW IF EXISTS `manaSpellers`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `manaSpellers` AS select `bs`.`mana_spellers`.`Id_Trabajador` AS `worker`,`bs`.`mana_spellers`.`size` AS `size`,`bs`.`mana_spellers`.`used` AS `used`,`bs`.`mana_spellers`.`prices_modifier_rate` AS `pricesModifierRate`,`bs`.`mana_spellers`.`prices_modifier_activated` AS `pricesModifierActivated`,`vn2008`.`Trabajadores`.`CodigoTrabajador` AS `workerCode`,`vn2008`.`Trabajadores`.`Nombre` AS `firstname`,`vn2008`.`Trabajadores`.`Apellidos` AS `name` from (`bs`.`mana_spellers` join `vn2008`.`Trabajadores` on((`bs`.`mana_spellers`.`Id_Trabajador` = `vn2008`.`Trabajadores`.`Id_Trabajador`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `mandate`
--

/*!50001 DROP VIEW IF EXISTS `mandate`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `mandate` AS select `m`.`id` AS `id`,`m`.`Id_Cliente` AS `clientFk`,`m`.`empresa_id` AS `companyFk`,`m`.`Id_mandato` AS `code`,`m`.`FAlta` AS `created`,`m`.`Fbaja` AS `finished`,`m`.`idmandato_tipo` AS `mandateTypeFk` from `vn2008`.`mandato` `m` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `mandateType`
--

/*!50001 DROP VIEW IF EXISTS `mandateType`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `mandateType` AS select `m`.`idmandato_tipo` AS `id`,`m`.`Nombre` AS `name` from `vn2008`.`mandato_tipo` `m` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `observationType`
--

/*!50001 DROP VIEW IF EXISTS `observationType`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `observationType` AS select `ot`.`observation_type_id` AS `id`,`ot`.`description` AS `description` from `vn2008`.`observation_type` `ot` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `orderTicket`
--

/*!50001 DROP VIEW IF EXISTS `orderTicket`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `orderTicket` AS select `b`.`order_id` AS `orderFk`,`b`.`Id_Ticket` AS `ticketFk` from `vn2008`.`order_Tickets` `b` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `origin`
--

/*!50001 DROP VIEW IF EXISTS `origin`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `origin` AS select `o`.`id` AS `id`,`o`.`Abreviatura` AS `code`,`o`.`Origen` AS `name`,`o`.`Id_Paises` AS `countryFk` from `vn2008`.`Origen` `o` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `originL10n`
--

/*!50001 DROP VIEW IF EXISTS `originL10n`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `originL10n` AS select `o`.`id` AS `id`,ifnull(`i`.`name`,`o`.`name`) AS `name` from (`vn`.`origin` `o` left join `vn`.`originI18n` `i` on(((`i`.`originFk` = `o`.`id`) and (`i`.`lang` = `util`.`lang`())))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `outgoingInvoice`
--

/*!50001 DROP VIEW IF EXISTS `outgoingInvoice`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `outgoingInvoice` AS select `vn2008`.`Facturas`.`Id_Factura` AS `id`,`vn2008`.`Facturas`.`Serie` AS `serie`,`vn2008`.`Facturas`.`Fecha` AS `dateInvoice`,`vn2008`.`Facturas`.`Importe` AS `total`,`vn2008`.`Facturas`.`Vencimiento` AS `dueDate`,`vn2008`.`Facturas`.`Id_Banco` AS `bank`,`vn2008`.`Facturas`.`Id_Cliente` AS `client`,`vn2008`.`Facturas`.`Id_Remesa` AS `remittance`,`vn2008`.`Facturas`.`Remesar` AS `remit`,`vn2008`.`Facturas`.`Id_Trabajador` AS `worker`,`vn2008`.`Facturas`.`odbc_date` AS `creationDate`,`vn2008`.`Facturas`.`empresa_id` AS `company`,`vn2008`.`Facturas`.`liquidacion` AS `liquidacion?`,`vn2008`.`Facturas`.`pdf` AS `isPdf` from `vn2008`.`Facturas` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `packageEquivalentItem`
--

/*!50001 DROP VIEW IF EXISTS `packageEquivalentItem`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `packageEquivalentItem` AS select `i`.`itemFk` AS `itemFk`,`ie`.`itemFk` AS `equivalentFk` from ((`vn`.`packageEquivalent` `pe` join `vn`.`packaging` `i` on((`i`.`id` = `pe`.`packageFk`))) join `vn`.`packaging` `ie` on((`ie`.`id` = `pe`.`equivalentFk`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `packaging`
--

/*!50001 DROP VIEW IF EXISTS `packaging`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `packaging` AS select `c`.`Id_Cubo` AS `id`,`c`.`Volumen` AS `volume`,`c`.`X` AS `width`,`c`.`Y` AS `height`,`c`.`Z` AS `depth`,`c`.`Retornable` AS `isPackageReturnable`,`c`.`odbc_date` AS `created`,`c`.`item_id` AS `itemFk`,`c`.`pvp` AS `price`,`c`.`bultoCubico` AS `isBox` from `vn2008`.`Cubos` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `payDem`
--

/*!50001 DROP VIEW IF EXISTS `payDem`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `payDem` AS select `t`.`id` AS `id`,`t`.`pay_dem` AS `payDem` from `vn2008`.`pay_dem` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `payMethod`
--

/*!50001 DROP VIEW IF EXISTS `payMethod`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `payMethod` AS select `t`.`id` AS `id`,`t`.`name` AS `name`,`t`.`graceDays` AS `graceDays`,`t`.`deudaviva` AS `outstandingDebt`,`t`.`ibanRequired` AS `ibanRequired` from `vn2008`.`pay_met` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `payment`
--

/*!50001 DROP VIEW IF EXISTS `payment`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `payment` AS select `p`.`id` AS `id`,`p`.`fecha` AS `received`,`p`.`id_proveedor` AS `supplierFk`,`p`.`importe` AS `amount`,`p`.`id_moneda` AS `currencyFk`,`p`.`divisa` AS `divisa`,`p`.`id_banco` AS `bankFk`,`p`.`pay_met_id` AS `payMethod`,`p`.`empresa_id` AS `companyFk`,`p`.`pago_sdc_id` AS `exchangeInsuranceFk`,`p`.`conciliado` AS `isConciliate` from `vn2008`.`pago` `p` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `paymentExchangeInsurance`
--

/*!50001 DROP VIEW IF EXISTS `paymentExchangeInsurance`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `paymentExchangeInsurance` AS select `p`.`pago_sdc_id` AS `id`,`p`.`importe` AS `amount`,`p`.`fecha` AS `created`,`p`.`vencimiento` AS `dueDay`,`p`.`entity_id` AS `entityFk`,`p`.`ref` AS `ref`,`p`.`rate` AS `rate`,`p`.`empresa_id` AS `companyFk`,`p`.`financialProductTypefk` AS `financialProductTypefk`,`p`.`upperBarrier` AS `upperBarrier`,`p`.`lowerBarrier` AS `lowerBarrier`,`p`.`strike` AS `strike` from `vn2008`.`pago_sdc` `p` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `payrollCenter`
--

/*!50001 DROP VIEW IF EXISTS `payrollCenter`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `payrollCenter` AS select `b`.`cod_centro` AS `codCenter`,`b`.`Centro` AS `name`,`b`.`nss_cotizacion` AS `nss`,`b`.`domicilio` AS `street`,`b`.`poblacion` AS `city`,`b`.`cp` AS `postcode`,`b`.`empresa_id` AS `companyFk`,`b`.`codempresa` AS `companyCode` from `vn2008`.`payroll_centros` `b` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `plantpassport`
--

/*!50001 DROP VIEW IF EXISTS `plantpassport`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `plantpassport` AS select `pp`.`producer_id` AS `producerFk`,`pp`.`plantpassport_authority_id` AS `plantpassportAuthorityFk`,`pp`.`number` AS `number` from `vn2008`.`plantpassport` `pp` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `plantpassportAuthority`
--

/*!50001 DROP VIEW IF EXISTS `plantpassportAuthority`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `plantpassportAuthority` AS select `ppa`.`plantpassport_authority_id` AS `id`,`ppa`.`denomination` AS `denomination`,`ppa`.`Paises_Id` AS `countryFk` from `vn2008`.`plantpassport_authority` `ppa` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `preparationException`
--

/*!50001 DROP VIEW IF EXISTS `preparationException`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `preparationException` AS select `p`.`exception_day` AS `exceptionDay`,`p`.`warehouse_id` AS `warehouseFk`,`p`.`percentage` AS `percentage` from `vn2008`.`preparation_exception` `p` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `preparationPercentage`
--

/*!50001 DROP VIEW IF EXISTS `preparationPercentage`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `preparationPercentage` AS select `p`.`week_day` AS `weekDay`,`p`.`warehouse_id` AS `warehouseFk`,`p`.`percentage` AS `percentage` from `vn2008`.`preparation_percentage` `p` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `priceBuilderDistinctTags`
--

/*!50001 DROP VIEW IF EXISTS `priceBuilderDistinctTags`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `priceBuilderDistinctTags` AS select `priceBuilderTag`.`priceBuilderFk` AS `priceBuilderFk`,count(distinct `priceBuilderTag`.`tagFk`) AS `numTags` from `priceBuilderTag` group by `priceBuilderTag`.`priceBuilderFk` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `priceFixed`
--

/*!50001 DROP VIEW IF EXISTS `priceFixed`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `priceFixed` AS select `p`.`item_id` AS `itemFk`,`p`.`rate_0` AS `rate0`,`p`.`rate_1` AS `rate1`,`p`.`rate_2` AS `rate2`,`p`.`rate_3` AS `rate3`,`p`.`date_start` AS `started`,`p`.`date_end` AS `ended`,`p`.`bonus` AS `bonus`,`p`.`warehouse_id` AS `warehouseFk`,`p`.`odbc_date` AS `created`,`p`.`price_fixed_id` AS `id`,`p`.`grouping` AS `grouping`,`p`.`Packing` AS `packing`,`p`.`caja` AS `box` from `vn2008`.`price_fixed` `p` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `printServerQueue`
--

/*!50001 DROP VIEW IF EXISTS `printServerQueue`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `printServerQueue` AS select `c`.`Id_Cola` AS `id`,`c`.`Id_Impresora` AS `printerFk`,`c`.`Id_Prioridad` AS `priorityFk`,`c`.`Id_Informe` AS `reportFk`,`c`.`Id_Estado` AS `statusFk`,`c`.`Hora_Inicio` AS `started`,`c`.`Hora_Fin` AS `finished`,`c`.`Cola` AS `param1`,`c`.`Id_Trabajador` AS `workerFk`,`c`.`Cola2` AS `param2`,`c`.`Cola3` AS `param3`,`c`.`error` AS `error` from `vn2008`.`Colas` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `printer`
--

/*!50001 DROP VIEW IF EXISTS `printer`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `printer` AS select `i`.`Id_Impresora` AS `id`,`i`.`Ruta` AS `path`,`i`.`Impresora` AS `name`,`i`.`referencia` AS `reference`,`i`.`isLabeler` AS `isLabeler`,`i`.`description` AS `description` from `vn2008`.`Impresoras` `i` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `printingQueue`
--

/*!50001 DROP VIEW IF EXISTS `printingQueue`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `printingQueue` AS select `c`.`Id_Cola` AS `id`,`c`.`Id_Impresora` AS `printer`,`c`.`Id_Prioridad` AS `priority`,`c`.`Id_Informe` AS `report`,`c`.`Id_Estado` AS `state`,`c`.`Hora_Inicio` AS `startingTime`,`c`.`Hora_Fin` AS `endingTime`,`c`.`Cola` AS `text`,`c`.`Id_Trabajador` AS `worker`,`c`.`Cola2` AS `text2`,`c`.`Cola3` AS `text3` from `vn2008`.`Colas` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `producer`
--

/*!50001 DROP VIEW IF EXISTS `producer`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `producer` AS select `p`.`producer_id` AS `id`,`p`.`name` AS `name`,`p`.`visible` AS `isVisible` from `vn2008`.`producer` `p` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `promissoryNote`
--

/*!50001 DROP VIEW IF EXISTS `promissoryNote`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `promissoryNote` AS select `p`.`Id_Pagare` AS `id`,`p`.`Concepto` AS `Concept`,`p`.`pago_id` AS `paymentFk` from `vn2008`.`Pagares` `p` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `province`
--

/*!50001 DROP VIEW IF EXISTS `province`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `province` AS select `t`.`province_id` AS `id`,`t`.`name` AS `name`,`t`.`Paises_Id` AS `countryFk`,`t`.`warehouse_id` AS `warehouseFk`,`t`.`zone` AS `zoneFk`,`t`.`geoFk` AS `geoFk` from `vn2008`.`province` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `receipt`
--

/*!50001 DROP VIEW IF EXISTS `receipt`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8mb4 */;
/*!50001 SET character_set_results     = utf8mb4 */;
/*!50001 SET collation_connection      = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `receipt` AS select `t`.`Id` AS `id`,`t`.`Id_Factura` AS `invoiceFk`,`t`.`Entregado` AS `amountPaid`,`t`.`Pendiente` AS `amountUnpaid`,`t`.`Fechacobro` AS `payed`,`t`.`Id_Trabajador` AS `workerFk`,`t`.`Id_Banco` AS `bankFk`,`t`.`Id_Cliente` AS `clientFk`,`t`.`odbc_date` AS `created`,`t`.`empresa_id` AS `companyFk`,`t`.`conciliado` AS `isConciliate` from `vn2008`.`Recibos` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `recovery`
--

/*!50001 DROP VIEW IF EXISTS `recovery`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `recovery` AS select `r`.`recovery_id` AS `id`,`r`.`Id_Cliente` AS `clientFk`,`r`.`dstart` AS `started`,`r`.`dend` AS `finished`,`r`.`amount` AS `amount`,`r`.`period` AS `period` from `vn2008`.`recovery` `r` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `referenceRate`
--

/*!50001 DROP VIEW IF EXISTS `referenceRate`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `referenceRate` AS select `r`.`moneda_id` AS `currencyFk`,`r`.`date` AS `dated`,`r`.`rate` AS `value` from `vn2008`.`reference_rate` `r` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `role`
--

/*!50001 DROP VIEW IF EXISTS `role`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `role` AS select `account`.`role`.`id` AS `id`,`account`.`role`.`name` AS `name`,`account`.`role`.`description` AS `description`,`account`.`role`.`hasLogin` AS `hasLogin` from `account`.`role` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `route`
--

/*!50001 DROP VIEW IF EXISTS `route`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `route` AS select `a`.`Id_Ruta` AS `id`,`a`.`Id_Trabajador` AS `workerFk`,`a`.`Fecha` AS `created`,`a`.`Id_Vehiculo` AS `vehicleFk`,`a`.`Id_Agencia` AS `agencyModeFk`,`a`.`Hora` AS `time`,`a`.`ok` AS `isOk`,`a`.`km_start` AS `kmStart`,`a`.`km_end` AS `kmEnd`,`a`.`date_start` AS `started`,`a`.`date_end` AS `finished`,`a`.`gestdoc_id` AS `gestdocFk`,`a`.`cost` AS `cost`,`a`.`m3` AS `m3`,`a`.`description` AS `description` from `vn2008`.`Rutas` `a` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `routesControl`
--

/*!50001 DROP VIEW IF EXISTS `routesControl`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `routesControl` AS select `t`.`Id_Ruta` AS `routeFk`,count(`e`.`expeditions_id`) AS `expeditions`,count(`sl`.`scan_line_id`) AS `scanned`,count(distinct `sl`.`scan_id`) AS `pallets`,max(`sl`.`odbc_date`) AS `lastScanned` from ((`vn2008`.`Tickets` `t` join `vn2008`.`expeditions` `e` on((`t`.`Id_Ticket` = `e`.`ticket_id`))) left join `vn2008`.`scan_line` `sl` on((`e`.`expeditions_id` = `sl`.`code`))) where (`t`.`Fecha` >= curdate()) group by `t`.`Id_Ruta` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `sale`
--

/*!50001 DROP VIEW IF EXISTS `sale`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `sale` AS select `m`.`Id_Movimiento` AS `id`,`m`.`Id_Article` AS `itemFk`,`m`.`Id_Ticket` AS `ticketFk`,`m`.`Concepte` AS `concept`,`m`.`Cantidad` AS `quantity`,`m`.`Preu` AS `price`,`m`.`Descuento` AS `discount`,`m`.`Reservado` AS `reserved`,`m`.`OK` AS `isPicked`,`m`.`odbc_date` AS `created`,`m`.`CostFixat` AS `priceFixed`,`m`.`PrecioFijado` AS `isPriceFixed` from `vn2008`.`Movimientos` `m` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `saleChecked`
--

/*!50001 DROP VIEW IF EXISTS `saleChecked`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `saleChecked` AS select `m`.`Id_Movimiento` AS `saleFk`,`m`.`checked` AS `isChecked` from `vn2008`.`Movimientos_checked` `m` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `saleComponent`
--

/*!50001 DROP VIEW IF EXISTS `saleComponent`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `saleComponent` AS select `mc`.`Id_Movimiento` AS `saleFk`,`mc`.`Id_Componente` AS `componentFk`,`mc`.`Valor` AS `value`,`mc`.`created` AS `created` from `vn2008`.`Movimientos_componentes` `mc` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `saleTracking`
--

/*!50001 DROP VIEW IF EXISTS `saleTracking`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `saleTracking` AS select `m`.`Id_Movimiento` AS `saleFk`,`m`.`valor` AS `isChecked`,`m`.`odbc_date` AS `created`,`m`.`original_quantity` AS `originalQuantity`,`m`.`Id_Trabajador` AS `workerFk`,`m`.`Id_Accion` AS `actionFk`,`m`.`Id_Movimiento_mark` AS `id`,`m`.`stateFk` AS `stateFk` from `vn2008`.`Movimientos_mark` `m` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `sample`
--

/*!50001 DROP VIEW IF EXISTS `sample`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `sample` AS select `e`.`id` AS `id`,`e`.`abrev` AS `code`,`e`.`descripcion` AS `description`,`e`.`visible` AS `isVisible`,`e`.`hasCompany` AS `hasCompany` from `vn2008`.`escritos` `e` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `sharingCart`
--

/*!50001 DROP VIEW IF EXISTS `sharingCart`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `sharingCart` AS select `s`.`id` AS `id`,`s`.`Id_Trabajador` AS `workerFk`,`s`.`datSTART` AS `started`,`s`.`datEND` AS `ended`,`s`.`Id_Suplente` AS `workerSubstitute`,`s`.`odbc_date` AS `created` from `vn2008`.`sharingcart` `s` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `sharingClient`
--

/*!50001 DROP VIEW IF EXISTS `sharingClient`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `sharingClient` AS select `s`.`id` AS `id`,`s`.`Id_Trabajador` AS `workerFk`,`s`.`datSTART` AS `started`,`s`.`datEND` AS `ended`,`s`.`Id_Cliente` AS `clientFk` from `vn2008`.`sharingclient` `s` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `specialPrice`
--

/*!50001 DROP VIEW IF EXISTS `specialPrice`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `specialPrice` AS select `p`.`Id_PrecioEspecial` AS `id`,`p`.`Id_Cliente` AS `clientFk`,`p`.`Id_Article` AS `itemFk`,`p`.`PrecioEspecial` AS `value` from `vn2008`.`PreciosEspeciales` `p` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `state`
--

/*!50001 DROP VIEW IF EXISTS `state`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `state` AS select `s`.`id` AS `id`,`s`.`name` AS `name`,`s`.`order` AS `order`,`s`.`alert_level` AS `alertLevel`,`s`.`code` AS `code`,`s`.`sectorProdPriority` AS `sectorProdPriority` from `vn2008`.`state` `s` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `supplier`
--

/*!50001 DROP VIEW IF EXISTS `supplier`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `supplier` AS select `p`.`Id_Proveedor` AS `id`,`p`.`Proveedor` AS `name`,`p`.`cuenta` AS `account`,`p`.`pais_id` AS `countryFk`,`p`.`NIF` AS `nif`,`p`.`Agricola` AS `isFarmer`,`p`.`Telefono` AS `phone`,`p`.`cuentaret` AS `retAccount`,`p`.`ComisionProveedor` AS `commission`,`p`.`odbc_time` AS `created`,`p`.`postcode_id` AS `postcodeFk`,`p`.`active` AS `isActive`,`p`.`Domicilio` AS `street`,`p`.`Localidad` AS `city`,`p`.`province_id` AS `provinceFk`,`p`.`codpos` AS `postCode`,`p`.`pay_met_id` AS `payMethodFk`,`p`.`pay_dem_id` AS `payDemFk`,`p`.`Alias` AS `nickname` from `vn2008`.`Proveedores` `p` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `supplierAccount`
--

/*!50001 DROP VIEW IF EXISTS `supplierAccount`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `supplierAccount` AS select `pa`.`Id_Proveedores_account` AS `id`,`pa`.`Id_Proveedor` AS `supplierFk`,`pa`.`IBAN` AS `iban`,`pa`.`entity_id` AS `bankEntityFk` from `vn2008`.`Proveedores_account` `pa` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `supplierPackaging`
--

/*!50001 DROP VIEW IF EXISTS `supplierPackaging`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `supplierPackaging` AS select `e`.`supplierFk` AS `supplierFk`,`b`.`itemFk` AS `itemFk`,`i`.`longName` AS `longName`,`s`.`name` AS `supplier`,`b`.`entryFk` AS `entryFk`,`tr`.`landed` AS `landed`,-(least(`b`.`quantity`,0)) AS `out`,greatest(`b`.`quantity`,0) AS `in`,`w`.`name` AS `almacen` from ((((((`vn`.`buy` `b` join `vn`.`item` `i` on((`i`.`id` = `b`.`itemFk`))) join `vn`.`packaging` `p` on((`p`.`itemFk` = `i`.`id`))) join `vn`.`entry` `e` on((`e`.`id` = `b`.`entryFk`))) join `vn`.`supplier` `s` on((`s`.`id` = `e`.`supplierFk`))) join `vn`.`travel` `tr` on((`tr`.`id` = `e`.`travelFk`))) join `vn`.`warehouse` `w` on((`w`.`id` = `tr`.`warehouseInFk`))) where `p`.`isPackageReturnable` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `tagL10n`
--

/*!50001 DROP VIEW IF EXISTS `tagL10n`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `tagL10n` AS select `t`.`id` AS `id`,ifnull(`i`.`name`,`t`.`name`) AS `name` from (`tag` `t` left join `tagI18n` `i` on(((`i`.`tagFk` = `t`.`id`) and (`i`.`lang` = `util`.`LANG`())))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `taxClass`
--

/*!50001 DROP VIEW IF EXISTS `taxClass`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `taxClass` AS select `c`.`iva_group_id` AS `id`,`c`.`description` AS `description`,`c`.`code` AS `code` from `vn2008`.`iva_group` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `taxClassCode`
--

/*!50001 DROP VIEW IF EXISTS `taxClassCode`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `taxClassCode` AS select `c`.`iva_group_id` AS `taxClassFk`,`c`.`date` AS `effectived`,`c`.`iva_codigo_id` AS `taxCodeFk` from `vn2008`.`iva_group_codigo` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `taxCode`
--

/*!50001 DROP VIEW IF EXISTS `taxCode`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `taxCode` AS select `ic`.`id` AS `id`,`ic`.`fecha` AS `dated`,`ic`.`codigo` AS `code`,`ic`.`iva_tipo_id` AS `taxTypeFk`,`ic`.`iva` AS `rate`,`ic`.`recargo` AS `equalizationTax`,`ic`.`tipo` AS `type`,`ic`.`link` AS `link`,`ic`.`isActive` AS `isActive`,`ic`.`updated` AS `updated`,`ic`.`transactionCode` AS `transactionCode` from `vn2008`.`iva_codigo` `ic` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `taxType`
--

/*!50001 DROP VIEW IF EXISTS `taxType`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `taxType` AS select `t`.`id` AS `id`,`t`.`alias` AS `nickname`,`t`.`isAccrued` AS `isAccrued`,`t`.`serie_id` AS `serial`,`t`.`TIPOOPE` AS `TIPOOPE`,`t`.`descripcion` AS `description`,`t`.`Id_Pais` AS `countryFk` from `vn2008`.`iva_tipo` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `ticket`
--

/*!50001 DROP VIEW IF EXISTS `ticket`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ticket` AS select `t`.`Id_Ticket` AS `id`,`t`.`Id_Cliente` AS `clientFk`,`t`.`warehouse_id` AS `warehouseFk`,`t`.`Fecha` AS `shipped`,`t`.`landing` AS `landed`,`t`.`Alias` AS `nickname`,`t`.`Factura` AS `refFk`,`t`.`Id_Consigna` AS `addressFk`,`t`.`Localizacion` AS `location`,`t`.`Solucion` AS `solution`,`t`.`Id_Ruta` AS `routeFk`,`t`.`empresa_id` AS `companyFk`,`t`.`Id_Agencia` AS `agencyModeFk`,`t`.`Prioridad` AS `priority`,`t`.`Bultos` AS `packages`,`t`.`isDeleted` AS `isDeleted`,`t`.`odbc_date` AS `created` from `vn2008`.`Tickets` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `ticketDms`
--

/*!50001 DROP VIEW IF EXISTS `ticketDms`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketDms` AS select `g`.`Id_Ticket` AS `ticketFk`,`g`.`gestdoc_id` AS `dmsFk` from `vn2008`.`tickets_gestdoc` `g` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `ticketDownBuffer`
--

/*!50001 DROP VIEW IF EXISTS `ticketDownBuffer`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketDownBuffer` AS select `td`.`ticketFk` AS `ticketFk`,`td`.`created` AS `created`,`td`.`selected` AS `selected`,concat(`tr`.`Nombre`,' ',`tr`.`Apellidos`) AS `sacador`,`pk`.`code` AS `parking` from ((((`vn`.`ticketDown` `td` left join `vn`.`shelving` `s` on((`s`.`code` = `td`.`ticketFk`))) left join `vn`.`parking` `pk` on((`s`.`parkingFk` = `pk`.`id`))) join `vn`.`ticketStateToday` `tst` on((`tst`.`ticket` = `td`.`ticketFk`))) join `vn2008`.`Trabajadores` `tr` on((`tr`.`Id_Trabajador` = `tst`.`worker`))) where (`td`.`selected` = 2) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `ticketNotInvoiced`
--

/*!50001 DROP VIEW IF EXISTS `ticketNotInvoiced`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketNotInvoiced` AS select `t`.`companyFk` AS `companyFk`,`cm`.`code` AS `companyCode`,`t`.`clientFk` AS `clientFk`,`c`.`name` AS `clientName`,`t`.`shipped` AS `shipped`,cast(sum((((`s`.`quantity` * `s`.`price`) * (100 - `s`.`discount`)) / 100)) as decimal(10,2)) AS `value` from (((`vn`.`ticket` `t` join `vn`.`sale` `s` on((`s`.`ticketFk` = `t`.`id`))) join `vn`.`client` `c` on((`c`.`id` = `t`.`clientFk`))) join `vn`.`company` `cm` on((`cm`.`id` = `t`.`companyFk`))) where (isnull(`t`.`refFk`) and (`t`.`shipped` > '2017-01-01')) group by `t`.`id` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `ticketObservation`
--

/*!50001 DROP VIEW IF EXISTS `ticketObservation`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketObservation` AS select `to`.`ticket_observation_id` AS `id`,`to`.`Id_Ticket` AS `ticketFk`,`to`.`observation_type_id` AS `observationTypeFk`,`to`.`text` AS `description` from `vn2008`.`ticket_observation` `to` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `ticketRequest`
--

/*!50001 DROP VIEW IF EXISTS `ticketRequest`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketRequest` AS select `t`.`Id_ORDEN` AS `id`,`t`.`ORDEN` AS `description`,`t`.`requesterFk` AS `requesterFk`,`t`.`atenderFk` AS `atenderFk`,`t`.`CANTIDAD` AS `quantity`,`t`.`Id_ARTICLE` AS `itemFk`,`t`.`PRECIOMAX` AS `price`,`t`.`isOk` AS `isOk`,`t`.`Id_Movimiento` AS `saleFk`,`t`.`ticketFk` AS `ticketFk`,`t`.`COMENTARIO` AS `response`,`t`.`odbc_date` AS `created` from `vn2008`.`Ordenes` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `ticketState`
--

/*!50001 DROP VIEW IF EXISTS `ticketState`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketState` AS select `i`.`odbc_date` AS `updated`,`i`.`state_id` AS `stateFk`,`i`.`Id_Trabajador` AS `workerFk`,`ts`.`Id_Ticket` AS `ticketFk`,`s`.`id` AS `state`,`s`.`order` AS `productionOrder`,`s`.`alert_level` AS `alertLevel`,`s`.`code` AS `code`,`ts`.`Id_Ticket` AS `ticket`,`i`.`Id_Trabajador` AS `worker` from ((`vn2008`.`Tickets_state` `ts` join `vncontrol`.`inter` `i` on((`i`.`inter_id` = `ts`.`inter_id`))) join `vn2008`.`state` `s` on((`s`.`id` = `i`.`state_id`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `ticketStateToday`
--

/*!50001 DROP VIEW IF EXISTS `ticketStateToday`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketStateToday` AS select `ts`.`ticket` AS `ticket`,`ts`.`state` AS `state`,`ts`.`productionOrder` AS `productionOrder`,`ts`.`alertLevel` AS `alertLevel`,`ts`.`worker` AS `worker`,`ts`.`code` AS `code`,`ts`.`updated` AS `updated` from (`vn`.`ticketState` `ts` join `vn`.`ticket` `t` on((`t`.`id` = `ts`.`ticket`))) where (`t`.`shipped` between curdate() and `MIDNIGHT`(curdate())) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `ticketToPrepare`
--

/*!50001 DROP VIEW IF EXISTS `ticketToPrepare`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketToPrepare` AS select `m`.`Id_Ticket` AS `Id_Ticket`,`mk`.`Id_Movimiento` AS `Id_Movimiento`,`mk`.`Id_Movimiento_mark` AS `Id_Movimiento_mark`,`mk`.`Id_Trabajador` AS `Id_Trabjador`,`m`.`Id_Article` AS `Id_Article`,`m`.`Concepte` AS `Concepte`,`art`.`subName` AS `subName`,(`mk`.`original_quantity` - ifnull(`is`.`quantity`,0)) AS `Cantidad`,`mk`.`original_quantity` AS `original_quantity`,hour(`t`.`shipped`) AS `Hora`,hour(`t`.`shipped`) AS `Departure`,minute(`t`.`shipped`) AS `Minuto`,`am`.`agencyFk` AS `agency_id`,`t`.`warehouseFk` AS `warehouse_id`,`a`.`provinceFk` AS `province_id`,`is`.`quantity` AS `picked` from ((((((`vn2008`.`Movimientos_mark` `mk` join `vn2008`.`Movimientos` `m` on((`m`.`Id_Movimiento` = `mk`.`Id_Movimiento`))) join `vn`.`ticket` `t` on((`m`.`Id_Ticket` = `t`.`id`))) join `vn`.`agencyMode` `am` on((`am`.`id` = `t`.`agencyModeFk`))) join `vn`.`address` `a` on((`a`.`id` = `t`.`addressFk`))) left join `vn`.`itemShelvingSale` `is` on((`is`.`saleFk` = `mk`.`Id_Movimiento`))) join `vn2008`.`Articles` `art` on((`art`.`Id_Article` = `m`.`Id_Article`))) where ((`mk`.`stateFk` = 26) and (`mk`.`valor` <> 1) and (`t`.`warehouseFk` = 1)) group by `mk`.`Id_Movimiento_mark` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `ticketTracking`
--

/*!50001 DROP VIEW IF EXISTS `ticketTracking`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketTracking` AS select `i`.`inter_id` AS `id`,`i`.`state_id` AS `stateFk`,`i`.`odbc_date` AS `created`,`i`.`Id_Ticket` AS `ticketFk`,`i`.`Id_Trabajador` AS `workerFk` from `vncontrol`.`inter` `i` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `ticketUpdateAction`
--

/*!50001 DROP VIEW IF EXISTS `ticketUpdateAction`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketUpdateAction` AS select `b`.`buo_id` AS `id`,`b`.`description` AS `description` from `vn2008`.`bionic_updating_options` `b` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `ticketWeekly`
--

/*!50001 DROP VIEW IF EXISTS `ticketWeekly`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketWeekly` AS select `t`.`Id_Ticket` AS `ticketFk`,`t`.`weekDay` AS `weekDay` from `vn2008`.`Tickets_turno` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `ticketeToPreparePrepared`
--

/*!50001 DROP VIEW IF EXISTS `ticketeToPreparePrepared`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketeToPreparePrepared` AS select `m`.`Id_Ticket` AS `Id_Ticket`,`mk`.`Id_Movimiento` AS `Id_Movimiento`,`mk`.`Id_Movimiento_mark` AS `Id_Movimiento_mark`,`mk`.`Id_Trabajador` AS `Id_Trabjador`,`m`.`Id_Article` AS `Id_Article`,`m`.`Concepte` AS `Concepte`,`art`.`subName` AS `subName`,(`mk`.`original_quantity` - ifnull(`is`.`quantity`,0)) AS `Cantidad`,`mk`.`original_quantity` AS `original_quantity`,hour(`t`.`shipped`) AS `Hora`,hour(`t`.`shipped`) AS `Departure`,minute(`t`.`shipped`) AS `Minuto`,`am`.`agencyFk` AS `agency_id`,`t`.`warehouseFk` AS `warehouse_id`,`a`.`provinceFk` AS `province_id`,`is`.`quantity` AS `picked`,`t`.`CodigoTrabajador` AS `trabajador` from (((((((`vn2008`.`Movimientos_mark` `mk` join `vn2008`.`Movimientos` `m` on((`m`.`Id_Movimiento` = `mk`.`Id_Movimiento`))) join `vn`.`ticket` `t` on((`m`.`Id_Ticket` = `t`.`id`))) join `vn`.`agencyMode` `am` on((`am`.`id` = `t`.`agencyModeFk`))) join `vn`.`address` `a` on((`a`.`id` = `t`.`addressFk`))) left join `vn`.`itemShelvingSale` `is` on((`is`.`saleFk` = `mk`.`Id_Movimiento`))) join `vn2008`.`Articles` `art` on((`art`.`Id_Article` = `m`.`Id_Article`))) left join `vn2008`.`Trabajadores` `t` on((`t`.`Id_Trabajador` = `mk`.`Id_Trabajador`))) where ((`mk`.`stateFk` = 26) and (`t`.`warehouseFk` = 1)) group by `mk`.`Id_Movimiento_mark` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `till`
--

/*!50001 DROP VIEW IF EXISTS `till`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `till` AS select `c`.`Id_Caja` AS `id`,`c`.`Cajafecha` AS `created`,`c`.`Serie` AS `serie`,`c`.`Concepto` AS `concept`,`c`.`Entrada` AS `in`,`c`.`Salida` AS `out`,`c`.`Id_Banco` AS `bankFk`,`c`.`empresa_id` AS `supplierFk`,`c`.`Partida` AS `isAccountable`,`c`.`InForeignValue` AS `inForeignValue`,`c`.`OutForeignValue` AS `outForeignValue`,`c`.`Id_Trabajador` AS `workerFk` from `vn2008`.`Cajas` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `time`
--

/*!50001 DROP VIEW IF EXISTS `time`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `time` AS select `t`.`date` AS `dated`,`t`.`period` AS `period`,`t`.`month` AS `month`,`t`.`year` AS `year`,`t`.`day` AS `day`,`t`.`week` AS `week` from `vn2008`.`time` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `travel`
--

/*!50001 DROP VIEW IF EXISTS `travel`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `travel` AS select `t`.`id` AS `id`,`t`.`shipment` AS `shipped`,`t`.`shipment_hour` AS `shipmentHour`,`t`.`landing` AS `landed`,`t`.`landing_hour` AS `landingHour`,`t`.`warehouse_id` AS `warehouseInFk`,`t`.`warehouse_id_out` AS `warehouseOutFk`,`t`.`agency_id` AS `agencyFk`,`t`.`ref` AS `ref`,`t`.`delivered` AS `isDelivered`,`t`.`received` AS `isReceived`,`t`.`m3` AS `m3`,`t`.`kg` AS `kg`,`t`.`cargoSupplierFk` AS `cargoSupplierFk`,`t`.`totalEntries` AS `totalEntries` from `vn2008`.`travel` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `unary`
--

/*!50001 DROP VIEW IF EXISTS `unary`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `unary` AS select `a`.`id` AS `id`,`a`.`parent` AS `parent` from `vn2008`.`unary` `a` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `unaryScan`
--

/*!50001 DROP VIEW IF EXISTS `unaryScan`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `unaryScan` AS select `u`.`unary_id` AS `unaryFk`,`u`.`name` AS `name`,`u`.`odbc_date` AS `created`,`u`.`type` AS `type` from `vn2008`.`unary_scan` `u` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `unaryScanLine`
--

/*!50001 DROP VIEW IF EXISTS `unaryScanLine`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `unaryScanLine` AS select `u`.`id` AS `id`,`u`.`code` AS `code`,`u`.`odbc_date` AS `created`,`u`.`unary_id` AS `unaryScanFk` from `vn2008`.`unary_scan_line` `u` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `unaryScanLineBuy`
--

/*!50001 DROP VIEW IF EXISTS `unaryScanLineBuy`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `unaryScanLineBuy` AS select `u`.`scan_line_id` AS `unaryScanLineFk`,`u`.`Id_Article` AS `itemFk` from `vn2008`.`unary_scan_line_buy` `u` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `unaryScanLineExpedition`
--

/*!50001 DROP VIEW IF EXISTS `unaryScanLineExpedition`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `unaryScanLineExpedition` AS select `u`.`scan_line_id` AS `unaryScanLineFk`,`u`.`expedition_id` AS `expeditionFk` from `vn2008`.`unary_scan_line_expedition` `u` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `user`
--

/*!50001 DROP VIEW IF EXISTS `user`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `user` AS select `account`.`user`.`id` AS `id`,`account`.`user`.`name` AS `name`,`account`.`user`.`password` AS `password`,`account`.`user`.`role` AS `role`,`account`.`user`.`active` AS `active`,`account`.`user`.`recoverPass` AS `recoverPass`,`account`.`user`.`lastPassChange` AS `lastPassChange` from `account`.`user` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `vehicle`
--

/*!50001 DROP VIEW IF EXISTS `vehicle`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `vehicle` AS select `v`.`Id_Vehiculo` AS `id`,`v`.`Matricula` AS `numberPlate`,`v`.`Marca` AS `tradeMark`,`v`.`Modelo` AS `model`,`v`.`empresa_id` AS `companyFk`,`v`.`warehouseFk` AS `warehouseFk`,`v`.`description` AS `description`,`v`.`m3` AS `m3`,`v`.`active` AS `isActive` from `vn2008`.`Vehiculos` `v` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `warehouse`
--

/*!50001 DROP VIEW IF EXISTS `warehouse`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `warehouse` AS select `t`.`id` AS `id`,`t`.`name` AS `name`,`t`.`inventario` AS `isInventory`,`t`.`fuente` AS `isFeedStock`,`t`.`is_comparative` AS `isComparative`,`t`.`comisionantes` AS `hasComission`,`t`.`reserve` AS `hasAvailable`,`t`.`isManaged` AS `isManaged`,`t`.`tpv` AS `isForTicket` from `vn2008`.`warehouse` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `warehouseAlias`
--

/*!50001 DROP VIEW IF EXISTS `warehouseAlias`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `warehouseAlias` AS select `wa`.`warehouse_alias_id` AS `id`,`wa`.`alias` AS `name` from `vn2008`.`warehouse_alias` `wa` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `workCenterHoliday`
--

/*!50001 DROP VIEW IF EXISTS `workCenterHoliday`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `workCenterHoliday` AS select `wh`.`workcenter_id` AS `workCenterFk`,`wh`.`day` AS `days`,`wh`.`year` AS `year` from `vn2008`.`workcenter_holiday` `wh` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `worker`
--

/*!50001 DROP VIEW IF EXISTS `worker`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `worker` AS select `t`.`Id_Trabajador` AS `id`,`t`.`CodigoTrabajador` AS `workerCode`,`t`.`Nombre` AS `firstName`,`t`.`Apellidos` AS `name`,`t`.`user_id` AS `userFk`,`t`.`phone` AS `phone`,`t`.`boss` AS `bossFk`,`t`.`Foto` AS `photo`,`t`.`dni` AS `fi`,`t`.`DniExpiration` AS `fiDueDate`,`t`.`CodigoTrabajador` AS `code`,`t`.`Apellidos` AS `lastName` from `vn2008`.`Trabajadores` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `workerCalendar`
--

/*!50001 DROP VIEW IF EXISTS `workerCalendar`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `workerCalendar` AS select `ce`.`business_id` AS `businessFk`,`p`.`id_trabajador` AS `workerFk`,`ce`.`calendar_state_id` AS `absenceTypeFk`,`ce`.`date` AS `dated` from (((`postgresql`.`person` `p` join `postgresql`.`profile` `pr` on((`pr`.`person_id` = `p`.`person_id`))) join `postgresql`.`business` `b` on((`b`.`client_id` = `pr`.`profile_id`))) join `postgresql`.`calendar_employee` `ce` on((`ce`.`business_id` = `b`.`business_id`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `workerDepartment`
--

/*!50001 DROP VIEW IF EXISTS `workerDepartment`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `workerDepartment` AS select `p`.`id_trabajador` AS `workerFk`,`d`.`id` AS `departmentFk` from (((`postgresql`.`person` `p` join `postgresql`.`profile` `pr` on((`pr`.`person_id` = `p`.`person_id`))) left join (`postgresql`.`business` `b` left join `postgresql`.`business_labour` `bl` on((`b`.`business_id` = `bl`.`business_id`))) on((`pr`.`profile_id` = `b`.`client_id`))) join `vn`.`department` `d` on((`d`.`id` = `bl`.`department_id`))) where ((isnull(`b`.`date_end`) and (`b`.`date_start` <= curdate())) or ((`b`.`date_end` > curdate()) and (`b`.`date_start` <= curdate()))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `workerLabour`
--

/*!50001 DROP VIEW IF EXISTS `workerLabour`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `workerLabour` AS select `b`.`business_id` AS `businessFk`,`p`.`id_trabajador` AS `workerFk`,`bl`.`workcenter_id` AS `workCenterFk`,`b`.`date_start` AS `started`,`b`.`date_end` AS `ended`,`d`.`id` AS `departmentFk` from ((((`postgresql`.`person` `p` join `postgresql`.`profile` `pr` on((`pr`.`person_id` = `p`.`person_id`))) join `postgresql`.`business` `b` on((`b`.`client_id` = `pr`.`profile_id`))) join `postgresql`.`business_labour` `bl` on((`b`.`business_id` = `bl`.`business_id`))) join `vn`.`department` `d` on((`d`.`id` = `bl`.`department_id`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `workerMedia`
--

/*!50001 DROP VIEW IF EXISTS `workerMedia`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `workerMedia` AS select `p`.`id_trabajador` AS `workerFk`,`m`.`value` AS `mediaValue` from ((((`postgresql`.`person` `p` join `postgresql`.`profile` `po` on((`po`.`person_id` = `p`.`person_id`))) join `postgresql`.`profile_media` `pom` on((`pom`.`profile_id` = `po`.`profile_id`))) join `postgresql`.`media` `m` on((`m`.`media_id` = `pom`.`media_id`))) join `postgresql`.`media_type` `mt` on((`mt`.`media_type_id` = `m`.`media_type_id`))) where (`mt`.`name` = 'movil empresa') */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `workerTeam`
--

/*!50001 DROP VIEW IF EXISTS `workerTeam`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `workerTeam` AS select `w`.`team` AS `team`,`w`.`user` AS `user`,`w`.`id` AS `id`,`t`.`Id_Trabajador` AS `Id_Trabajador` from (`vn2008`.`workerTeam` `w` left join `vn2008`.`Trabajadores` `t` on((`t`.`user_id` = `w`.`user`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `workerTeamCollegues`
--

/*!50001 DROP VIEW IF EXISTS `workerTeamCollegues`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `workerTeamCollegues` AS select distinct `w`.`Id_Trabajador` AS `workerFk`,`t`.`Id_Trabajador` AS `collegueFk` from (`vn`.`workerTeam` `w` join `vn`.`workerTeam` `t` on((`w`.`team` = `t`.`team`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `workerTimeControl_Journey`
--

/*!50001 DROP VIEW IF EXISTS `workerTimeControl_Journey`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `workerTimeControl_Journey` AS select `wtc`.`userFk` AS `userFk`,cast(`wtc`.`timed` as date) AS `dated`,cast(sum((if((`wtc`.`order` % 2),-(1),1) * (hour(`wtc`.`timed`) + (minute(`wtc`.`timed`) / 60)))) as decimal(10,2)) AS `Journey`,dayname(`wtc`.`timed`) AS `dayName`,`w`.`lastName` AS `name`,`w`.`firstName` AS `firstname` from (`vn`.`workerTimeControl` `wtc` join `vn`.`worker` `w` on((`w`.`userFk` = `wtc`.`userFk`))) group by cast(`wtc`.`timed` as date),`wtc`.`userFk` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `workerTimeJourneyNG`
--

/*!50001 DROP VIEW IF EXISTS `workerTimeJourneyNG`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `workerTimeJourneyNG` AS select `wtc`.`userFk` AS `userFk`,cast(`wtc`.`timed` as date) AS `dated`,(if((`wtc`.`order` % 2),-(1),1) * (hour(`wtc`.`timed`) + (minute(`wtc`.`timed`) / 60))) AS `Journey`,dayname(`wtc`.`timed`) AS `dayName`,`w`.`lastName` AS `name`,`w`.`firstName` AS `firstname` from (`vn`.`workerTimeControl` `wtc` join `vn`.`worker` `w` on((`w`.`userFk` = `wtc`.`userFk`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Current Database: `vn2008`
--

USE `vn2008`;

--
-- Final view structure for view `V_edi_item_track`
--

/*!50001 DROP VIEW IF EXISTS `V_edi_item_track`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `V_edi_item_track` AS select `edi`.`item_track`.`item_id` AS `item_id`,`edi`.`item_track`.`s1` AS `s1`,`edi`.`item_track`.`s2` AS `s2`,`edi`.`item_track`.`s3` AS `s3`,`edi`.`item_track`.`s4` AS `s4`,`edi`.`item_track`.`s5` AS `s5`,`edi`.`item_track`.`s6` AS `s6`,`edi`.`item_track`.`kop` AS `kop`,`edi`.`item_track`.`pac` AS `pac`,`edi`.`item_track`.`cat` AS `cat`,`edi`.`item_track`.`ori` AS `ori`,`edi`.`item_track`.`pro` AS `pro`,`edi`.`item_track`.`sub` AS `sub`,`edi`.`item_track`.`package` AS `package` from `edi`.`item_track` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `VerEspionaje`
--

/*!50001 DROP VIEW IF EXISTS `VerEspionaje`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `VerEspionaje` AS select `Trabajadores`.`CodigoTrabajador` AS `CodigoTrabajador`,`Espionajes`.`Fecha` AS `Fecha`,`Espionajes`.`HoraEntrada` AS `HoraEntrada`,`Espionajes`.`HoraSalida` AS `HoraSalida`,`Espionajes`.`Id_Equipo` AS `Id_Equipo`,`Trabajadores`.`Id_Trabajador` AS `Id_Trabajador` from (`Espionajes` join `Trabajadores` on((`Espionajes`.`Id_Trabajador` = `Trabajadores`.`Id_Trabajador`))) order by `Trabajadores`.`CodigoTrabajador`,`Espionajes`.`Fecha` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `awb_volume`
--

/*!50001 DROP VIEW IF EXISTS `awb_volume`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `awb_volume` AS select `d`.`awbFk` AS `awb_id`,(((`c`.`Etiquetas` * `a`.`density`) * if((`cu`.`Volumen` > 0),`cu`.`Volumen`,((`cu`.`X` * `cu`.`Y`) * if((`cu`.`Z` = 0),(`a`.`Medida` + 10),`cu`.`Z`)))) / 167000) AS `volume` from (((((((`vn2008`.`Compres` `c` join `vn2008`.`Articles` `a` on((`c`.`Id_Article` = `a`.`Id_Article`))) join `vn2008`.`Tipos` `t` on((`a`.`tipo_id` = `t`.`tipo_id`))) join `vn2008`.`Cubos` `cu` on((`cu`.`Id_Cubo` = `c`.`Id_Cubo`))) join `vn2008`.`Entradas` `e` on((`c`.`Id_Entrada` = `e`.`Id_Entrada`))) join `vn2008`.`travel` `tr` on((`tr`.`id` = `e`.`travel_id`))) join `vn`.`duaEntry` `de` on((`de`.`entryFk` = `e`.`Id_Entrada`))) join `vn`.`dua` `d` on((`d`.`id` = `de`.`duaFk`))) where (`tr`.`shipment` > makedate((year(curdate()) - 1),1)) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `cdr`
--

/*!50001 DROP VIEW IF EXISTS `cdr`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `cdr` AS select `c`.`call_date` AS `calldate`,`c`.`clid` AS `clid`,`c`.`src` AS `src`,`c`.`dst` AS `dst`,`c`.`dcontext` AS `dcontext`,`c`.`channel` AS `channel`,`c`.`dst_channel` AS `dstchannel`,`c`.`last_app` AS `lastapp`,`c`.`last_data` AS `lastdata`,`c`.`duration` AS `duration`,`c`.`billsec` AS `billsec`,`c`.`disposition` AS `disposition`,`c`.`ama_flags` AS `amaflags`,`c`.`account_code` AS `accountcode`,`c`.`unique_id` AS `uniqueid`,`c`.`user_field` AS `userfield` from `pbx`.`cdr` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `clientMana`
--

/*!50001 DROP VIEW IF EXISTS `clientMana`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `clientMana` AS select `t`.`Id_Cliente` AS `Id_Cliente`,`mc`.`Valor` AS `ManaUnitario`,(`mc`.`Valor` * `m`.`Cantidad`) AS `ManaTotal`,`t`.`Id_Ticket` AS `Id_Ticket`,`m`.`Id_Article` AS `Id_Article`,`m`.`Concepte` AS `Concepte`,`m`.`Cantidad` AS `Cantidad`,`m`.`Preu` AS `Preu`,`t`.`Fecha` AS `Fecha`,`m`.`Id_Movimiento` AS `Id_Movimiento` from ((((`vn2008`.`Tickets` `t` join `vn2008`.`Movimientos` `m` on((`m`.`Id_Ticket` = `t`.`Id_Ticket`))) join `vn2008`.`Movimientos_componentes` `mc` on((`mc`.`Id_Movimiento` = `m`.`Id_Movimiento`))) join `vn2008`.`tarifa_componentes` `tc` on((`tc`.`Id_Componente` = `mc`.`Id_Componente`))) join `vn2008`.`tarifa_componentes_series` `tcs` on((`tc`.`tarifa_componentes_series_id` = `tcs`.`tarifa_componentes_series_id`))) where ((`t`.`Fecha` >= '2016-01-01') and (`tcs`.`Serie` = 'cartera_comercial') and (`mc`.`Valor` <> 0)) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `edi_article`
--

/*!50001 DROP VIEW IF EXISTS `edi_article`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `edi_article` AS select `edi`.`item`.`id` AS `id`,`edi`.`item`.`product_name` AS `product_name`,`edi`.`item`.`name` AS `name`,`edi`.`item`.`plant_id` AS `plant_id`,`edi`.`item`.`group_id` AS `group_id`,`edi`.`item`.`entry_date` AS `entry_date`,`edi`.`item`.`expiry_date` AS `expiry_date`,`edi`.`item`.`change_date_time` AS `change_date_time` from `edi`.`item` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `edi_bucket`
--

/*!50001 DROP VIEW IF EXISTS `edi_bucket`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `edi_bucket` AS select (cast(`edi`.`bucket`.`bucket_id` as char charset utf8) collate utf8_general_ci) AS `bucket_id`,`edi`.`bucket`.`bucket_type_id` AS `bucket_type_id`,`edi`.`bucket`.`description` AS `description`,`edi`.`bucket`.`x_size` AS `x_size`,`edi`.`bucket`.`y_size` AS `y_size`,`edi`.`bucket`.`z_size` AS `z_size`,`edi`.`bucket`.`entry_date` AS `entry_date`,`edi`.`bucket`.`expiry_date` AS `expiry_date`,`edi`.`bucket`.`change_date_time` AS `change_date_time` from `edi`.`bucket` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `edi_bucket_type`
--

/*!50001 DROP VIEW IF EXISTS `edi_bucket_type`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `edi_bucket_type` AS select `edi`.`bucket_type`.`bucket_type_id` AS `bucket_type_id`,`edi`.`bucket_type`.`description` AS `description`,`edi`.`bucket_type`.`entry_date` AS `entry_date`,`edi`.`bucket_type`.`expiry_date` AS `expiry_date`,`edi`.`bucket_type`.`change_date_time` AS `change_date_time` from `edi`.`bucket_type` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `edi_feature`
--

/*!50001 DROP VIEW IF EXISTS `edi_feature`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `edi_feature` AS select `edi`.`feature`.`item_id` AS `item_id`,`edi`.`feature`.`feature_type_id` AS `feature_type_id`,`edi`.`feature`.`feature_value` AS `feature_value`,`edi`.`feature`.`entry_date` AS `entry_date`,`edi`.`feature`.`expiry_date` AS `expiry_date`,`edi`.`feature`.`change_date_time` AS `change_date_time` from `edi`.`feature` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `edi_genus`
--

/*!50001 DROP VIEW IF EXISTS `edi_genus`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `edi_genus` AS select `edi`.`genus`.`genus_id` AS `genus_id`,`edi`.`genus`.`latin_genus_name` AS `latin_genus_name`,`edi`.`genus`.`entry_date` AS `entry_date`,`edi`.`genus`.`expiry_date` AS `expiry_date`,`edi`.`genus`.`change_date_time` AS `change_date_time` from `edi`.`genus` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `edi_item_feature`
--

/*!50001 DROP VIEW IF EXISTS `edi_item_feature`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `edi_item_feature` AS select `edi`.`item_feature`.`item_id` AS `item_id`,`edi`.`item_feature`.`presentation_order` AS `presentation_order`,`edi`.`item_feature`.`feature` AS `feature`,`edi`.`item_feature`.`regulation_type` AS `regulation_type`,`edi`.`item_feature`.`entry_date` AS `entry_date`,`edi`.`item_feature`.`expiry_date` AS `expiry_date`,`edi`.`item_feature`.`change_date_time` AS `change_date_time` from `edi`.`item_feature` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `edi_plant`
--

/*!50001 DROP VIEW IF EXISTS `edi_plant`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `edi_plant` AS select `edi`.`plant`.`plant_id` AS `plant_id`,`edi`.`plant`.`genus_id` AS `genus_id`,`edi`.`plant`.`specie_id` AS `specie_id`,`edi`.`plant`.`entry_date` AS `entry_date`,`edi`.`plant`.`expiry_date` AS `expiry_date`,`edi`.`plant`.`change_date_time` AS `change_date_time` from `edi`.`plant` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `edi_specie`
--

/*!50001 DROP VIEW IF EXISTS `edi_specie`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `edi_specie` AS select `edi`.`specie`.`specie_id` AS `specie_id`,`edi`.`specie`.`genus_id` AS `genus_id`,`edi`.`specie`.`latin_species_name` AS `latin_species_name`,`edi`.`specie`.`entry_date` AS `entry_date`,`edi`.`specie`.`expiry_date` AS `expiry_date`,`edi`.`specie`.`change_date_time` AS `change_date_time` from `edi`.`specie` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `edi_supplier`
--

/*!50001 DROP VIEW IF EXISTS `edi_supplier`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `edi_supplier` AS select `edi`.`supplier`.`supplier_id` AS `supplier_id`,`edi`.`supplier`.`company_name` AS `company_name` from `edi`.`supplier` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `edi_type`
--

/*!50001 DROP VIEW IF EXISTS `edi_type`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `edi_type` AS select `edi`.`type`.`type_id` AS `type_id`,`edi`.`type`.`type_group_id` AS `type_group_id`,`edi`.`type`.`description` AS `description`,`edi`.`type`.`entry_date` AS `entry_date`,`edi`.`type`.`expiry_date` AS `expiry_date`,`edi`.`type`.`change_date_time` AS `change_date_time` from `edi`.`type` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `edi_value`
--

/*!50001 DROP VIEW IF EXISTS `edi_value`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `edi_value` AS select `edi`.`value`.`type_id` AS `type_id`,`edi`.`value`.`type_value` AS `type_value`,`edi`.`value`.`type_description` AS `type_description`,`edi`.`value`.`entry_date` AS `entry_date`,`edi`.`value`.`expiry_date` AS `expiry_date`,`edi`.`value`.`change_date_time` AS `change_date_time` from `edi`.`value` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemTag`
--

/*!50001 DROP VIEW IF EXISTS `itemTag`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemTag` AS select `i`.`id` AS `id`,`i`.`itemFk` AS `itemFk`,`i`.`tagFk` AS `tagFk`,`i`.`value` AS `value`,`i`.`priority` AS `priority` from `vn`.`itemTag` `i` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `item_entry_in`
--

/*!50001 DROP VIEW IF EXISTS `item_entry_in`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `item_entry_in` AS select `t`.`warehouse_id` AS `warehouse_id`,`t`.`landing` AS `dat`,`m`.`Id_Article` AS `item_id`,`m`.`Cantidad` AS `amount`,`t`.`received` AS `received`,`e`.`Redada` AS `isVirtualStock` from ((`Compres` `m` join `Entradas` `e` on((`m`.`Id_Entrada` = `e`.`Id_Entrada`))) join `travel` `t` on((`e`.`travel_id` = `t`.`id`))) where ((`e`.`Inventario` = 0) and (`m`.`Cantidad` <> 0)) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `item_entry_out`
--

/*!50001 DROP VIEW IF EXISTS `item_entry_out`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `item_entry_out` AS select `t`.`warehouse_id_out` AS `warehouse_id`,`t`.`shipment` AS `dat`,`m`.`Id_Article` AS `item_id`,-(`m`.`Cantidad`) AS `amount`,(`t`.`delivered` or ifnull(`co`.`valor`,0)) AS `delivered` from (((`Compres` `m` join `Entradas` `e` on((`m`.`Id_Entrada` = `e`.`Id_Entrada`))) join `travel` `t` on((`e`.`travel_id` = `t`.`id`))) left join `Compres_ok` `co` on(((`co`.`Id_Compra` = `m`.`Id_Compra`) and (`co`.`Id_Accion` = 3) and (`co`.`valor` <> 0)))) where ((`e`.`Inventario` = 0) and (`e`.`Redada` = 0) and (`m`.`Cantidad` <> 0)) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `item_out`
--

/*!50001 DROP VIEW IF EXISTS `item_out`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `item_out` AS select `t`.`warehouse_id` AS `warehouse_id`,`t`.`Fecha` AS `dat`,`m`.`Id_Article` AS `item_id`,-(`m`.`Cantidad`) AS `amount`,`m`.`OK` AS `ok`,`m`.`Reservado` AS `Reservado`,`t`.`Factura` AS `invoice`,`m`.`Id_Movimiento` AS `saleFk`,`m`.`Id_Ticket` AS `ticketFk` from (`Movimientos` `m` join `Tickets` `t` on((`m`.`Id_Ticket` = `t`.`Id_Ticket`))) where (`m`.`Cantidad` <> 0) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `manaByTicket`
--

/*!50001 DROP VIEW IF EXISTS `manaByTicket`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `manaByTicket` AS select `t`.`Id_Ticket` AS `Id_Ticket`,`t`.`Fecha` AS `Fecha`,`cs`.`Id_cliente` AS `Id_Cliente`,(`m`.`Cantidad` * `mc`.`Valor`) AS `mana` from (((`Tickets` `t` join `Consignatarios` `cs` on((`t`.`Id_Consigna` = `cs`.`id_consigna`))) join `Movimientos` `m` on((`m`.`Id_Ticket` = `t`.`Id_Ticket`))) join `Movimientos_componentes` `mc` on((`mc`.`Id_Movimiento` = `m`.`Id_Movimiento`))) where ((`mc`.`Id_Componente` in (37,39)) and (`t`.`Fecha` between '2016-01-01' and curdate())) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `order`
--

/*!50001 DROP VIEW IF EXISTS `order`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `order` AS select `hedera`.`order`.`id` AS `id`,`hedera`.`order`.`date_make` AS `date_make`,`hedera`.`order`.`date_send` AS `date_send`,`hedera`.`order`.`customer_id` AS `customer_id`,`hedera`.`order`.`delivery_method_id` AS `delivery_method_id`,`hedera`.`order`.`agency_id` AS `agency_id`,`hedera`.`order`.`address_id` AS `address_id`,`hedera`.`order`.`note` AS `note`,`hedera`.`order`.`confirmed` AS `confirmed`,`hedera`.`order`.`is_bionic` AS `is_bionic`,`hedera`.`order`.`source_app` AS `source_app` from `hedera`.`order` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `order_component`
--

/*!50001 DROP VIEW IF EXISTS `order_component`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `order_component` AS select `c`.`order_row_id` AS `order_row_id`,`c`.`component_id` AS `component_id`,`c`.`price` AS `price` from `hedera`.`order_component` `c` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `order_row`
--

/*!50001 DROP VIEW IF EXISTS `order_row`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `order_row` AS select `order_row`.`id` AS `id`,`order_row`.`order_id` AS `order_id`,`order_row`.`item_id` AS `item_id`,`order_row`.`warehouse_id` AS `warehouse_id`,`order_row`.`shipment` AS `shipment`,`order_row`.`amount` AS `amount`,`order_row`.`price` AS `price`,`order_row`.`rate` AS `rate`,`order_row`.`created` AS `created`,`order_row`.`Id_Movimiento` AS `Id_Movimiento` from `hedera`.`order_row` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `person_user`
--

/*!50001 DROP VIEW IF EXISTS `person_user`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `person_user` AS select `u`.`id` AS `id`,`u`.`role` AS `mysql_user_id`,`u`.`name` AS `name`,`u`.`password` AS `password`,`u`.`active` AS `active`,`u`.`lastPassChange` AS `last_pass_change` from `account`.`user` `u` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `person_user_idtrabajador`
--

/*!50001 DROP VIEW IF EXISTS `person_user_idtrabajador`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `person_user_idtrabajador` AS select `t`.`Id_Trabajador` AS `Id_Trabajador` from (`vn2008`.`person_user` `p` join `vn2008`.`Trabajadores` `t` on((`p`.`id` = `t`.`user_id`))) where (`t`.`user_id` = `account`.`userGetId`()) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `proveedores_clientes`
--

/*!50001 DROP VIEW IF EXISTS `proveedores_clientes`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `proveedores_clientes` AS select `Proveedores`.`Id_Proveedor` AS `Id_Proveedor`,`Proveedores`.`Proveedor` AS `Proveedor`,`Clientes`.`id_cliente` AS `Id_Cliente`,`Clientes`.`cliente` AS `Cliente` from (`Proveedores` join `Clientes` on((`Proveedores`.`NIF` = `Clientes`.`if`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `sms`
--

/*!50001 DROP VIEW IF EXISTS `sms`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `sms` AS select `t`.`id` AS `id`,`t`.`senderFk` AS `Id_trabajador`,`t`.`destinationFk` AS `Id_Cliente`,`t`.`sender` AS `from`,`t`.`destination` AS `to`,`t`.`message` AS `text`,`t`.`statusCode` AS `sent`,`t`.`status` AS `response`,`t`.`created` AS `DATE_ODBC` from `vn`.`sms` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `tag`
--

/*!50001 DROP VIEW IF EXISTS `tag`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `tag` AS select `t`.`id` AS `id`,`t`.`name` AS `name`,`t`.`isFree` AS `isFree`,`t`.`isQuantitatif` AS `isQuantitatif`,`t`.`sourceTable` AS `sourceTable`,`t`.`unit` AS `unit` from `vn`.`tag` `t` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `tarifa_componentes`
--

/*!50001 DROP VIEW IF EXISTS `tarifa_componentes`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `tarifa_componentes` AS select `bi`.`tarifa_componentes`.`Id_Componente` AS `Id_Componente`,`bi`.`tarifa_componentes`.`Componente` AS `Componente`,`bi`.`tarifa_componentes`.`tarifa_componentes_series_id` AS `tarifa_componentes_series_id`,`bi`.`tarifa_componentes`.`tarifa_class` AS `tarifa_class`,`bi`.`tarifa_componentes`.`tax` AS `tax`,`bi`.`tarifa_componentes`.`is_renewable` AS `is_renewable` from `bi`.`tarifa_componentes` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `tarifa_componentes_series`
--

/*!50001 DROP VIEW IF EXISTS `tarifa_componentes_series`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `tarifa_componentes_series` AS select `bi`.`tarifa_componentes_series`.`tarifa_componentes_series_id` AS `tarifa_componentes_series_id`,`bi`.`tarifa_componentes_series`.`Serie` AS `Serie`,`bi`.`tarifa_componentes_series`.`base` AS `base` from `bi`.`tarifa_componentes_series` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `ticketCreationData`
--

/*!50001 DROP VIEW IF EXISTS `ticketCreationData`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketCreationData` AS select dayname(`h`.`confirm_date`) AS `DiadelaSemana`,hour(`h`.`confirm_date`) AS `Hora`,cast(`h`.`confirm_date` as date) AS `Fecha`,`h`.`source_app` AS `Dispositivo` from `hedera`.`order` `h` where `h`.`confirm_date` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_Agenda`
--

/*!50001 DROP VIEW IF EXISTS `v_Agenda`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_Agenda` AS select 'P' AS `Tipo`,`Proveedores`.`Id_Proveedor` AS `Id`,`Proveedores`.`Proveedor` AS `Nombre`,`Proveedores`.`Telefono` AS `Telephone` from `Proveedores` where (`Proveedores`.`Telefono` is not null) union select 'C' AS `Tipo`,`Clientes`.`id_cliente` AS `Id`,`Clientes`.`cliente` AS `Cliente`,`Clientes`.`telefono` AS `Telefono` from `Clientes` where (`Clientes`.`telefono` is not null) union select 'C' AS `Tipo`,`Clientes`.`id_cliente` AS `Id`,`Clientes`.`cliente` AS `Cliente`,`Clientes`.`movil` AS `Movil` from `Clientes` where (`Clientes`.`movil` is not null) union select if(isnull(`Relaciones`.`Id_Proveedor`),'C','P') AS `Tipo`,if(isnull(`Relaciones`.`Id_Proveedor`),`Relaciones`.`Id_Cliente`,`Relaciones`.`Id_Proveedor`) AS `Id`,`Contactos`.`Nombre` AS `Nombre`,`Contactos`.`Telefono` AS `Telefono` from (`Contactos` join `Relaciones` on((`Contactos`.`Id_Contacto` = `Relaciones`.`Id_Contacto`))) where (`Contactos`.`Telefono` is not null) union select if(isnull(`Relaciones`.`Id_Proveedor`),'C','P') AS `Tipo`,if(isnull(`Relaciones`.`Id_Proveedor`),`Relaciones`.`Id_Cliente`,`Relaciones`.`Id_Proveedor`) AS `Id`,`Contactos`.`Nombre` AS `Nombre`,`Contactos`.`Movil` AS `Movil` from (`Contactos` join `Relaciones` on((`Contactos`.`Id_Contacto` = `Relaciones`.`Id_Contacto`))) where (`Contactos`.`Movil` is not null) union select 'T' AS `Tipo`,`Trabajadores`.`Id_Trabajador` AS `Id_Trabajador`,`Trabajadores`.`CodigoTrabajador` AS `CodigoTrabajador`,`Trabajadores`.`extension` AS `extension` from `Trabajadores` where (`Trabajadores`.`extension` is not null) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_Agenda2`
--

/*!50001 DROP VIEW IF EXISTS `v_Agenda2`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_Agenda2` AS select `v_Agenda`.`Tipo` AS `Tipo`,`v_Agenda`.`Id` AS `Id`,`v_Agenda`.`Nombre` AS `Nombre`,replace(`v_Agenda`.`Telephone`,' ','') AS `Telefono` from `v_Agenda` where `v_Agenda`.`Telephone` group by replace(`v_Agenda`.`Telephone`,' ','') */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_Articles_botanical`
--

/*!50001 DROP VIEW IF EXISTS `v_Articles_botanical`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_Articles_botanical` AS select `ab`.`Id_Article` AS `Id_Article`,ifnull(`ab`.`botanical`,concat(`g`.`latin_genus_name`,' ',ifnull(`s`.`latin_species_name`,''))) AS `edi_botanic` from ((`vn2008`.`Articles_botanical` `ab` left join `edi`.`genus` `g` on((`ab`.`genus_id` = `g`.`genus_id`))) left join `edi`.`specie` `s` on((`s`.`specie_id` = `ab`.`specie_id`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_Movimientos_Volumen_shipping_charge`
--

/*!50001 DROP VIEW IF EXISTS `v_Movimientos_Volumen_shipping_charge`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8mb4 */;
/*!50001 SET character_set_results     = utf8mb4 */;
/*!50001 SET collation_connection      = utf8mb4_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_Movimientos_Volumen_shipping_charge` AS select `s`.`ticketFk` AS `Id_Ticket`,`t`.`routeFk` AS `Id_Ruta`,`s`.`id` AS `Id_Movimiento`,`t`.`shipped` AS `Fecha`,`az`.`price` AS `price`,((((`s`.`quantity` * `r`.`cm3`) * `az`.`price`) * `i`.`compression`) / `cb`.`volume`) AS `freight`,(((`s`.`quantity` * `r`.`cm3`) * `i`.`compression`) / 1000000) AS `volume` from ((((((((`vn`.`sale` `s` join `vn`.`item` `i` on((`i`.`id` = `s`.`itemFk`))) join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `vn`.`address` `c` on((`c`.`id` = `t`.`addressFk`))) join `vn`.`packaging` `cb` on((`cb`.`id` = '94'))) join `vn`.`agencyMode` `a` on((`a`.`id` = `t`.`agencyModeFk`))) join `bi`.`rotacion` `r` on(((`r`.`Id_Article` = `s`.`itemFk`) and (`r`.`warehouse_id` = `t`.`warehouseFk`)))) join `vn`.`agencyProvince` `ap` on(((`ap`.`agencyFk` = `a`.`agencyFk`) and (`ap`.`provinceFk` = `c`.`provinceFk`) and (`ap`.`warehouseFk` = `t`.`warehouseFk`)))) straight_join `vn`.`agencyModeZone` `az` on(((`az`.`agencyModeFk` = `t`.`agencyModeFk`) and (`az`.`zone` = `ap`.`zone`) and (`az`.`warehouseFk` = `t`.`warehouseFk`) and (`az`.`itemFk` = 71)))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_Ordenes`
--

/*!50001 DROP VIEW IF EXISTS `v_Ordenes`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_Ordenes` AS select `Ordenes`.`Id_ORDEN` AS `Id_ORDEN`,`Ordenes`.`ORDEN` AS `ORDEN`,`Ordenes`.`datORDEN` AS `datORDEN`,`Ordenes`.`datTICKET` AS `datTICKET`,`Ordenes`.`CodVENDEDOR` AS `CodVENDEDOR`,`Ordenes`.`CodCOMPRADOR` AS `CodCOMPRADOR`,`Ordenes`.`CANTIDAD` AS `CANTIDAD`,`Ordenes`.`PRECIOMAX` AS `PRECIOMAX`,`Ordenes`.`PREU` AS `PREU`,`Ordenes`.`Id_ARTICLE` AS `Id_ARTICLE`,`Ordenes`.`Id_CLIENTE` AS `Id_CLIENTE`,`Ordenes`.`COMENTARIO` AS `COMENTARIO`,`Ordenes`.`OK` AS `OK`,`Ordenes`.`TOTAL` AS `TOTAL`,`Ordenes`.`datCOMPRA` AS `datCOMPRA`,`Ordenes`.`KO` AS `KO`,`Ordenes`.`Id_Movimiento` AS `Id_Movimiento`,`Ordenes`.`odbc_date` AS `odbc_date` from `Ordenes` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_XDiario_ALL`
--

/*!50001 DROP VIEW IF EXISTS `v_XDiario_ALL`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_XDiario_ALL` AS select `bi`.`XDiario_ALL`.`empresa_id` AS `empresa_id`,`bi`.`XDiario_ALL`.`SUBCTA` AS `SUBCTA`,`bi`.`XDiario_ALL`.`Eurodebe` AS `Eurodebe`,`bi`.`XDiario_ALL`.`Eurohaber` AS `Eurohaber`,`bi`.`XDiario_ALL`.`Fecha` AS `Fecha`,`bi`.`XDiario_ALL`.`FECHA_EX` AS `FECHA_EX` from `bi`.`XDiario_ALL` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_accion`
--

/*!50001 DROP VIEW IF EXISTS `v_accion`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_accion` AS select `vncontrol`.`accion`.`accion_id` AS `accion_id`,`vncontrol`.`accion`.`accion` AS `accion` from `vncontrol`.`accion` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_account`
--

/*!50001 DROP VIEW IF EXISTS `v_account`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_account` AS select `a`.`id` AS `user_id` from `account`.`account` `a` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_analisis_ventas`
--

/*!50001 DROP VIEW IF EXISTS `v_analisis_ventas`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_analisis_ventas` AS select `bi`.`analisis_ventas`.`Familia` AS `Familia`,`bi`.`analisis_ventas`.`Reino` AS `Reino`,`bi`.`analisis_ventas`.`Comercial` AS `Comercial`,`bi`.`analisis_ventas`.`Comprador` AS `Comprador`,`bi`.`analisis_ventas`.`Provincia` AS `Provincia`,`bi`.`analisis_ventas`.`almacen` AS `almacen`,`bi`.`analisis_ventas`.`Año` AS `Año`,`bi`.`analisis_ventas`.`Mes` AS `Mes`,`bi`.`analisis_ventas`.`Semana` AS `Semana`,`bi`.`analisis_ventas`.`Vista` AS `Vista`,`bi`.`analisis_ventas`.`Importe` AS `Importe` from `bi`.`analisis_ventas` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_awb_volumen`
--

/*!50001 DROP VIEW IF EXISTS `v_awb_volumen`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_awb_volumen` AS select `a`.`id` AS `awb_id`,`a`.`codigo` AS `codigo`,`a`.`importe` AS `importe`,cast(sum(`v`.`volume`) as signed) AS `Vol_Total` from (`vn2008`.`awb` `a` join `vn2008`.`awb_volume` `v` on((`v`.`awb_id` = `a`.`id`))) group by `a`.`id` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_barcodes`
--

/*!50001 DROP VIEW IF EXISTS `v_barcodes`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_barcodes` AS select `Articles`.`Id_Article` AS `code`,`Articles`.`Id_Article` AS `Id_Article` from `Articles` union all select `barcodes`.`code` AS `code`,`barcodes`.`Id_Article` AS `Id_Article` from `barcodes` union all select `c`.`Id_Compra` AS `Id_Compra`,`c`.`Id_Article` AS `Id_Article` from ((`Compres` `c` join `Entradas` `e` on((`c`.`Id_Entrada` = `e`.`Id_Entrada`))) join `travel` `tr` on((`tr`.`id` = `e`.`travel_id`))) where (`tr`.`landing` >= (curdate() + interval -(15) day)) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_botanic_export`
--

/*!50001 DROP VIEW IF EXISTS `v_botanic_export`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_botanic_export` AS select concat(ifnull(concat(`eg`.`latin_genus_name`,' '),''),ifnull(`es`.`latin_species_name`,'')) AS `Nom_botanic`,`be`.`Id_Paises` AS `Id_Paises`,`be`.`restriction` AS `restriction`,`be`.`description` AS `description` from ((`vn2008`.`botanic_export` `be` left join `vn2008`.`edi_genus` `eg` on((`be`.`edi_genus_id` = `eg`.`genus_id`))) left join `vn2008`.`edi_specie` `es` on((`be`.`edi_specie_id` = `es`.`specie_id`))) order by concat(`eg`.`latin_genus_name`,' ',`es`.`latin_species_name`) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_compres`
--

/*!50001 DROP VIEW IF EXISTS `v_compres`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_compres` AS select `TP`.`Id_Tipo` AS `Familia`,`RN`.`id` AS `reino_id`,`C`.`Id_Compra` AS `Id_Compra`,`C`.`Id_Entrada` AS `Id_Entrada`,`C`.`Id_Article` AS `Id_Article`,`C`.`Cantidad` AS `Cantidad`,`C`.`Costefijo` AS `Costefijo`,`C`.`Portefijo` AS `Portefijo`,`C`.`Novincular` AS `Novincular`,`C`.`Etiquetas` AS `Etiquetas`,`C`.`Packing` AS `Packing`,`C`.`grouping` AS `grouping`,`C`.`Comisionfija` AS `Comisionfija`,`C`.`Embalajefijo` AS `Embalajefijo`,`an`.`nicho` AS `Nicho`,`C`.`Id_Cubo` AS `Id_Cubo`,`C`.`Tarifa1` AS `Tarifa1`,`C`.`Tarifa2` AS `Tarifa2`,`C`.`Tarifa3` AS `Tarifa3`,`C`.`PVP` AS `PVP`,`C`.`Vida` AS `Vida`,`C`.`Id_Trabajador` AS `Id_Trabajador`,`C`.`punteo` AS `punteo`,`C`.`odbc_date` AS `odbc_date`,`E`.`Inventario` AS `Inventario`,`E`.`Id_Proveedor` AS `Id_Proveedor`,`E`.`Fecha` AS `Fecha`,`E`.`Confirmada` AS `Confirmada`,`E`.`Redada` AS `Redada`,`E`.`empresa_id` AS `empresa_id`,`E`.`travel_id` AS `travel_id`,`E`.`Pedida` AS `Pedida`,`E`.`recibida_id` AS `recibida_id`,`TR`.`id` AS `id`,`TR`.`shipment` AS `shipment`,`TR`.`landing` AS `landing`,`TR`.`warehouse_id` AS `warehouse_id`,`TR`.`warehouse_id_out` AS `warehouse_id_out`,`TR`.`agency_id` AS `agency_id`,`TR`.`ref` AS `ref`,`TR`.`delivered` AS `delivered`,`TR`.`received` AS `received`,`A`.`Article` AS `Article`,`A`.`Medida` AS `Medida`,`A`.`Tallos` AS `Tallos`,`C`.`caja` AS `caja`,`A`.`Categoria` AS `Categoria`,`A`.`id_origen` AS `id_origen`,`TP`.`Id_Tipo` AS `Tipo`,`A`.`tipo_id` AS `tipo_id`,`A`.`Color` AS `Color`,`A`.`Min` AS `Min`,(((`C`.`Costefijo` + `C`.`Embalajefijo`) + `C`.`Comisionfija`) + `C`.`Portefijo`) AS `Coste`,`W_OUT`.`fuente` AS `fuente`,`A`.`iva_group_id` AS `iva_group_id`,(if((`cb`.`Volumen` > 0),`cb`.`Volumen`,((`cb`.`X` * `cb`.`Y`) * if((`cb`.`Z` = 0),(`A`.`Medida` + 10),`cb`.`Z`))) * `C`.`Etiquetas`) AS `cm3`,`A`.`producer_id` AS `producer_id` from (((((((((`Compres` `C` join `Entradas` `E` on((`C`.`Id_Entrada` = `E`.`Id_Entrada`))) join `travel` `TR` on((`TR`.`id` = `E`.`travel_id`))) join `warehouse` `W_IN` on((`W_IN`.`id` = `TR`.`warehouse_id`))) join `warehouse` `W_OUT` on((`W_OUT`.`id` = `TR`.`warehouse_id_out`))) join `Articles` `A` on((`C`.`Id_Article` = `A`.`Id_Article`))) join `Tipos` `TP` on((`A`.`tipo_id` = `TP`.`tipo_id`))) join `reinos` `RN` on((`RN`.`id` = `TP`.`reino_id`))) join `Cubos` `cb` on((`cb`.`Id_Cubo` = `C`.`Id_Cubo`))) left join `Articles_nicho` `an` on(((`A`.`Id_Article` = `an`.`Id_Article`) and (`an`.`warehouse_id` = `W_IN`.`id`)))) where ((not(`W_IN`.`fuente`)) and (not(`E`.`Inventario`)) and (not(`E`.`Redada`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_departure_limit`
--

/*!50001 DROP VIEW IF EXISTS `v_departure_limit`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_departure_limit` AS select `cache`.`departure_limit`.`warehouse_id` AS `warehouse_id`,`cache`.`departure_limit`.`fecha` AS `fecha`,`cache`.`departure_limit`.`hora` AS `hora`,`cache`.`departure_limit`.`minSpeed` AS `minSpeed` from `cache`.`departure_limit` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_descuadre_bionic`
--

/*!50001 DROP VIEW IF EXISTS `v_descuadre_bionic`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_descuadre_bionic` AS select `t`.`Id_Ticket` AS `Id_Ticket`,`t`.`Alias` AS `Alias`,`m`.`Concepte` AS `Concepte`,sum(`mc`.`Valor`) AS `suma_componente`,`m`.`Preu` AS `Preu`,`m`.`Descuento` AS `Descuento`,(((`m`.`Preu` * (100 - `m`.`Descuento`)) / 100) - sum(`mc`.`Valor`)) AS `diferencia`,`t`.`Fecha` AS `Fecha`,((`m`.`Preu` > 0) and (`tp`.`reino_id` <> 6) and (`a`.`tipo_id` not in (7,115))) AS `benvenut` from ((((((`Movimientos` `m` join `Tickets` `t` on((`m`.`Id_Ticket` = `t`.`Id_Ticket`))) join `Clientes` `c` on((`t`.`Id_Cliente` = `c`.`id_cliente`))) join `warehouse` `w` on((`w`.`id` = `t`.`warehouse_id`))) join `Articles` `a` on((`m`.`Id_Article` = `a`.`Id_Article`))) join `Tipos` `tp` on((`a`.`tipo_id` = `tp`.`tipo_id`))) left join `Movimientos_componentes` `mc` on((`m`.`Id_Movimiento` = `mc`.`Id_Movimiento`))) where ((`t`.`Fecha` >= '2015-09-01') and (`t`.`empresa_id` in (442,791,567)) and `w`.`reserve` and `c`.`real` and (`tp`.`reino_id` <> 6)) group by `m`.`Id_Movimiento` having ((abs(`diferencia`) > 0.01) or isnull(`diferencia`)) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_descuadre_porte2`
--

/*!50001 DROP VIEW IF EXISTS `v_descuadre_porte2`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_descuadre_porte2` AS select `t`.`Id_Ticket` AS `Id_Ticket`,(`mc`.`Valor` * `m`.`Cantidad`) AS `suma_componente`,`t`.`Fecha` AS `Fecha` from (((`vn2008`.`Movimientos` `m` left join `vn2008`.`Movimientos_componentes` `mc` on((`m`.`Id_Movimiento` = `mc`.`Id_Movimiento`))) join `vn2008`.`tarifa_componentes` `tc` on(((`tc`.`Id_Componente` = `mc`.`Id_Componente`) and (`tc`.`tarifa_componentes_series_id` = 6)))) join `vn2008`.`Tickets` `t` on((`t`.`Id_Ticket` = `m`.`Id_Ticket`))) where ((`t`.`Fecha` >= '2015-09-01') and (`t`.`empresa_id` in (442,791,567))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_descuadre_portekk`
--

/*!50001 DROP VIEW IF EXISTS `v_descuadre_portekk`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_descuadre_portekk` AS select `t`.`Id_Ticket` AS `Id_Ticket`,round(sum((`mc`.`Valor` * `m`.`Cantidad`)),2) AS `suma_componente`,round(`es`.`shipping_charge`,2) AS `teorico_agencia`,round((sum((`mc`.`Valor` * `m`.`Cantidad`)) - `es`.`shipping_charge`),2) AS `diferencia`,`t`.`Fecha` AS `Fecha` from ((((`vn2008`.`Movimientos` `m` left join `vn2008`.`Movimientos_componentes` `mc` on((`m`.`Id_Movimiento` = `mc`.`Id_Movimiento`))) join `vn2008`.`tarifa_componentes` `tc` on(((`tc`.`Id_Componente` = `mc`.`Id_Componente`) and (`tc`.`tarifa_componentes_series_id` = 6)))) join `vn2008`.`Tickets` `t` on((`t`.`Id_Ticket` = `m`.`Id_Ticket`))) left join `vn2008`.`v_expeditions_shipping_chargekk` `es` on((`es`.`Id_Ticket` = `t`.`Id_Ticket`))) where ((`t`.`Fecha` >= '2015-09-01') and (`t`.`empresa_id` in (442,791,567))) group by `t`.`Id_Ticket` having ((abs(`diferencia`) > 0.01) or isnull(`diferencia`)) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_empresa`
--

/*!50001 DROP VIEW IF EXISTS `v_empresa`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_empresa` AS select `e`.`logo` AS `logo`,`e`.`id` AS `id`,`e`.`registro` AS `registro`,`e`.`gerente_id` AS `gerente_id`,`e`.`alta` AS `alta`,`t`.`Nombre` AS `Nombre`,`t`.`Apellidos` AS `Apellidos`,`p`.`Proveedor` AS `Proveedor`,`p`.`Domicilio` AS `Domicilio`,`p`.`CP` AS `CP`,`p`.`Localidad` AS `Localidad`,`p`.`NIF` AS `NIF`,`p`.`Telefono` AS `Telefono`,`p`.`Alias` AS `Alias`,`e`.`abbreviation` AS `abbreviation` from ((`empresa` `e` join `Trabajadores` `t` on((`t`.`Id_Trabajador` = `e`.`gerente_id`))) join `Proveedores` `p` on((`p`.`Id_Proveedor` = `e`.`id`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_encajado`
--

/*!50001 DROP VIEW IF EXISTS `v_encajado`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_encajado` AS select hour(`e`.`odbc_date`) AS `hora`,minute(`e`.`odbc_date`) AS `minuto`,ifnull(`c`.`Volumen`,94500) AS `cm3`,`t`.`warehouse_id` AS `warehouse_id` from ((`expeditions` `e` left join `Cubos` `c` on((`c`.`item_id` = `e`.`EsBulto`))) join `Tickets` `t` on((`t`.`Id_Ticket` = `e`.`ticket_id`))) where (`e`.`odbc_date` between curdate() and `DAYEND`(curdate())) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_encajado_ultima_hora`
--

/*!50001 DROP VIEW IF EXISTS `v_encajado_ultima_hora`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_encajado_ultima_hora` AS select sum((ifnull(`c`.`Volumen`,94500) / 1000000)) AS `m3`,`t`.`warehouse_id` AS `warehouse_id` from ((`expeditions` `e` left join `Cubos` `c` on((`c`.`item_id` = `e`.`EsBulto`))) join `Tickets` `t` on((`t`.`Id_Ticket` = `e`.`ticket_id`))) where ((`e`.`odbc_date` > (now() + interval -(1) hour)) and (`t`.`warehouse_id` in (1,44))) group by `t`.`warehouse_id` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_expeditions_shipping_charge2`
--

/*!50001 DROP VIEW IF EXISTS `v_expeditions_shipping_charge2`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_expeditions_shipping_charge2` AS select `t`.`Id_Ticket` AS `Id_Ticket`,`az`.`price` AS `shipping_charge`,`t`.`Fecha` AS `Fecha`,`t`.`warehouse_id` AS `warehouse_id` from ((((((`Tickets` `t` left join `Clientes` `cli` on((`cli`.`id_cliente` = `t`.`Id_Cliente`))) left join `expeditions` `e` on((`e`.`ticket_id` = `t`.`Id_Ticket`))) join `Consignatarios` `c` on((`c`.`id_consigna` = `t`.`Id_Consigna`))) join `Agencias` `a` on((`a`.`Id_Agencia` = `t`.`Id_Agencia`))) join `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 `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` >= '2015-01-01') and (`cli`.`real` <> 0) and (`t`.`empresa_id` in (442,567))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_expeditions_shipping_charge_by_container`
--

/*!50001 DROP VIEW IF EXISTS `v_expeditions_shipping_charge_by_container`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_expeditions_shipping_charge_by_container` AS select `t`.`Id_Ticket` AS `Id_Ticket`,`t`.`Fecha` AS `Fecha`,`az`.`Id_Article` AS `Id_Article`,`az`.`price` AS `price`,`t`.`Id_Ruta` AS `Id_Ruta` from ((((((`Tickets` `t` join `Clientes` `cli` on((`cli`.`id_cliente` = `t`.`Id_Cliente`))) left join `expeditions` `e` on((`e`.`ticket_id` = `t`.`Id_Ticket`))) join `Consignatarios` `c` on((`c`.`id_consigna` = `t`.`Id_Consigna`))) join `Agencias` `a` on((`a`.`Id_Agencia` = `t`.`Id_Agencia`))) join `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 `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` >= '2016-10-01') and (`cli`.`real` <> 0) and (`t`.`empresa_id` in (442,791,567))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_expeditions_shipping_chargekk`
--

/*!50001 DROP VIEW IF EXISTS `v_expeditions_shipping_chargekk`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_expeditions_shipping_chargekk` AS select `t`.`Id_Ticket` AS `Id_Ticket`,sum(`az`.`price`) AS `shipping_charge`,`t`.`Fecha` AS `Fecha` from ((((((`Tickets` `t` join `Clientes` `cli` on((`cli`.`id_cliente` = `t`.`Id_Cliente`))) left join `expeditions` `e` on((`e`.`ticket_id` = `t`.`Id_Ticket`))) join `Consignatarios` `c` on((`c`.`id_consigna` = `t`.`Id_Consigna`))) join `Agencias` `a` on((`a`.`Id_Agencia` = `t`.`Id_Agencia`))) join `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 `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` >= '2015-10-01') and (`cli`.`real` <> 0) and (`t`.`empresa_id` in (442,791,567))) group by `t`.`Id_Ticket` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_fallo`
--

/*!50001 DROP VIEW IF EXISTS `v_fallo`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_fallo` AS select `vncontrol`.`fallo`.`queja_id` AS `queja_id`,`vncontrol`.`fallo`.`accion_id` AS `accion_id` from `vncontrol`.`fallo` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_inter`
--

/*!50001 DROP VIEW IF EXISTS `v_inter`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_inter` AS select `vncontrol`.`inter`.`inter_id` AS `inter_id`,`vncontrol`.`inter`.`state_id` AS `state_id`,`vncontrol`.`inter`.`nota` AS `nota`,`vncontrol`.`inter`.`odbc_date` AS `odbc_date`,`vncontrol`.`inter`.`Id_Ticket` AS `Id_Ticket`,`vncontrol`.`inter`.`Id_Trabajador` AS `Id_Trabajador`,`vncontrol`.`inter`.`Id_Supervisor` AS `Id_supervisor` from `vncontrol`.`inter` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_jerarquia`
--

/*!50001 DROP VIEW IF EXISTS `v_jerarquia`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_jerarquia` AS select `jerarquia`.`worker_id` AS `Id_Trabajador`,`jerarquia`.`boss_id` AS `boss_id` from `jerarquia` union all select distinct `jerarquia`.`boss_id` AS `Id_Trabajador`,`jerarquia`.`boss_id` AS `boss_id` from `jerarquia` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_location`
--

/*!50001 DROP VIEW IF EXISTS `v_location`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_location` AS select `tl`.`longitude` AS `longitude`,`tl`.`latitude` AS `latitude`,`t`.`Id_Consigna` AS `Id_Consigna` from (`ticket_location` `tl` join `Tickets` `t` on((`t`.`Id_Ticket` = `tl`.`Id_Ticket`))) where (`t`.`Fecha` >= (curdate() + interval -(3) month)) group by `t`.`Id_Consigna` order by `t`.`Id_Ticket` desc */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_mana_spellers`
--

/*!50001 DROP VIEW IF EXISTS `v_mana_spellers`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_mana_spellers` AS select `bs`.`mana_spellers`.`Id_Trabajador` AS `Id_Trabajador`,`bs`.`mana_spellers`.`size` AS `size`,`bs`.`mana_spellers`.`used` AS `used` from `bs`.`mana_spellers` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_miriam`
--

/*!50001 DROP VIEW IF EXISTS `v_miriam`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_miriam` AS select `M`.`Id_Article` AS `Id_Article`,`M`.`Concepte` AS `Concepte`,`M`.`Cantidad` AS `Cantidad`,`M`.`Preu` AS `Preu`,`M`.`Descuento` AS `Descuento`,`T`.`Fecha` AS `Fecha`,`T`.`Id_Cliente` AS `Id_Cliente`,(((`M`.`Cantidad` * `M`.`Preu`) * (100 - `M`.`Descuento`)) / 100) AS `Importe` from (((`Tickets` `T` join `Movimientos` `M` on((`T`.`Id_Ticket` = `M`.`Id_Ticket`))) join `Articles` `A` on((`M`.`Id_Article` = `A`.`Id_Article`))) join `Tipos` `TP` on((`A`.`tipo_id` = `TP`.`tipo_id`))) where ((`T`.`Fecha` >= '2011-01-01') and (`A`.`tipo_id` = 7)) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_movimientos_mark`
--

/*!50001 DROP VIEW IF EXISTS `v_movimientos_mark`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_movimientos_mark` AS select `Movimientos_mark`.`Id_Movimiento` AS `Id_Movimiento`,max(`Movimientos_mark`.`Id_Accion`) AS `Accion` from `Movimientos_mark` group by `Movimientos_mark`.`Id_Movimiento` having ((max(`Movimientos_mark`.`Id_Accion`) = '6') or (max(`Movimientos_mark`.`Id_Accion`) = '7')) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_pedidos_auto_preparadosKk`
--

/*!50001 DROP VIEW IF EXISTS `v_pedidos_auto_preparadosKk`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_pedidos_auto_preparadosKk` AS select `t`.`CodigoTrabajador` AS `CodigoTrabajador`,`i`.`Id_Ticket` AS `Id_Ticket`,`i`.`odbc_date` AS `Momento` from ((`vn2008`.`v_jerarquia` `j` left join `vn2008`.`v_inter` `i` on((`j`.`Id_Trabajador` = `i`.`Id_Trabajador`))) join `vn2008`.`Trabajadores` `t` on((`t`.`Id_Trabajador` = `j`.`Id_Trabajador`))) where (`i`.`state_id` = 20) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_phonebook`
--

/*!50001 DROP VIEW IF EXISTS `v_phonebook`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_phonebook` AS select `Clientes`.`id_cliente` AS `Id_Cliente`,replace(`Clientes`.`telefono`,' ','') AS `Telefono` from `Clientes` where (`Clientes`.`telefono` and `Clientes`.`activo`) union select `Clientes`.`id_cliente` AS `Id_Cliente`,replace(`Clientes`.`movil`,' ','') AS `Movil` from `Clientes` where (`Clientes`.`movil` and `Clientes`.`activo`) union select `Consignatarios`.`Id_cliente` AS `Id_Cliente`,replace(`Consignatarios`.`telefono`,' ','') AS `TRIM(telefono)` from (`Consignatarios` join `Clientes` `c` on((`Consignatarios`.`Id_cliente` = `c`.`id_cliente`))) where (`Consignatarios`.`telefono` and `c`.`activo`) union select `Consignatarios`.`Id_cliente` AS `Id_Cliente`,replace(`Consignatarios`.`movil`,' ','') AS `TRIM(movil)` from (`Consignatarios` join `Clientes` `c` on((`Consignatarios`.`Id_cliente` = `c`.`id_cliente`))) where (`Consignatarios`.`movil` and `c`.`activo`) union select `r`.`Id_Cliente` AS `Id_Cliente`,replace(`c`.`Telefono`,' ','') AS `REPLACE(c.telefono,' ','')` from ((`Clientes` `cl` join `Relaciones` `r` on((`cl`.`id_cliente` = `r`.`Id_Cliente`))) join `Contactos` `c` on((`r`.`Id_Contacto` = `c`.`Id_Contacto`))) where (`cl`.`telefono` and `cl`.`activo`) union select `r`.`Id_Cliente` AS `Id_Cliente`,replace(`c`.`Movil`,' ','') AS `REPLACE(c.Movil,' ','')` from ((`Clientes` `cl` join `Relaciones` `r` on((`cl`.`id_cliente` = `r`.`Id_Cliente`))) join `Contactos` `c` on((`r`.`Id_Contacto` = `c`.`Id_Contacto`))) where (`cl`.`movil` and `cl`.`activo`) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_price_fixed`
--

/*!50001 DROP VIEW IF EXISTS `v_price_fixed`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_price_fixed` AS select `pf`.`warehouse_id` AS `warehouse_id`,`pf`.`item_id` AS `item_id`,`pf`.`rate_0` AS `rate_0`,`pf`.`rate_1` AS `rate_1`,`pf`.`rate_2` AS `rate_2`,`pf`.`rate_3` AS `rate_3`,`pf`.`date_start` AS `date_start`,`pf`.`date_end` AS `date_end`,`pf`.`bonus` AS `bonus`,`pf`.`grouping` AS `grouping`,`pf`.`Packing` AS `Packing`,`pf`.`caja` AS `caja` from `price_fixed` `pf` where (`pf`.`warehouse_id` < 1000) union all select `wg`.`warehouse_id` AS `warehouse_id`,`pf`.`item_id` AS `item_id`,`pf`.`rate_0` AS `rate_0`,`pf`.`rate_1` AS `rate_1`,`pf`.`rate_2` AS `rate_2`,`pf`.`rate_3` AS `rate_3`,`pf`.`date_start` AS `date_start`,`pf`.`date_end` AS `date_end`,`pf`.`bonus` AS `bonus`,`pf`.`grouping` AS `grouping`,`pf`.`Packing` AS `Packing`,`pf`.`caja` AS `caja` from (`price_fixed` `pf` join `warehouse_group` `wg`) where ((`wg`.`warehouse_alias_id` + 1000) = `pf`.`warehouse_id`) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_price_fixed_group`
--

/*!50001 DROP VIEW IF EXISTS `v_price_fixed_group`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_price_fixed_group` AS select `pf`.`warehouse_id` AS `warehouse_id`,`pf`.`item_id` AS `item_id`,`pf`.`rate_0` AS `rate_0`,`pf`.`rate_1` AS `rate_1`,`pf`.`rate_2` AS `rate_2`,`pf`.`rate_3` AS `rate_3`,`pf`.`date_start` AS `date_start`,`pf`.`date_end` AS `date_end`,`pf`.`bonus` AS `bonus`,`pf`.`grouping` AS `grouping`,`pf`.`Packing` AS `Packing`,`pf`.`caja` AS `caja` from `v_price_fixed` `pf` group by `pf`.`warehouse_id`,`pf`.`item_id`,`pf`.`date_start`,`pf`.`date_end` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_session`
--

/*!50001 DROP VIEW IF EXISTS `v_session`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_session` AS select 1 AS `id`,`t`.`CodigoTrabajador` AS `CodigoTrabajador`,if(isnull(`sc`.`Id_Suplente`),`c`.`Id_Trabajador`,`sc`.`Id_Suplente`) AS `Id_Trabajador`,`c`.`id_cliente` AS `Id_Cliente`,`c`.`cliente` AS `Cliente`,`s`.`lastUpdate` AS `Fecha` from ((((`hedera`.`userSession` `s` join `hedera`.`visitUser` `v` on((`v`.`id` = `s`.`userVisit`))) join `vn2008`.`Clientes` `c` on((`c`.`id_cliente` = `v`.`user`))) left join `vn2008`.`Trabajadores` `t` on((`c`.`Id_Trabajador` = `t`.`Id_Trabajador`))) left join `vn2008`.`sharingcart` `sc` on(((`sc`.`Id_Trabajador` = `c`.`Id_Trabajador`) and (curdate() between `sc`.`datSTART` and `sc`.`datEND`)))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_ticket_amount`
--

/*!50001 DROP VIEW IF EXISTS `v_ticket_amount`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_ticket_amount` AS select `Movimientos`.`Id_Ticket` AS `Id_Ticket`,sum((((`Movimientos`.`Cantidad` * `Movimientos`.`Preu`) * (100 - `Movimientos`.`Descuento`)) / 100)) AS `amount` from (`Movimientos` join `Tickets` on((`Movimientos`.`Id_Ticket` = `Tickets`.`Id_Ticket`))) where (`Tickets`.`Fecha` >= (curdate() + interval -(6) month)) group by `Movimientos`.`Id_Ticket` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_trabajadores`
--

/*!50001 DROP VIEW IF EXISTS `v_trabajadores`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_trabajadores` AS select `t`.`CodigoTrabajador` AS `CodigoTrabajador`,`t`.`Nombre` AS `Nombre`,`t`.`Fecha_Inicio` AS `Fecha_Inicio`,`t`.`Password` AS `Password`,`t`.`user` AS `user`,`t`.`Apellidos` AS `Apellidos`,`t`.`Id_Trabajador` AS `Id_Trabajador`,`t`.`Foto` AS `Foto` from `vn2008`.`Trabajadores` `t` where (`t`.`Id_Cliente_Interno` = `account`.`userGetId`()) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_user`
--

/*!50001 DROP VIEW IF EXISTS `v_user`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_user` AS select `u`.`id` AS `id`,`u`.`role` AS `mysql_user_id`,`u`.`name` AS `name`,`u`.`password` AS `password`,`u`.`active` AS `active` from `account`.`user` `u` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_ventes`
--

/*!50001 DROP VIEW IF EXISTS `v_ventes`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_ventes` AS select `Agencias`.`Agencia` AS `Agencia`,`A`.`Categoria` AS `Categoria`,`A`.`tipo_id` AS `tipo_id`,`A`.`Medida` AS `Medida`,`A`.`Article` AS `Article`,`A`.`Color` AS `Color`,`CS`.`Id_cliente` AS `Id_Cliente`,`TP`.`Id_Tipo` AS `Tipo`,`T`.`Factura` AS `Factura`,`T`.`warehouse_id` AS `warehouse_id`,`M`.`Id_Movimiento` AS `Id_Movimiento`,`M`.`Id_Article` AS `Id_Article`,`TP`.`Id_Tipo` AS `Familia`,`M`.`Id_Ticket` AS `Id_Ticket`,`M`.`Concepte` AS `Concepte`,`M`.`Cantidad` AS `Cantidad`,`M`.`quantity` AS `quantity`,`M`.`Preu` AS `Preu`,`M`.`Descuento` AS `Descuento`,if((`T`.`Fecha` >= '2015-10-01'),`M`.`CostFixat`,((`M`.`Preu` * (100 - `M`.`Descuento`)) / 100)) AS `CostFixat`,`M`.`Reservado` AS `Reservado`,`M`.`OK` AS `OK`,`M`.`PrecioFijado` AS `PrecioFijado`,`M`.`odbc_date` AS `odbc_date`,cast(`T`.`Fecha` as date) AS `Fecha`,`T`.`Fecha` AS `FechaCompleta`,`CS`.`consignatario` AS `Alias`,`T`.`Id_Consigna` AS `Id_Consigna`,(((`M`.`Cantidad` * `M`.`Preu`) * (100 - `M`.`Descuento`)) / 100) AS `Importe`,`O`.`Origen` AS `Origen`,`TP`.`reino_id` AS `reino_id`,`C`.`invoice` AS `invoice`,`A`.`producer_id` AS `producer_id` from ((((((((`Movimientos` `M` join `Tickets` `T` on((`M`.`Id_Ticket` = `T`.`Id_Ticket`))) join `Consignatarios` `CS` on((`CS`.`id_consigna` = `T`.`Id_Consigna`))) join `Clientes` `C` on((`CS`.`Id_cliente` = `C`.`id_cliente`))) join `Articles` `A` on((`M`.`Id_Article` = `A`.`Id_Article`))) join `Origen` `O` on((`O`.`id` = `A`.`id_origen`))) join `Tipos` `TP` on((`A`.`tipo_id` = `TP`.`tipo_id`))) join `reinos` `r` on((`TP`.`reino_id` = `r`.`id`))) join `Agencias` on((`Agencias`.`Id_Agencia` = `T`.`Id_Agencia`))) where ((`T`.`Fecha` >= '2013-01-01') and (`C`.`real` > 0) and (`r`.`id` <> 6)) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_warehouse`
--

/*!50001 DROP VIEW IF EXISTS `v_warehouse`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_warehouse` AS select `warehouse`.`id` AS `id`,`warehouse`.`name` AS `almacen` from `warehouse` union all select (1000 + `warehouse_alias`.`warehouse_alias_id`) AS `warehouse_alias_id`,concat(`warehouse_alias`.`alias`,'(G)') AS `concat(alias, '(G)')` from `warehouse_alias` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_xsubclien`
--

/*!50001 DROP VIEW IF EXISTS `v_xsubclien`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_xsubclien` AS select distinct `Facturas`.`Id_Cliente` AS `Id_Cliente`,`Facturas`.`empresa_id` AS `empresa_id` from `Facturas` where (`Facturas`.`Fecha` > (curdate() + interval -(2) month)) union select `Recibos`.`Id_Cliente` AS `Id_Cliente`,`Recibos`.`empresa_id` AS `empresa_id` from `Recibos` where (`Recibos`.`Fechacobro` > (curdate() + interval -(2) month)) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_xsubcuentas`
--

/*!50001 DROP VIEW IF EXISTS `v_xsubcuentas`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_xsubcuentas` AS select `Clientes`.`Cuenta` AS `COD`,`Clientes`.`razonSocial` AS `TITULO`,concat(if(((`p`.`CEE` = 1) and (ascii(left(`Clientes`.`if`,1)) < 58)),`p`.`Codigo`,''),`Clientes`.`if`) AS `NIF`,`Clientes`.`domicilio` AS `DOMICILIO`,`Clientes`.`poblacion` AS `POBLACION`,`province`.`name` AS `PROVINCIA`,`Clientes`.`codPostal` AS `CODPOSTAL`,`p`.`Codigo` AS `country_code`,`v_xsubclien`.`empresa_id` AS `empresa_id`,substr(`Clientes`.`e-mail`,1,(coalesce(nullif(locate(',',`Clientes`.`e-mail`),0),99) - 1)) AS `EMAIL`,if((`p`.`CEE` = 0),1,if((`p`.`CEE` = 1),2,4)) AS `IDNIF` from (((`Clientes` join `v_xsubclien` on((`Clientes`.`id_cliente` = `v_xsubclien`.`Id_Cliente`))) left join `Paises` `p` on((`p`.`Id` = `Clientes`.`Id_Pais`))) join `province` on((`Clientes`.`province_id` = `province`.`province_id`))) where (`Clientes`.`oficial` <> 0) group by `Clientes`.`id_cliente`,`v_xsubclien`.`empresa_id` union all select `Proveedores`.`cuenta` AS `Cuenta`,`Proveedores`.`Proveedor` AS `Proveedor`,concat(if(((`p`.`CEE` = 1) and (ascii(left(`Proveedores`.`NIF`,1)) < 58)),`p`.`Codigo`,''),`Proveedores`.`NIF`) AS `NIF`,`Proveedores`.`Domicilio` AS `Domicilio`,`Proveedores`.`Localidad` AS `Localidad`,`prov`.`name` AS `Provincia`,`Proveedores`.`CP` AS `CP`,`p`.`Codigo` AS `country_code`,`v_xsubprov`.`empresa_id` AS `empresa_id`,substr(`c`.`email`,1,(coalesce(nullif(locate(',',`c`.`email`),0),99) - 1)) AS `EMAIL`,if((`p`.`CEE` = 0),1,if((`p`.`CEE` = 1),2,4)) AS `IDNIF` from (((((`Proveedores` join `v_xsubprov` on((`Proveedores`.`Id_Proveedor` = `v_xsubprov`.`proveedor_id`))) left join `Paises` `p` on((`p`.`Id` = `Proveedores`.`pais_id`))) left join `province` `prov` on((`prov`.`province_id` = `Proveedores`.`province_id`))) left join `Relaciones` `r` on((`r`.`Id_Proveedor` = `Proveedores`.`Id_Proveedor`))) left join `Contactos` `c` on((`c`.`Id_Contacto` = `r`.`Id_Contacto`))) where (`Proveedores`.`oficial` <> 0) group by `v_xsubprov`.`proveedor_id`,`v_xsubprov`.`empresa_id` union all select `Gastos`.`Id_Gasto` AS `Id_Gasto`,`Gastos`.`Gasto` AS `Gasto`,NULL AS `NULL`,NULL AS `My_exp_NULL`,NULL AS `My_exp_1_NULL`,NULL AS `My_exp_2_NULL`,NULL AS `My_exp_3_NULL`,NULL AS `country_code`,`e`.`id` AS `id`,NULL AS `EMAIL`,1 AS `IDNIF` from (`Gastos` join `empresa` `e` on((`e`.`id` = 442))) union all select `Bancos`.`Cuenta` AS `Cuenta`,`Bancos`.`Banco` AS `Banco`,NULL AS `NULL`,NULL AS `My_exp_NULL`,NULL AS `My_exp_1_NULL`,NULL AS `My_exp_2_NULL`,NULL AS `My_exp_3_NULL`,NULL AS `country_code`,`e`.`id` AS `id`,NULL AS `EMAIL`,1 AS `IDNIF` from (`Bancos` join `empresa` `e` on((`e`.`id` = 442))) union all select lpad(right(`Proveedores`.`cuenta`,5),10,'47510000') AS `Cuenta`,`Proveedores`.`Proveedor` AS `Proveedor`,`Proveedores`.`NIF` AS `NIF`,`Proveedores`.`Domicilio` AS `Domicilio`,`Proveedores`.`Localidad` AS `Localidad`,`prov`.`name` AS `Provincia`,`Proveedores`.`CP` AS `CP`,`p`.`Codigo` AS `country_code`,`v_xsubprov`.`empresa_id` AS `empresa_id`,substr(`c`.`email`,1,(coalesce(nullif(locate(',',`c`.`email`),0),99) - 1)) AS `EMAIL`,if((`p`.`CEE` = 0),1,if((`p`.`CEE` = 1),2,4)) AS `IDNIF` from (((((`Proveedores` join `v_xsubprov` on((`Proveedores`.`Id_Proveedor` = `v_xsubprov`.`proveedor_id`))) left join `Paises` `p` on((`p`.`Id` = `Proveedores`.`pais_id`))) left join `province` `prov` on((`prov`.`province_id` = `Proveedores`.`province_id`))) left join `Relaciones` `r` on((`r`.`Id_Proveedor` = `Proveedores`.`Id_Proveedor`))) left join `Contactos` `c` on((`c`.`Id_Contacto` = `r`.`Id_Contacto`))) where (((`Proveedores`.`cuenta` like '_____3____') or (`Proveedores`.`cuenta` like '_____2____')) and (`Proveedores`.`oficial` = 1)) group by `v_xsubprov`.`proveedor_id`,`v_xsubprov`.`empresa_id` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `v_xsubprov`
--

/*!50001 DROP VIEW IF EXISTS `v_xsubprov`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `v_xsubprov` AS select `recibida`.`proveedor_id` AS `proveedor_id`,`recibida`.`empresa_id` AS `empresa_id` from `recibida` where (`recibida`.`fecha` > (curdate() + interval -(3) month)) group by `recibida`.`proveedor_id`,`recibida`.`empresa_id` union all select `pago`.`id_proveedor` AS `id_proveedor`,`pago`.`empresa_id` AS `empresa_id` from `pago` where (`pago`.`fecha` > (curdate() + interval -(3) month)) group by `pago`.`id_proveedor`,`pago`.`empresa_id` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `vnCreditClassification`
--

/*!50001 DROP VIEW IF EXISTS `vnCreditClassification`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `vnCreditClassification` AS select `vn`.`creditClassification`.`id` AS `id`,`vn`.`creditClassification`.`client` AS `client`,`vn`.`creditClassification`.`dateStart` AS `dateStart`,`vn`.`creditClassification`.`dateEnd` AS `dateEnd` from `vn`.`creditClassification` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `vnCreditInsurance`
--

/*!50001 DROP VIEW IF EXISTS `vnCreditInsurance`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `vnCreditInsurance` AS select `vn`.`creditInsurance`.`id` AS `id`,`vn`.`creditInsurance`.`creditClassification` AS `creditClassification`,`vn`.`creditInsurance`.`credit` AS `credit`,`vn`.`creditInsurance`.`creationDate` AS `creationDate`,`vn`.`creditInsurance`.`grade` AS `grade` from `vn`.`creditInsurance` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `vnSolunionCAP`
--

/*!50001 DROP VIEW IF EXISTS `vnSolunionCAP`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `vnSolunionCAP` AS select `vn`.`solunionCAP`.`creditInsurance` AS `creditInsurance`,`vn`.`solunionCAP`.`dateStart` AS `dateStart`,`vn`.`solunionCAP`.`dateEnd` AS `dateEnd`,`vn`.`solunionCAP`.`dateLeaving` AS `dateLeaving` from `vn`.`solunionCAP` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `workerDocument`
--

/*!50001 DROP VIEW IF EXISTS `workerDocument`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `workerDocument` AS select `vn`.`workerDocument`.`id` AS `id`,`vn`.`workerDocument`.`worker` AS `worker`,`vn`.`workerDocument`.`document` AS `document` from `vn`.`workerDocument` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `workerTeamCollegues`
--

/*!50001 DROP VIEW IF EXISTS `workerTeamCollegues`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `workerTeamCollegues` AS select distinct `w`.`Id_Trabajador` AS `workerId`,`t`.`Id_Trabajador` AS `collegueId` from (`vn`.`workerTeam` `w` join `vn`.`workerTeam` `t` on((`w`.`team` = `t`.`team`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `zoneNickname`
--

/*!50001 DROP VIEW IF EXISTS `zoneNickname`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `zoneNickname` AS select `ap`.`warehouse_id` AS `warehouse_id`,`ap`.`agency_id` AS `agency_id`,`ap`.`zona` AS `zona`,concat('ZONA ',`ap`.`zona`,' ',if((`ap`.`zona` = 20),'Madrid',`p`.`name`)) AS `alias` from (`Agencias_province` `ap` join `province` `p` on((`p`.`province_id` = `ap`.`province_id`))) group by `ap`.`zona`,`ap`.`warehouse_id`,`ap`.`agency_id` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

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

USE `vncontrol`;
/*!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 2019-05-23  8:39:14
