-- MySQL dump 10.13  Distrib 5.7.28, for osx10.15 (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  = 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 `account`.`account_afterInsert`
	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  = 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 `account`.`account_afterDelete`
	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',
  `idBase` int(11) NOT NULL,
  `min` smallint(6) NOT NULL,
  `max` smallint(6) NOT NULL,
  `warn` smallint(6) NOT NULL,
  `inact` smallint(6) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT 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 `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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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,
  `bcryptPassword` varchar(255) COLLATE utf8_unicode_ci DEFAULT 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,
  `password` char(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Deprecated',
  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=InnoDBDEFAULT 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  = 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 `user_beforeInsert`
	BEFORE INSERT ON `user`
	FOR EACH ROW
BEGIN
	CALL user_checkName(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_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `user_beforeUpdate`
	BEFORE UPDATE ON `user`
    FOR EACH ROW
BEGIN
	IF !(NEW.`name` <=> OLD.`name`) THEN
		CALL user_checkName (NEW.`name`);
	END IF;

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

	IF !(NEW.`password` <=> OLD.`password`) THEN
		SET NEW.bcryptPassword = NULL;
		SET NEW.lastPassChange = NOW();
	END IF;
    
    /*borrar el lunes*/
    IF (NEW.`id` = 14255) THEN
		SET NEW.role = 9;
    END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `user_afterUpdate`
	AFTER UPDATE ON `user`
	FOR EACH ROW
BEGIN
	IF !(NEW.`role` <=> OLD.`role`)
    THEN
		INSERT INTO vn.mail SET
			`sender` = 'jgallego@verdnatura.es',
            `replyTo` = 'jgallego@verdnatura.es',
            `subject` = 'Rol modificado',
            `body` = CONCAT(myUserGetName(), ' ha modificado el rol del usuario ',
				NEW.`name`, ' de ', OLD.role, ' a ', NEW.role);
	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=InnoDBDEFAULT 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=InnoDBDEFAULT 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 `role_getDescendents` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `role_getDescendents`(vSelf INT)
BEGIN
/**
 * Obtiene los identificadores de todos los subroles
 * implementados por un rol (Incluido el mismo).
 *
 * @param vSelf 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 vSelf AS id;

	CREATE TEMPORARY TABLE parents
		ENGINE = MEMORY
		SELECT vSelf 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 `role_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 `role_sync`()
BEGIN
/**
 * Sincroniza la tabla @roleRole con la jerarquía de roles
 * actual. Este procedimiento debe ser llamado cada vez que
 * se modifique la tabla @roleInherit para que los cambios
 * realizados sobre esta sean efectivos.
 */
	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 role_getDescendents(vRoleId);

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

	CLOSE cur;
    
    CALL role_syncPrivileges;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `role_syncPrivileges` */;
/*!50003 SET @saved_cs_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 `role_syncPrivileges`()
BEGIN
/**
 * Sincroniza los permisos de los usuarios 'rol' de MySQL
 * en base a la jerarquía de roles. Los usuarios rol resultantes
 * de la mezcla de permisos serán nombrados singuiendo el patrón
 * z-[nombre_rol].
 *
 * Si existe el usuario any@localhost que se tomará como plantilla
 * para los atributos básicos.
 *
 * ¡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 vTplHost VARCHAR(255) DEFAULT '%';
	DECLARE vRoleHost VARCHAR(255) DEFAULT 'localhost';
	DECLARE vAllHost VARCHAR(255) DEFAULT '%';
	DECLARE vPrefix VARCHAR(2) DEFAULT 'z-';
	DECLARE vPrefixedLike VARCHAR(255);
			
	-- Borra todos los privilegios calculados

	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
		(INDEX (id))
		ENGINE = MEMORY
		SELECT
			id,
			`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
			r.prefixedRole,
			ri.`name` inheritsFrom
			FROM tRole 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,
			IFNULL(t.`Password`, ''),
			IFNULL(IF('' != u.`ssl_type`,
				u.`ssl_type`, t.`ssl_type`),
                ''),
			IFNULL(IF('' != u.`ssl_cipher`,
				u.`ssl_cipher`, t.`ssl_cipher`),
                ''),
			IFNULL(IF('' != u.`x509_issuer`,
				u.`x509_issuer`, t.`x509_issuer`),
                ''),
			IFNULL(IF('' != u.`x509_subject`,
				u.`x509_subject`, t.`x509_subject`),
                ''),
			IFNULL(IF(0 != u.`max_questions`,
				u.`max_questions`, t.`max_questions`),
                0),
			IFNULL(IF(0 != u.`max_updates`,
				u.`max_updates`, t.`max_updates`),
                0),
			IFNULL(IF(0 != u.`max_connections`,
				u.`max_connections`, t.`max_connections`),
                0),
			IFNULL(IF(0 != u.`max_user_connections`,
				u.`max_user_connections`, t.`max_user_connections`),
                0)
			FROM tRole r
				LEFT JOIN mysql.user t
					ON t.`User` = vTplUser
						AND t.`Host` = vRoleHost
				LEFT JOIN mysql.user u
					ON u.`User` = r.role
						AND u.`Host` = vRoleHost;

	INSERT INTO mysql.proxies_priv (
		`User`,
		`Host`,
		`Proxied_user`,
		`Proxied_host`,
		`Grantor`
	)
	SELECT
		'',
		vAllHost,
		prefixedRole,
		vTplHost,
		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`= vRoleHost
			GROUP BY r.prefixedRole;

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

	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`= vRoleHost
			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`),
			IFNULL(GROUP_CONCAT(NULLIF(t.`Table_priv`, '')), ''),
			IFNULL(GROUP_CONCAT(NULLIF(t.`Column_priv`, '')), '')
			FROM tRoleInherit r
				JOIN mysql.tables_priv t
					ON t.`User` = r.inheritsFrom
						AND t.`Host`= vRoleHost
			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`),
			IFNULL(GROUP_CONCAT(NULLIF(t.`Column_priv`, '')), '')
			FROM tRoleInherit r
				JOIN mysql.columns_priv t
					ON t.`User` = r.inheritsFrom
						AND t.`Host`= vRoleHost
			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`= vRoleHost;
						
	-- 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 `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  = 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 `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
 */
	DECLARE vSelf INT;

	CALL user_checkPassword(vPassword);

	SELECT id INTO vSelf
		FROM user WHERE `name` = vUserName;

	UPDATE user SET
		`password` = MD5(vPassword),
		`recoverPass` = FALSE
		WHERE id = vSelf;
        
	CALL user_syncPassword(vSelf, vPassword);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `user_checkName` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = 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 `user_checkName`(vUserName VARCHAR(255))
BEGIN
/**
 * Comprueba que el nombre de usuario reune los requisitos
 * de sintaxis necesarios, en caso contrario lanza una
 * excepción.
 * El nombre de usuario solo debe contener letras minúsculas
 * o, a partir del segundo carácter, números o subguiones.
 */
	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 `user_checkPassword` */;
/*!50003 SET @saved_cs_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 `user_checkPassword`(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 `user_syncPassword` */;
/*!50003 SET @saved_cs_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 `user_syncPassword`(
	vSelf VARCHAR(255),
    vPassword VARCHAR(255)
)
BEGIN
/**
 * Synchronizes the user password in other schemes.
 *
 * @param vSelf The user id
 * @param vPassword The user password
 */
	CALL pbx.sip_setPassword(vSelf, vPassword);

	DELETE FROM salix.user 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 */ ;

--
-- 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=InnoDBDEFAULT 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 `vn`.`buy` (`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 `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=InnoDBDEFAULT 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=InnoDBDEFAULT 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 `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- 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 `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `customer_risk_ibfk_2` FOREIGN KEY (`company_id`) REFERENCES `vn`.`company` (`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,
  `frozened` date 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 `vn`.`ticket` (`id`) 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 `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- 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 `warehouse_id_rotacion_idx` (`warehouse_id`),
  CONSTRAINT `id_article_rotaci` FOREIGN KEY (`Id_Article`) REFERENCES `vn`.`item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `warehouse_id_rotaci` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`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  = 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 `bi`.`rotacion_beforeInsert`
	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  = 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 `bi`.`rotacion_beforeUpdate`
	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 */ ;

--
-- 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`),
  UNIQUE KEY `rutasBoard_Ruta` (`Id_Ruta`),
  KEY `rutasBoard_ix1` (`year`),
  KEY `rutasBoard_ix2` (`month`),
  KEY `rutasBoard_ix3` (`warehouse_id`)
) ENGINE=InnoDBDEFAULT 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',
  `code` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los valores de gasto por almacen';
/*!40101 SET character_set_client = @saved_cs_client */;

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

--
-- Dumping routines for database 'bi'
--
/*!50003 DROP FUNCTION IF EXISTS `nz` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `nz`(dblCANTIDAD DOUBLE) RETURNS double
BEGIN

DECLARE dblRESULT  DOUBLE;

SET dblRESULT = IFNULL(dblCANTIDAD,0);

RETURN dblRESULT;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `analisis_ventas_evolution_add` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `analisis_ventas_evolution_add`()
BEGIN
	DECLARE vPreviousPeriod INT;
	DECLARE vCurrentPeriod INT;
    DECLARE vLastPeriod INT;
    DECLARE vMinPeriod INT DEFAULT 201400;
    DECLARE vMaxPeriod INT DEFAULT vn2008.vnperiod(CURDATE());

	DECLARE vYear INT;
	DECLARE vWeek INT;

	-- Almacen

	SET vCurrentPeriod = IFNULL(vLastPeriod, vMinPeriod);

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

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

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

		DELETE FROM bi.analisis_ventas_almacen_evolution
			WHERE Periodo = vCurrentPeriod;

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

	-- Reino

	SET vCurrentPeriod = vMinPeriod;

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

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

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

		DELETE FROM bi.analisis_ventas_reino_evolution
			WHERE Periodo = vCurrentPeriod;

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

	-- Familia

	SET vCurrentPeriod = vMinPeriod;

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

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

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

		DELETE FROM bi.analisis_ventas_familia_evolution
			WHERE Periodo = vCurrentPeriod;

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

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

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

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

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

		DELETE FROM bi.analisis_ventas_comprador_evolution
			WHERE Periodo = vCurrentPeriod;

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

	SET vCurrentPeriod = vMinPeriod;

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

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

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

		DELETE FROM bi.analisis_ventas_provincia_evolution
			WHERE Periodo = vCurrentPeriod;

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

	-- Vista

	SET vCurrentPeriod = vMinPeriod;

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

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

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

		DELETE FROM bi.analisis_ventas_vista_evolution
			WHERE Periodo = vCurrentPeriod;

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

	-- Vendedor

	SET vCurrentPeriod = vMinPeriod;

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

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

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

		REPLACE bi.analisis_ventas_vendedor_evolution(vendedor, ventas, semana,año, periodo)
			SELECT  Comercial AS vendedor, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod
				FROM (
					SELECT Comercial, sum(Importe) AS ventas
						from bi.analisis_ventas
						WHERE  vYear = Año 
						AND vWeek = Semana
						GROUP BY Comercial
					UNION ALL
					SELECT Comercial, - sum(Importe) AS ventas
						from bi.analisis_ventas
						WHERE  vYear - 1 = Año 
						AND vWeek = Semana
						GROUP BY Comercial
					UNION ALL
					SELECT vendedor, ventas
						FROM bi.analisis_ventas_vendedor_evolution
						WHERE Periodo = vPreviousPeriod
				) sub
				GROUP BY vendedor;
	END WHILE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `analisis_ventas_simple` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `analisis_ventas_simple`()
BEGIN

TRUNCATE bi.analisis_grafico_simple;

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

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `analisis_ventas_update` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = 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 4358
	UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 4358; 

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

	-- 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.Tipos tp ON tp.tipo_id = v.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 m.Id_Article, Periodo, t.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
				WHERE v.fecha BETWEEN datINI and datFIN
					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 `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 `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 `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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `defaulting`(IN `vDate` DATE)
BEGIN
/*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
		LEFT JOIN (
			SELECT * FROM(
				SELECT client, amount , defaulterSince, frozened 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 <> IFNULL(yesterday.amount,0), 1, 0),
		d.defaulterSince = yesterday.defaulterSince,
        d.frozened = yesterday.frozened
	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;
	
    UPDATE defaulters d
			JOIN vn.config ON TRUE
		SET d.frozened = NULL
		WHERE d.`date` = vDate 
			AND d.amount <= config.defaultersMaxAmount;
		    
    CALL vn.clientFreeze();
    
    -- actualizamos defaulting
	DELETE FROM bi.defaulting WHERE date = vDate;

	INSERT INTO bi.defaulting(date, amount)
		SELECT vDate, SUM(amount)
			FROM bi.defaulters
			WHERE date = vDate and amount > 0;

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

	CALL bi.defaulting(curdate());

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

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

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


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

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

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

END IF;
*/
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `facturacion_media_anual_update` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = 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 TIMESTAMPADD(DAY,-10,CURDATE()); -- '2019-07-01'
	DECLARE datEND DATETIME DEFAULT TIMESTAMPADD(DAY,-1,CURDATE());

	DROP TEMPORARY TABLE IF EXISTS tmp.dp;

	-- Agencias que no cobran por volumen
	CREATE TEMPORARY TABLE tmp.dp
		(PRIMARY KEY (Id_Ticket))
		ENGINE = MEMORY
		 SELECT t.Id_Ticket,
			SUM(z.price * ebv.ratio) 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 vn.expeditionBoxVol ebv ON ebv.boxFk = e.EsBulto
			JOIN vn.zone z ON t.zoneFk = z.id
		WHERE
			t.Fecha between datSTART AND datEND
				AND cli.`real`
				AND t.empresa_id IN (442 , 567)
				AND z.isVolumetric = FALSE
		GROUP BY t.Id_Ticket;
    
	-- Agencias que cobran por volumen
	INSERT INTO tmp.dp
		SELECT sf.ticketFk,
			SUM(freight) AS teorico,
			00000.00 as practico,
			00000.00 as greuge
		FROM vn.saleFreight sf
			JOIN vn.`client` c ON c.id = sf.clientFk
		    JOIN vn.zone z ON z.id = sf.zoneFk
		WHERE c.isRelevant
			AND sf.companyFk IN (442 , 567)
			AND sf.shipped BETWEEN datSTART AND datEND
			AND z.isVolumetric != FALSE
		GROUP BY sf.ticketFk;

	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_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `Greuge_Evolution_Add`()
BEGIN
/*
	Inserta en la tabla Greuge_Evolution el saldo acumulado de cada cliente,
	así como las ventas acumuladas en los ultimos 365 dias, para poder controlar
	su evolucion.
*/
	DECLARE datFEC DATE;
	DECLARE datFEC_TOMORROW DATE;
	DECLARE datFEC_LASTYEAR DATE;
   
    DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN 
  	
		GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT;
		SELECT CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'));
		INSERT INTO vn2008.mail (`to`,`subject`,`text`)  VALUES ('jgallego@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')));
		INSERT INTO vn2008.mail (`to`,`subject`,`text`)  VALUES ('pako@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')));
		
	END;
  
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

	DELETE FROM bi.Greuge_Evolution WHERE Fecha >= TIMESTAMPADD(MONTH,-1,CURDATE());

	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_general_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`(
	vItemFrom INT,
    vItemTo INT,
    vStartDate DATE,
    vEndDate DATE
)
BEGIN

	DECLARE vDays INT DEFAULT DATEDIFF(vEndDate, vStartDate);
    DECLARE vLastEventFinished DATETIME;

	DROP TEMPORARY TABLE IF EXISTS timing;
    CREATE TEMPORARY TABLE timing
		SELECT 'Starting Procedure' AS evento, now() as finished, 0 as seconds;
        
	SELECT now() INTO vLastEventFinished;

	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 / vDays),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:= vStartDate, @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 vStartDate AND vEndDate
										AND r.mercancia = TRUE
										AND Id_Article BETWEEN vItemFrom AND vItemTo
										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 vStartDate AND vEndDate
										AND r.mercancia = TRUE
										AND Id_Article BETWEEN vItemFrom AND vItemTo
										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 vStartDate AND vEndDate
										AND r.mercancia = TRUE
										AND r.display <> 0 
										AND NOT fuente
										AND Id_Article BETWEEN vItemFrom AND vItemTo
										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 vStartDate AND vEndDate
						AND r.mercancia = TRUE
						AND Id_Article BETWEEN vItemFrom AND vItemTo
						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;

	INSERT INTO timing
		SELECT 'Replace' AS evento, now() as finished, TIMEDIFF(now(),vLastEventFinished) as seconds;
        
	SELECT MAX(finished) FROM timing INTO vLastEventFinished;
    
	-- Añadimos el volumen por unidad de venta
    -- FIXME: Optimizar la consulta de actualización

	-- CALL vn2008.item_last_buy_(NULL, vStartDate);
	CALL cache.last_buy_refresh(FALSE);

	INSERT INTO timing
		SELECT 'last_buy_refresh' AS evento, now() as finished, TIMEDIFF(now(),vLastEventFinished) as seconds;
        
	SELECT MAX(finished) FROM timing INTO vLastEventFinished;
    
	UPDATE bi.rotacion r
			JOIN cache.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.packaging p ON p.id = c.Id_Cubo
			JOIN vn2008.Articles a ON a.Id_Article = c.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 * IF(p.volume > 0, p.volume, p.width * p.depth * IF(p.height, p.height, a.medida + 10))  / c.packing
		WHERE re.mercancia = TRUE
			AND r.Id_Article BETWEEN vItemFrom AND vItemTo;
	
    INSERT INTO timing
		SELECT 'update volume' AS evento, now() as finished, TIMEDIFF(now(),vLastEventFinished) as seconds;
        
	SELECT MAX(finished) FROM timing INTO vLastEventFinished;
    
    -- DROP TEMPORARY TABLE vn2008.t_item_last_buy;

	-- 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 vItemFrom AND vItemTo
				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 vItemFrom AND vItemTo;	
        
	 INSERT INTO timing
		SELECT 'update almacenamiento' AS evento, now() as finished, TIMEDIFF(now(),vLastEventFinished) as seconds;
        
	SELECT MAX(finished) FROM timing INTO vLastEventFinished;
    
	-- 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, cm3)
		SELECT a.Id_Article, warehouse_id,cm3_m
			FROM vn2008.Articles a
			JOIN (
				SELECT tp.tipo_id, warehouse_id,AVG(cm3) cm3_m
					FROM bi.rotacion rt
						JOIN vn2008.Articles a ON a.Id_Article = rt.Id_Article
						JOIN vn2008.Tipos tp ON tp.tipo_id = a.tipo_id
						JOIN vn2008.reinos r ON r.id = tp.reino_id
					WHERE r.mercancia = TRUE
						GROUP BY tipo_id, warehouse_id
			) sub ON sub.tipo_id = a.tipo_id
			WHERE a.Id_Article BETWEEN vItemFrom AND vItemTo
		ON DUPLICATE KEY UPDATE rotacion = rotacion;
        
	 INSERT INTO timing
		SELECT 'historico' AS evento, now() as finished, TIMEDIFF(now(),vLastEventFinished) as seconds;
        
	SELECT MAX(finished) FROM timing INTO vLastEventFinished;
    
    SELECT * FROM timing;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = 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 `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 = vn.item_getVolume(r.Id_Article, Id_Cubo) / 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 `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: `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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=MEMORYDEFAULT 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 `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- 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=InnoDBDEFAULT 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 `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` (`item_id`) USING BTREE
) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping events for database 'cache'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `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=`root`@`%`*/ /*!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 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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `available_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 vn.itemStock (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 inventoried INTO vInventoryDate FROM vn.config;

	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(it.life IS NULL, NULL,
		TIMESTAMP(TIMESTAMPADD(DAY, it.life, c.landing), '23:59:59')) AS date_end
		FROM (
			SELECT b.itemFk item_id, MAX(t.landed) landing
				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 w ON w.id = t.warehouseInFk
				WHERE t.landed BETWEEN vInventoryDate AND vStartDate
					AND t.warehouseInFk = vWarehouse
					AND NOT e.isInventory
					/*AND NOT e.isRaid*/ -- JGF cau-13144	2019-10-14
				GROUP BY b.itemFk 
		) c
			JOIN vn.item i ON i.id = c.item_id
			JOIN vn.itemType it ON it.id = i.typeFk
		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 il.itemFk AS item_id, stock
			FROM tmp.itemList il
				JOIN item_range ir ON ir.item_id = il.itemFk 
		UNION ALL
		SELECT t.item_id, minacum(dt, amount, vDate) AS available FROM (
			SELECT itemFk AS item_id, DATE(dat) dt, SUM(quantity) amount FROM (
				SELECT i.itemFk, i.shipped AS dat, i.quantity
					FROM vn.itemTicketOut i
						JOIN item_range_copy1 ir ON ir.item_id = i.itemFk
					WHERE i.shipped >= vStartDate
						AND (ir.date_end IS NULL OR i.shipped <= ir.date_end)
						AND i.warehouseFk = vWarehouse
				UNION ALL
				SELECT i.itemFk, i.landed AS dat, i.quantity
					FROM vn.itemEntryIn i
						JOIN item_range_copy2 ir ON ir.item_id = i.itemFk
					WHERE i.landed >= vStartDate
						AND (ir.date_end IS NULL OR i.landed <= ir.date_end)
						AND i.warehouseInFk = vWarehouse
				UNION ALL
				SELECT i.itemFk, i.shipped AS dat, i.quantity
					FROM vn.itemEntryOut i
						JOIN item_range_copy3 ir ON ir.item_id = i.itemFk 
					WHERE i.shipped >= vStartDate 
						AND (ir.date_end IS NULL OR i.shipped <= ir.date_end)
						AND i.warehouseOutFk = 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;

	DROP TEMPORARY TABLE IF EXISTS 
		tmp.itemList
		,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 `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
-- bernat working in this file
	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*/ -- JGF cau-13144	2019-10-14
				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;

	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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `cache_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  = 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 `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?
    SELECT inventoried INTO started FROM vn.config LIMIT 1;
	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 `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  = 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 `last_buy_refresh__`(vRefresh BOOL)
proc: BEGIN
/**
 * BERNAT: WORKING IN THIS FILE
 * 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  = 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 `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 inventoried FROM vn.config 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 itemFk AS item_id, warehouseFk AS warehouse_id, quantity AS amount 
			FROM vn.itemTicketOut
			WHERE shipped >= v_date_inv AND shipped < v_curdate
		UNION ALL
		SELECT itemFk ASitem_id, warehouseInFk AS warehouse_id, quantity AS amount 
			FROM vn.itemEntryIn
			WHERE landed >= v_date_inv AND landed < v_curdate AND isVirtualStock is FALSE
		UNION ALL
		SELECT itemFk AS item_id ,warehouseOutFk AS warehouse_id, quantity AS amount 
			FROM vn.itemEntryOut
			WHERE shipped >= v_date_inv AND shipped < 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 `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  = 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 `stock_refresh__`(v_refresh BOOL)
proc: BEGIN
/**
 * bernat: WORKING IN THIS FILE
 * 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 `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 vn.item_GetVisible(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 `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
	-- bernat working in this file
	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 */ ;

--
-- 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 `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 `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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `ekt`
--

DROP TABLE IF EXISTS `ekt`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ekt` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `barcode` char(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `entryYear` smallint(5) unsigned NOT NULL,
  `deliveryNumber` 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,
  `k1` smallint(5) unsigned DEFAULT NULL,
  `k2` smallint(5) unsigned DEFAULT NULL,
  `k3` tinyint(3) unsigned DEFAULT NULL,
  `k4` 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',
  `trolleyFk` 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`,`entryYear`),
  UNIQUE KEY `entry_year` (`deliveryNumber`,`entryYear`) USING BTREE,
  KEY `ref` (`ref`),
  KEY `ptj` (`ptj`),
  KEY `pro` (`pro`),
  KEY `kop` (`kop`),
  KEY `barcode` (`barcode`),
  KEY `fec` (`fec`),
  KEY `putOrderFk` (`putOrderFk`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `exchange`
--

DROP TABLE IF EXISTS `exchange`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `exchange` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `mailFk` int(10) unsigned NOT NULL,
  `typeFk` smallint(5) unsigned NOT NULL,
  `ektFk` int(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `type_id` (`typeFk`,`ektFk`),
  KEY `message_id` (`mailFk`),
  KEY `buy_edi_id` (`ektFk`),
  CONSTRAINT `exchange_ibfk_1` FOREIGN KEY (`mailFk`) REFERENCES `mail` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `exchange_ibfk_2` FOREIGN KEY (`ektFk`) REFERENCES `ekt` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `exchangeConfig`
--

DROP TABLE IF EXISTS `exchangeConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `exchangeConfig` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `logMail` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Mail where the log information is sent',
  `restrictToSenders` tinyint(4) NOT NULL COMMENT 'Whether to process mails only from known senders',
  `presaleFk` mediumint(8) unsigned DEFAULT NULL,
  `defaultKop` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `presale_id` (`presaleFk`),
  CONSTRAINT `exchangeConfig_ibfk_1` FOREIGN KEY (`presaleFk`) REFERENCES `exchangeType` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Configuration parameters';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `exchangeType`
--

DROP TABLE IF EXISTS `exchangeType`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `exchangeType` (
  `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 `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 `fileConfig`
--

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

--
-- Table structure for table `ftpConfig`
--

DROP TABLE IF EXISTS `ftpConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ftpConfig` (
  `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=InnoDBDEFAULT 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 `imapConfig`
--

DROP TABLE IF EXISTS `imapConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `imapConfig` (
  `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,
  `cleanPeriod` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'How long the old mails are preserved',
  `successFolder` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `errorFolder` 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`)
) 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,
  `senderFk` int(10) unsigned DEFAULT NULL,
  `sender` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `messageId` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `nExchanges` int(10) unsigned NOT NULL,
  `error` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `mail_id` (`messageId`),
  KEY `sender_id` (`senderFk`),
  CONSTRAINT `mail_ibfk_2` FOREIGN KEY (`senderFk`) REFERENCES `mailSender` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `mailSender`
--

DROP TABLE IF EXISTS `mailSender`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mailSender` (
  `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=InnoDBDEFAULT 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 `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=InnoDBDEFAULT 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `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 */;

--
-- 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`),
  KEY `IX_TransNumber` (`TransactionNumber`) COMMENT 'Agregado por Ernesto 11.6.2019\nSe ejecutaba 1 consulta por segundo desde MAIL y consumia un 20% de CPU de todo el servidor !!!!!\nCPU usada es mas estable que Indice en SendererID, cpu vs espacio que ocupa?\n'
) ENGINE=InnoDBDEFAULT 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 FUNCTION IF EXISTS `floramondoTodayEntryGet` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `floramondoTodayEntryGet`() RETURNS int(11)
    READS SQL DATA
BEGIN

	DECLARE myTravel INT;
    DECLARE myEntry INT;
    
    SET myTravel = FloramondoTodayTravelGet();
    
    SELECT IFNULL(MAX(id),0) INTO myEntry 
		FROM vn.entry
		WHERE travelFk = myTravel;
      
    IF NOT myEntry THEN
    
		INSERT INTO vn.entry(travelFk, supplierFk, commission, companyFk, currencyFk)
			SELECT myTravel, s.id, 4, c.id, cu.id
				FROM vn.supplier s
					JOIN vn.company c ON c.code = 'VNL'
                    JOIN vn.currency cu ON cu.code = 'EUR'
                WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN';
                
		SELECT IFNULL(MAX(id),0) INTO myEntry 
			FROM vn.entry
			WHERE travelFk = myTravel;
            
    END IF;

	RETURN myEntry;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `floramondoTodayTravelGet` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `floramondoTodayTravelGet`() RETURNS int(11)
    READS SQL DATA
BEGIN

	DECLARE myTravel INT;

	SELECT IFNULL(MAX(tr.id),0) INTO myTravel 
		FROM vn.travel tr
        JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk
        JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk
		WHERE wIn.name = 'VNH'
			AND wOut.name = 'Floramondo'
			AND landed = CURDATE();

	IF NOT myTravel THEN
    
		INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyFk)
			SELECT CURDATE(), util.yesterday(), wIn.id, wOut.id, am.id 
				FROM vn.warehouse wIn
					JOIN vn.warehouse wOut ON wOut.name = 'Floramondo'
                    JOIN vn.agencyMode am ON am.name = 'HOLANDA DIRECTO'
                WHERE wIn.name = 'VNH';
                
		SELECT MAX(tr.id) INTO myTravel 
			FROM vn.travel tr
				JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk
				JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk
					WHERE wIn.name = 'VNH'
						AND wOut.name = 'Floramondo'
						AND landed = CURDATE();
            
    END IF;

	RETURN myTravel;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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

	DELETE di.* 
		FROM edi.deliveryInformation di
			-- LEFT JOIN vn.buy b ON b.deliveryFk = di.ID
		WHERE LatestOrderDateTime < CURDATE()
			-- AND b.id 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 `ekt_load` */;
/*!50003 SET @saved_cs_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 `ekt_load`(IN `vSelf` 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 ekt e
			LEFT JOIN item i ON e.ref = i.id
		WHERE e.id = vSelf;

	-- 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 = vSelf
			AND l.id != vSelf
			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 = vSelf;
					
			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
		,vSelf
		,(@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 = vSelf
		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 `exchange_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 `exchange_new`(
	IN `vMailFk` 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
/**
 * Adds a new exchange, generates it's barcode and
 * inserts/updates the transaction. When the referenced
 * transaction exists as provisional, updates it with
 * the new values.
 */
	DECLARE vEkt INT;
	DECLARE vRewriteKop INT DEFAULT NULL;
	DECLARE vBarcode CHAR(15) DEFAULT NULL;
	DECLARE vIsDuplicated BOOL;
	DECLARE vUpdateExistent BOOL DEFAULT FALSE;
	DECLARE duplicateKey CONDITION FOR 1062;

	DECLARE CONTINUE HANDLER FOR duplicateKey
		SET vIsDuplicated = TRUE;

	-- Generates the barcode

	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;

	-- Rewrites the kop parameter

	IF vKop IS NULL THEN
		SELECT defaultKop INTO vKop FROM exchangeConfig;
	END IF;

	SELECT e.kop INTO vRewriteKop
		FROM mailSender e
			JOIN mail m ON m.senderFk = e.id
		WHERE m.id = vMailFk;

	SET vKop = IFNULL(vRewriteKop, vKop);

	-- Inserts the new transaction

	SET vIsDuplicated = FALSE;
	INSERT INTO ekt SET
		 barcode = IFNULL(vBarcode, barcode)
		,deliveryNumber = vDeliveryNumber
		,entryYear = 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
		,k1 = vK1
		,k2 = vK2
		,k3 = vP1
		,k4 = vP2
		,auction = vAuction
		,package = vPackage
        ,putOrderFk = vPutOrderFk;

	-- If it exists duplicado updates it

	IF NOT vIsDuplicated 
	THEN
		SET vEkt = LAST_INSERT_ID();
		CALL ekt_load (vEkt);

	ELSEIF vDeliveryNumber != 0
	AND vDeliveryNumber IS NOT NULL
	THEN
		SELECT id INTO vEkt
			FROM ekt
			WHERE deliveryNumber = vDeliveryNumber;

		SELECT COUNT(*) = 0 INTO vUpdateExistent
			FROM ekt t
				JOIN `exchange` b ON b.ektFk = t.id
				JOIN exchangeConfig c
			WHERE t.deliveryNumber = vDeliveryNumber
				AND t.entryYear = YEAR(vDate)
				AND b.typeFk != c.presaleFk;
	END IF;

	IF vUpdateExistent
	THEN
		UPDATE ekt 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
			,k1 = vK1
			,k2 = vK2
			,k3 = vP1
			,k4 = vP2
			,auction = vAuction
			,package = vPackage
            ,putOrderFk = vPutOrderFk
		WHERE id = vEkt;
	END IF;

	-- Registers the exchange

	INSERT INTO `exchange` SET
		 mailFk = vMailFk
		,typeFk = vType
		,ektFk = vEkt;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `mail_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 `mail_new`(
	 vMessageId VARCHAR(100)
	,vSender VARCHAR(150)
    ,OUT vSelf INT
)
BEGIN
/**
 * Registers a mail message.
 *
 * @param vMessageId Message-ID of email
 * @param vSender Id of mail sender
 * @param vSelf The created message id
 */
	DECLARE vSenderId INT;
	DECLARE vIsDuplicated BOOL;
	DECLARE duplicateKey CONDITION FOR 1062;

	DECLARE CONTINUE HANDLER FOR duplicateKey
		SET vIsDuplicated = TRUE;

	SELECT id INTO vSenderId
		FROM mailSender
		WHERE mail = vSender;

	SET vIsDuplicated = FALSE;
	INSERT INTO mail SET
		sender = vSender,
		senderFk = vSenderId,
		messageId = vMessageId;
		
	IF vIsDuplicated THEN
		SELECT id INTO vSelf
			FROM mail
			WHERE messageId = vMessageId;
	ELSE
		SET vSelf = 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 */ ;

--
-- 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 `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- 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',
  `dmsDir` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Directory where documents are allocated',
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `image`
--

DROP TABLE IF EXISTS `image`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `image` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `collectionFk` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `updated` int(11) DEFAULT NULL,
  `nRefs` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `collection` (`collectionFk`,`name`),
  CONSTRAINT `image_ibfk_1` FOREIGN KEY (`collectionFk`) REFERENCES `imageCollection` (`name`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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,
  `model` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `property` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `schema` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Deprecated',
  `table` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Deprecated',
  `column` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Deprecated',
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT CHARSET=utf8 COMMENT='Global image parameters';
/*!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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`link_afterInsert`
	AFTER INSERT ON `link`
    FOR EACH ROW
BEGIN
	CALL image_ref('link', NEW.image);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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`.`link_afterUpdate`
	AFTER UPDATE ON `link`
	FOR EACH ROW
BEGIN
	IF !(NEW.image <=> OLD.image) THEN
		CALL image_unref('link', OLD.image);
		CALL image_ref('link', NEW.image);
	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`.`link_afterDelete`
	AFTER DELETE ON `link`
    FOR EACH ROW
BEGIN
	CALL image_unref('link', OLD.image);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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 `hasPdf`*/;
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 `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 `myOrderTicket`
--

DROP TABLE IF EXISTS `myOrderTicket`;
/*!50001 DROP VIEW IF EXISTS `myOrderTicket`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `myOrderTicket` AS SELECT 
 1 AS `orderFk`,
 1 AS `ticketFk`*/;
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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`news_afterInsert`
	AFTER INSERT ON `news`
    FOR EACH ROW
BEGIN
	CALL image_ref('news', NEW.image);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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`.`news_afterUpdate`
	AFTER UPDATE ON `news`
    FOR EACH ROW
BEGIN
	IF !(NEW.image <=> OLD.image) THEN
		CALL image_unref('news', OLD.image);
		CALL image_ref('news', NEW.image);
	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`.`news_afterDelete`
	AFTER DELETE ON `news`
    FOR EACH ROW
BEGIN
	CALL image_unref('news', OLD.image);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `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,
  `taxableBase` decimal(10,2) NOT NULL,
  `tax` decimal(10,2) NOT NULL,
  `total` decimal(10,2) NOT 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 `vn`.`address` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `order_ibfk_8` FOREIGN KEY (`delivery_method_id`) REFERENCES `vn`.`deliveryMethod` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `order_ibfk_9` FOREIGN KEY (`agency_id`) REFERENCES `vn`.`agencyMode` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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', NEW.id, OLD.id);
    
    IF !(OLD.address_id <=> NEW.address_id)
    OR !(OLD.company_id <=> NEW.company_id)
    OR !(OLD.customer_id <=> NEW.customer_id) THEN
		CALL order_requestRecalc(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 */ ;
/*!50003 SET @saved_cs_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,
  `guestAddressFk` 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`),
  KEY `guestAddressFk` (`guestAddressFk`),
  CONSTRAINT `orderConfig_ibfk_1` FOREIGN KEY (`employeeFk`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `orderConfig_ibfk_2` FOREIGN KEY (`defaultCompanyFk`) REFERENCES `vn`.`company` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `orderConfig_ibfk_3` FOREIGN KEY (`guestAgencyFk`) REFERENCES `vn`.`agencyMode` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `orderConfig_ibfk_4` FOREIGN KEY (`defaultAgencyFk`) REFERENCES `vn`.`agencyMode` (`id`),
  CONSTRAINT `orderConfig_ibfk_5` FOREIGN KEY (`guestAddressFk`) REFERENCES `vn`.`address` (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `orderRecalc`
--

DROP TABLE IF EXISTS `orderRecalc`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `orderRecalc` (
  `orderFk` int(10) unsigned NOT NULL,
  PRIMARY KEY (`orderFk`),
  CONSTRAINT `orderRecalc_ibfk_1` FOREIGN KEY (`orderFk`) REFERENCES `order` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Queue of changed orders to recalc it''s total';
/*!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,
  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 `vn`.`item` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `orderRow_ibfk_3` FOREIGN KEY (`orderFk`) REFERENCES `order` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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', NEW.id, NULL);
    CALL order_requestRecalc(NEW.orderFk);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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', NEW.id, OLD.id);
    CALL order_requestRecalc(OLD.orderFk);
    CALL order_requestRecalc(NEW.orderFk);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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', NULL, OLD.id);
    CALL order_requestRecalc(OLD.orderFk);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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=InnoDBDEFAULT 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 `vn`.`itemType` (`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 `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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 `vn`.`worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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=InnoDBDEFAULT 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 `vn`.`receipt` (`Id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `tpvTransaction_ibfk_1` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `tpvTransaction_ibfk_2` FOREIGN KEY (`merchantFk`) REFERENCES `tpvMerchant` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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,
  `userVisitFk` int(10) unsigned DEFAULT NULL,
  UNIQUE KEY `ssid` (`ssid`),
  KEY `userVisit` (`userVisitFk`),
  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,
  `firstAgentFk` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `firstAgent` (`firstAgentFk`),
  CONSTRAINT `visit_ibfk_1` FOREIGN KEY (`firstAgentFk`) REFERENCES `visitAgent` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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,
  `agentFk` 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` (`agentFk`),
  KEY `stamp` (`stamp`),
  CONSTRAINT `visitAccess_ibfk_1` FOREIGN KEY (`agentFk`) REFERENCES `visitAgent` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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,
  `visitFk` int(10) unsigned NOT NULL,
  `firstAccessFk` 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` (`visitFk`),
  KEY `firstAccess` (`firstAccessFk`),
  CONSTRAINT `visitAgent_ibfk_1` FOREIGN KEY (`visitFk`) REFERENCES `visit` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `visitAgent_ibfk_2` FOREIGN KEY (`firstAccessFk`) REFERENCES `visitAccess` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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,
  `accessFk` int(10) unsigned NOT NULL,
  `userFk` int(10) unsigned DEFAULT NULL,
  `stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `access_id` (`accessFk`),
  KEY `date_time` (`stamp`),
  KEY `user_id` (`userFk`),
  CONSTRAINT `visitUser_ibfk_1` FOREIGN KEY (`accessFk`) REFERENCES `visitAccess` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping events for database 'hedera'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `order_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=`root`@`%`*/ /*!50106 EVENT `order_doRecalc` ON SCHEDULE EVERY 10 SECOND STARTS '2019-08-29 14:18:04' ON COMPLETION PRESERVE ENABLE DO CALL order_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 'hedera'
--
/*!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 `myClient_getDebt` */;
/*!50003 SET @saved_cs_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 `myClient_getDebt`(vDate DATE) RETURNS decimal(10,2)
    DETERMINISTIC
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 `myUser_checkRestPriv` */;
/*!50003 SET @saved_cs_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 `myUser_checkRestPriv`(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 FUNCTION IF EXISTS `order_getTotal` */;
/*!50003 SET @saved_cs_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 `order_getTotal`(vSelf 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 vSelf 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 vSelf orderFk;

	CALL order_getTotal;

	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 PROCEDURE IF EXISTS `catalog_calcFromMyAddress` */;
/*!50003 SET @saved_cs_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_calcFromMyAddress`(vDelivery DATE, vAddress INT)
BEGIN
/**
 * Gets the available items list.
 *
 * @param vDelivery Delivery date
 * @param vAddress Address id
 * @return tmp.ticketCalculateItem
 * @return tmp.ticketComponentPrice
 * @return tmp.ticketComponent
 * @return tmp.ticketLot
 * @return tmp.zoneGetShipped
 */  
    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 vn.available_calc(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 tmp.availableCalc a ON a.calcFk = c.calc_id
			WHERE c.available > 0
			GROUP BY c.item_id;
 
	CALL vn.catalog_calculate(vDelivery, vAddress, vAgencyMode);

	DROP TEMPORARY TABLE 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 `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 `image_ref` */;
/*!50003 SET @saved_cs_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 `image_ref`(
    vCollection VARCHAR(255),
	vName VARCHAR(255)
)
proc: BEGIN
/**
 * Increases the reference count of an image.
 *
 * @param vCollection The collection name
 * @param vName The image name
 */
	IF vName IS NULL THEN
		LEAVE proc;
	END IF;

	INSERT INTO `image`
		SET `collectionFk` = vCollection,
			`name` = vName,
			`updated` = UNIX_TIMESTAMP(),
			`nRefs` = 1
		ON DUPLICATE KEY UPDATE
			`nRefs` = nRefs + 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 `image_unref` */;
/*!50003 SET @saved_cs_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 `image_unref`(
    vCollection VARCHAR(255),
	vName VARCHAR(255)
)
BEGIN
/**
 * Decreases the reference count of an image.
 *
 * @param vCollection The collection name
 * @param vName The image name
 */
	UPDATE image SET nRefs = GREATEST(CAST(nRefs AS SIGNED) - 1, 0)
		WHERE `name` = vName
			AND collectionFk = vCollection;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_calcCatalog` */;
/*!50003 SET @saved_cs_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_calcCatalog`(
	vSelf INT,
	vLanded DATE,
    vAddressFk INT,
    vAgencyModeFk INT)
BEGIN
/**
 * Calculates available and price for a single item.
 *
 * @param vItemFk The item id
 * @return List of available lots
 */
	DROP TEMPORARY TABLE IF EXISTS tmp.item;
	CREATE TEMPORARY TABLE tmp.item
		ENGINE = MEMORY 
		SELECT vSelf itemFk;

	CALL vn.catalog_calculate(vLanded, vAddressFk, vAgencyModeFk);

	SELECT l.warehouseFk, w.name warehouse,
			p.`grouping`, p.price, p.rate, l.available
		FROM tmp.ticketLot l
			JOIN tmp.ticketComponentPrice p ON p.warehouseFk = l.warehouseFk
			JOIN vn.warehouse w ON w.id = p.warehouseFk
		ORDER BY warehouseFk, `grouping`;

	DROP TEMPORARY TABLE
		tmp.ticketCalculateItem,
		tmp.ticketComponentPrice,
		tmp.ticketComponent,
		tmp.ticketLot,
		tmp.zoneGetShipped;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 vn.buyUltimate(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 tmp.buyUltimate bu ON bu.itemFk = a.id
			JOIN vn.buy b ON b.id = bu.buyFk
		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_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `item_getVisible`(
	vWarehouse TINYINT,
    vDate DATE,
    vType INT,
    vPrefix VARCHAR(255))
BEGIN
/**
 * Gets visible items of the specified type at specified date.
 *
 * @param vWarehouse 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 = vWarehouse
						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 = vWarehouse
						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 = vWarehouse
						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 = vWarehouse 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) depth, p.width, p.height,
				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_calcCatalogFromItem` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myBasket_calcCatalogFromItem`(vItem INT)
BEGIN
/**
 * Gets the availability and prices for the given item
 * using current user basket parameters.
 *
 * @table tmp.item(itemFk)
 * @return tmp.ticketCalculateItem
 * @return tmp.ticketComponentPrice
 * @return tmp.ticketComponent
 * @return tmp.ticketLot
 * @return tmp.zoneGetShipped
 */
	CALL order_calcCatalogFromItem(myBasket_getId(), 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 `myBasket_calcCatalogFull` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myBasket_calcCatalogFull`()
BEGIN
/**
 * Gets the availability and prices for the given items
 * using current user basket parameters.
 *
 * @table tmp.item(itemFk)
 * @return tmp.ticketCalculateItem
 * @return tmp.ticketComponentPrice
 * @return tmp.ticketComponent
 * @return tmp.ticketLot
 * @return tmp.zoneGetShipped
 */
	CALL order_calcCatalogFull(myBasket_getId());
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 order_checkConfig(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 order_checkConfig(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(255);
    DECLARE vAgency INT;
    DECLARE vAddress INT;
    DECLARE vDate DATE;
    
    SELECT guestMethod, guestAgencyFk, guestAddressFk
		INTO vMethod, vAgency, vAddress
        FROM orderConfig
        LIMIT 1;
        
	SET vDate = TIMESTAMPADD(DAY, 1, CURDATE());
    
    IF WEEKDAY(vDate) BETWEEN 5 AND 6 THEN
		SET vDate = TIMESTAMPADD(DAY, 7 - WEEKDAY(vDate), vDate);
	END IF;
    
    CALL myBasket_configure(vDate, vMethod, vAgency, vAddress);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myBasket_getAvailable`()
BEGIN
/**
 * Gets the available items list.
 *
 * @table tmp.itemAvailable
 */
	CALL order_getAvailable(myBasket_getId());
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 order_getTax();
    
    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 `myOrder_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 `myOrder_addItem`(
	vSelf INT,
    vWarehouse INT,
    vItem INT,
    vAmount INT)
BEGIN
	DECLARE vIsMine BOOL;

	SELECT COUNT(*) INTO vIsMine
		FROM myOrder
		WHERE id = vSelf;
		
	IF vIsMine 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 `myOrder_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 `myOrder_confirm`(vSelf INT)
BEGIN
	DECLARE vIsMine BOOL;
    
    SELECT COUNT(*) INTO vIsMine 
		FROM myOrder
        WHERE id = vSelf;
        
	IF vIsMine 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 `myOrder_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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myOrder_getAvailable`(vSelf INT)
BEGIN
/**
 * Gets the available items list.
 *
 * @param vSelf The order id
 * @table tmp.itemAvailable
 */
	DECLARE isMine BOOL;

	SELECT COUNT(*) INTO isMine
		FROM myOrder
		WHERE id = vSelf;
		
	IF isMine THEN
		CALL order_getAvailable(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 `myOrder_newWithAddress` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `myOrder_newWithAddress`(
	OUT vSelf INT,
    vLandingDate DATE,
    vAddressFk INT)
BEGIN
/**
 * Crea una nueva orden para el usuario actual especificando
 * una fecha de entrega.
 *
 * @param vSelf Id de la nueva orden
 * @param vLandingDate Fecha de entrega
 */
	DECLARE vCompany INT;
	DECLARE vDeliveryMethodId INT;
	DECLARE vAgencyMode INT;

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

	START TRANSACTION;

	SELECT a.agencyModeFk, a.id 
			INTO vAgencyMode, vAddressFk
		FROM vn.address a 
		WHERE a.id = vAddressFk;
				
	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 = vAddressFk,
			source_app = 'WEB',
			company_id = vCompany;

	SET vSelf = LAST_INSERT_ID();
	 
	CALL order_checkConfig(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 `myOrder_newWithDate` */;
/*!50003 SET @saved_cs_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 `myOrder_newWithDate`(
	OUT vSelf INT,
    vLandingDate DATE)
BEGIN
/**
 * Crea una nueva orden para el usuario actual especificando
 * una fecha de entrega.
 *
 * @param vSelf 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 vSelf = NULL;
	DECLARE EXIT HANDLER FOR SQLSTATE '45000'
	BEGIN
		ROLLBACK;
		SET vSelf = 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 vSelf = LAST_INSERT_ID();
	 
	CALL order_checkConfig(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 `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, t.nickname,
			ag.description agency, m.code method,
			a.street, a.postalCode, a.city, 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, im.updated, 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
			LEFT JOIN image im
				ON im.collectionFk = 'catalog'
				AND im.name = i.image
		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.category, i.size, i.stems, i.inkFk,
			i.tag5, i.value5, i.tag6, i.value6, i.tag7, i.value7,
            i.image, im.updated
		FROM myTicketRow r
			JOIN vn.item i ON i.id = r.itemFk
			LEFT JOIN image im
				ON im.collectionFk = 'catalog'
				AND im.name = i.image
		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(MONTH, -3, 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, v.nickname,
			a.city, 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 `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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `order_addItem`(
	vSelf INT,
    vWarehouse INT,
    vItem INT,
	vAmount INT)
BEGIN
/**
 * Adds an item to the order, checking availability and grouping.
 *
 * @param vSelf The order id
 * @param vWarehouse The warehouse id
 * @param vItem The item id
 * @param vAmount The amount to add
 */
	DECLARE vRow INT;
	DECLARE vAdd INT;
	DECLARE vAvailable INT;
	DECLARE vDone BOOL;
	DECLARE vGrouping INT;
	DECLARE vRate INT;
	DECLARE vShipment DATE;
	DECLARE vPrice DECIMAL(10,2);
	DECLARE cur CURSOR FOR
		SELECT `grouping`, price, rate
			FROM tmp.ticketComponentPrice
			WHERE warehouseFk = vWarehouse
				AND itemFk = vItem
			ORDER BY `grouping` DESC;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

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

	CALL order_calcCatalogFromItem(vSelf, vItem);
	START TRANSACTION;

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

	SELECT available INTO vAvailable
		FROM tmp.ticketLot
		WHERE warehouseFk = vWarehouse
			AND itemFk = 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 orderRow SET
			orderFk = vSelf,
			itemFk = vItem,
			warehouseFk = vWarehouse,
			shipment = vShipment,
			rate = vRate,
			amount = vAdd,
			price = vPrice;
			
		SET vRow = LAST_INSERT_ID();

		INSERT INTO orderRowComponent (rowFk, componentFk, price)
			SELECT vRow, c.componentFk, c.cost
				FROM tmp.ticketComponent c
					JOIN vn.component t
						ON t.id = c.componentFk
						AND (t.classRate IS NULL OR t.classRate = vRate)
				WHERE c.warehouseFk = vWarehouse
					AND c.itemFk = vItem;
	END LOOP;

	CLOSE cur;

	IF vAmount > 0 THEN
		CALL util.throw ('AMOUNT_NOT_MATCH_GROUPING');
	END IF;
				
	COMMIT;
    CALL vn.ticketCalculatePurge;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_calcCatalog` */;
/*!50003 SET @saved_cs_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_calcCatalog`(vSelf INT)
BEGIN
/**
 * Gets the availability and prices for order items.
 *
 * @param vSelf The order id
 * @return tmp.ticketCalculateItem
 * @return tmp.ticketComponentPrice
 * @return tmp.ticketComponent
 * @return tmp.ticketLot
 */
	DECLARE vDate DATE;
	DECLARE vAddress INT;
	DECLARE vAgencyMode INT;

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

	DROP TEMPORARY TABLE IF EXISTS tmp.item;
	CREATE TEMPORARY TABLE tmp.item
		(PRIMARY KEY (itemFk))
		ENGINE = MEMORY
		SELECT itemFk FROM orderRow 
			WHERE orderFk = vSelf
			GROUP BY itemFk;
		
	CALL vn.catalog_calculate(vDate, vAddress, vAgencyMode);

	DROP TEMPORARY TABLE 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 `order_calcCatalogFromItem` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `order_calcCatalogFromItem`(vSelf INT, vItem INT)
BEGIN
/**
 * Gets the availability and prices for the given item
 * using the order parameters.
 *
 * @param vSelf The order id
 * @table tmp.item(itemFk)
 * @return tmp.ticketCalculateItem
 * @return tmp.ticketComponentPrice
 * @return tmp.ticketComponent
 * @return tmp.ticketLot
 * @return tmp.zoneGetShipped
 */
	DECLARE vDate DATE;
	DECLARE vAddress INT;
	DECLARE vAgencyMode INT;

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

	CALL vn.catalog_calcFromItem(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 `order_calcCatalogFull` */;
/*!50003 SET @saved_cs_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_calcCatalogFull`(vSelf INT)
BEGIN
/**
 * Gets the availability and prices for the given items
 * using the order parameters.
 *
 * @param vSelf The order id
 * @table tmp.item(itemFk)
 * @return tmp.ticketCalculateItem
 * @return tmp.ticketComponentPrice
 * @return tmp.ticketComponent
 * @return tmp.ticketLot
 * @return tmp.zoneGetShipped
 */
	DECLARE vDate DATE;
	DECLARE vAddress INT;
	DECLARE vAgencyMode INT;

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

	CALL vn.catalog_calculate(vDate, vAddress, vAgencyMode);

	IF account.myUserGetName() = 'visitor'
	THEN
		DROP TEMPORARY TABLE tmp.ticketComponent;
		UPDATE tmp.ticketCalculateItem 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 `order_checkConfig` */;
/*!50003 SET @saved_cs_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_checkConfig`(vSelf INT)
BEGIN
/**
 * Comprueba que la configuración del pedido es correcta.
 *
 * @param vSelf Identificador del pedido
 */
	DECLARE vDeliveryMethod VARCHAR(255);
	DECLARE vLanded DATE;
	DECLARE vAgencyMode INT;
	DECLARE vAddress INT;
    DECLARE vIsAvailable BOOL;

	-- Obtiene los datos del pedido

	SELECT d.code, o.date_send, o.agency_id, o.address_id
		INTO vDeliveryMethod, vLanded, vAgencyMode, vAddress
		FROM `order` o
			JOIN vn.deliveryMethod d ON d.id = o.delivery_method_id
		WHERE o.id = vSelf;

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

	CALL vn.zoneGetAgency(vAddress, vLanded);
    
    SELECT COUNT(*) > 0 INTO vIsAvailable
		FROM tmp.zoneGetAgency
        WHERE agencyModeFk = vAgencyMode;

	IF !vIsAvailable THEN
		CALL util.throw ('ORDER_INVALID_AGENCY');
	END IF;
    
    DROP TEMPORARY TABLE tmp.zoneGetAgency;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 vIsConfirmed BOOL;
	DECLARE vClientId INT;
	DECLARE vCompanyId INT;
	DECLARE vAgencyModeId INT;

	DECLARE TICKET_FREE INT DEFAULT 2;

	DECLARE cDates CURSOR FOR
		SELECT zgs.shipped, r.warehouse_id
			FROM `order` o
				JOIN order_row r ON r.order_id = o.id
				LEFT JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = r.warehouse_id
			WHERE o.id = vOrder AND r.amount != 0
			GROUP BY r.warehouse_id;

	DECLARE cRows CURSOR FOR 
		SELECT r.id, r.item_id, i.name, r.amount, r.price, r.rate
			FROM order_row r
				JOIN vn.item i ON i.id = 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,
			o.confirmed, a.clientFk, o.company_id, o.agency_id
		INTO vDelivery, vAddress, vNotes, 
			vIsConfirmed, vClientId, vCompanyId, vAgencyModeId
		FROM hedera.`order` o
			JOIN vn.address a ON a.id = o.address_id
		WHERE o.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.zone_getShippedWarehouse (vDelivery, vAddress, vAgencyModeId);

	-- 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 t.id INTO vTicket
			FROM vn.ticket t
				LEFT JOIN vn.ticketState tls on tls.ticket = t.id
				JOIN `order` o
					ON o.address_id = t.addressFk
						AND vWarehouse = t.warehouseFk
						AND o.agency_id = t.agencyModeFk
						AND o.date_send = t.landed 
						AND vShipment = DATE(t.shipped)
			WHERE o.id = vOrder
				AND t.invoiceOutFk IS NULL
				AND IFNULL(tls.alertLevel,0) = 0
                AND t.clientFk <> 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 = vUserId,
					state_id = TICKET_FREE;
		END IF;
		
		INSERT IGNORE INTO vn.orderTicket
			SET orderFk = vOrder,
				ticketFk = vTicket;

		-- Añade las notas

		IF vNotes IS NOT NULL AND vNotes != ''
		THEN
			INSERT INTO vn.ticketObservation SET
					ticketFk = vTicket,
					observationTypeFk = 4 /* salesperson */ ,
					`description` = vNotes
				ON DUPLICATE KEY UPDATE
					`description` = CONCAT(VALUES(`description`),'. ', `description`);
		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 vn.sale 
			SET
				itemFk = vItem,
				ticketFk = vTicket,
				concept = vConcept,
				quantity = vAmount,
				price = vPrice,
				priceFixed = 0,
				isPriceFixed = TRUE;

			SET vSale = LAST_INSERT_ID();

			INSERT INTO vn.saleComponent
				(saleFk, componentFk, `value`)
				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(sc.`value`) valueSum, sc.saleFk
				FROM vn.saleComponent sc
					JOIN bi.tarifa_componentes tc ON tc.Id_Componente = sc.componentFk
					JOIN bi.tarifa_componentes_series tcs
						ON tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id
							AND tcs.base
					JOIN vn.sale s
						ON s.id = sc.saleFk
				WHERE s.ticketFk = vTicket
				GROUP BY sc.saleFk;

		UPDATE vn.sale s
			JOIN tComponents mc ON mc.saleFk = s.id
			SET s.priceFixed = 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_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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `order_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 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 zgs.shipped, r.warehouse_id
			FROM `order` o
				JOIN order_row r ON r.order_id = o.id
				LEFT JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = r.warehouse_id
			WHERE o.id = vOrder AND r.amount != 0
			GROUP BY r.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,
			o.confirmed, cs.Id_Cliente, o.company_id, o.agency_id
		INTO vDelivery, vAddress, vNotes, 
			vIsConfirmed, vClientId, vCompanyId, vAgencyModeId
		FROM hedera.`order` o
			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.zoneGetShippedWarehouse (vDelivery, vAddress, vAgencyModeId);

	-- 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_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 `order_doRecalc`()
proc: BEGIN
/**
 * Recalculates modified orders.
 */
	DECLARE vDone BOOL;
	DECLARE vOrderFk INT;

	DECLARE cCur CURSOR FOR
		SELECT orderFk FROM orderRecalc;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;
        
	DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
    BEGIN
		DO RELEASE_LOCK('hedera.order_doRecalc');
		ROLLBACK;
        RESIGNAL;
	END;

	IF !GET_LOCK('hedera.order_doRecalc', 0) THEN
		LEAVE proc;
	END IF;

	OPEN cCur;

	myLoop: LOOP
		SET vDone = FALSE;
		FETCH cCur INTO vOrderFk;

		IF vDone THEN
			LEAVE myLoop;
		END IF;

		START TRANSACTION;
        CALL order_recalc(vOrderFk);
        COMMIT;

		DELETE FROM orderRecalc WHERE orderFk = vOrderFk;
	END LOOP;

	CLOSE cCur;
	DO RELEASE_LOCK('hedera.order_doRecalc');
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `order_getAvailable`(vSelf INT)
BEGIN
/**
 * Gets the available items list.
 *
 * @param vSelf The order id
 * @table tmp.itemAvailable
 */
	DECLARE vDelivery DATE;
	DECLARE vAddress INT;
	DECLARE vAgencyMode INT;

	SELECT date_send, address_id, agency_id
		INTO vDelivery, vAddress, vAgencyMode
		FROM `order`
		WHERE id = vSelf;
		
	CALL vn.available_calc(vDelivery, vAddress, vAgencyMode);

	DROP TEMPORARY TABLE IF EXISTS tmp.itemAvailable;
	CREATE TEMPORARY TABLE tmp.itemAvailable
		(INDEX (id))
		ENGINE = MEMORY
		SELECT DISTINCT a.item_id id
			FROM `cache`.available a
				JOIN tmp.availableCalc c ON c.calcFk = a.calc_id
			WHERE a.available > 0;

	DROP TEMPORARY TABLE tmp.availableCalc;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_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 `order_getTax`()
    READS SQL DATA
BEGIN
/**
 * Calcula el IVA, y el recargo de equivalencia de un pedido
 * desglosados por tipos.
 *
 * @param vOrder El identificador del pedido
 * @return 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, `code`,
				SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax
			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 `order_getTotal` */;
/*!50003 SET @saved_cs_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_getTotal`()
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 orden
 */
	CALL order_getTax;

	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
		tmp.orderTax,
        tmp.orderAmount;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_recalc` */;
/*!50003 SET @saved_cs_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_recalc`(vSelf INT)
BEGIN
/**
 * Recalculates the order total.
 *
 * @param vSelf The order id
 */
	DECLARE vTaxableBase DECIMAL(10,2);
	DECLARE vTax DECIMAL(10,2);

	DROP TEMPORARY TABLE IF EXISTS tmp.`order`;
	CREATE TEMPORARY TABLE tmp.`order`
		ENGINE = MEMORY
		SELECT vSelf orderFk;
		
	CALL order_getTax;

	SELECT IFNULL(SUM(taxableBase), 0.0), IFNULL(SUM(tax), 0.0)
		INTO vTaxableBase, vTax
		FROM tmp.orderAmount;

	UPDATE `order`
		SET taxableBase = vTaxableBase,
			tax = vTax,
			total = vTaxableBase + vTax
		WHERE id = vSelf;

	DROP TEMPORARY TABLE
		tmp.`order`,
		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_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 `order_requestRecalc`(vSelf INT)
proc: BEGIN
/**
 * Adds a request to recalculate the order total.
 *
 * @param vSelf The order identifier
 */
	IF vSelf IS NULL THEN
		LEAVE proc;
	END IF;

	INSERT IGNORE INTO orderRecalc SET orderFk = 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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `order_update`(vSelf INT)
proc: BEGIN
/**
 * Actualiza las líneas de un pedido.
 *
 * @param vSelf Id del pedido
 */
	DECLARE vDate DATE;
	DECLARE vAddress INT;
	DECLARE vAgencyMode INT;
	DECLARE vNRows INT;

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

	START TRANSACTION;

	SELECT COUNT(*) INTO vNRows
		FROM orderRow WHERE orderFk = vSelf;

	IF vNRows > 0
	THEN
        CALL order_calcCatalog(vSelf);

		DELETE c
			FROM orderRow r
				JOIN orderRowComponent c ON c.rowFk = r.id
				WHERE r.orderFk = vSelf;
				
		UPDATE orderRow r
			LEFT JOIN tmp.ticketComponentPrice p
				ON p.warehouseFk = r.warehouseFk
					AND p.itemFk = r.itemFk
					AND p.rate = r.rate
			LEFT JOIN tmp.zoneGetShipped t
				ON t.warehouseFk = r.warehouseFk
			SET
				r.price = p.price,
				r.amount = IF(p.itemFk IS NOT NULL,
					r.amount + IF(@m := MOD(r.amount, p.`grouping`), p.`grouping` - @m, 0), 0),
				r.shipment = t.shipped
			WHERE r.orderFk = vSelf;

		INSERT INTO orderRowComponent(rowFk, componentFk, price)
			SELECT r.id, c.componentFk, c.cost
				FROM orderRow r
					JOIN tmp.ticketComponent c
						ON c.warehouseFk = r.warehouseFk
							AND c.itemFk = r.itemFk
					JOIN vn.component t
						ON t.id = c.componentFk
							AND (t.classRate IS NULL OR t.classRate = r.rate)
				WHERE r.orderFk = vSelf;
        
		CALL vn.ticketCalculatePurge;
	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 `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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_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
			LEFT JOIN tpvTransaction t ON t.id = vOrder
				WHERE m.id = vMerchant;

		INSERT INTO vn.receipt
		SET
			amountPaid = vAmount / 100
			,payed = vDate
			,workerFk = vEmployee
			,bankFk = vBank
			,clientFk = vCustomer
			,companyFk = vCompany
			,invoiceFk = vConcept
            ,isConciliate = TRUE;

		SET vReceipt = LAST_INSERT_ID();
		SET vStatus = 'ok';

		-- Código redundante

		DO vn.till_new
		(
			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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_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 vn.receipt
		WHERE id = vReceipt LIMIT 1;

	-- Elimina la entrada de cajas

	DELETE FROM vn.till
		WHERE bankFk = vBank
		AND DATE(dated) = vDate
		AND `in` = vAmount
			LIMIT 1;

	-- Elimina los asientos contables

	SELECT accountingAccount INTO vSubaccount
		 FROM vn.`client` WHERE id = vCustomer;

	SELECT account INTO vAccount
		FROM vn.bank WHERE id = vBank;

	DELETE FROM vn.XDiario
		WHERE SUBCTA = vSubaccount
		AND CONTRA = vAccount
		AND DATE(FECHA) = vDate
		AND EUROHABER = vAmount
			LIMIT 1;

	DELETE FROM vn.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
		accessFk = vAccess,
		userFk = account.userGetId();

	SET vUserVisit = LAST_INSERT_ID();

	UPDATE userSession SET userVisitFk = 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_listByBrowser` */;
/*!50003 SET @saved_cs_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_listByBrowser`(vFrom DATE, vTo DATE)
BEGIN
/**
 * Lists visits grouped by browser.
 *
 * @param vFrom The from date
 * @param vTo The to date
 * @select The list of visits
 */
	SELECT browser,
			MIN(CAST(version AS DECIMAL(4, 1))) minVersion,
			MAX(CAST(version AS DECIMAL(4, 1))) maxVersion,
			MAX(c.stamp) lastVisit,
			COUNT(DISTINCT c.id) visits,
			SUM(a.firstAccessFk = c.id AND v.firstAgentFk = a.id) newVisits
		FROM visitUser e
			JOIN visitAccess c ON c.id = e.accessFk
			JOIN visitAgent a ON a.id = c.agentFk
			JOIN visit v ON v.id = a.visitFk
		WHERE c.stamp BETWEEN TIMESTAMP(vFrom,'00:00:00') AND TIMESTAMP(vTo,'23:59:59')
		GROUP BY browser ORDER BY visits 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 `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 visitFk = 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
			 visitFk = 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 firstAgentFk = vAgentId
			WHERE id = vVisit;
	END IF;

	-- Registers the user access

	INSERT INTO visitAccess SET
		 agentFk = vAgentId
		,ip = vIp
        ,referer = vReferer;

	SET vAccessId = LAST_INSERT_ID();

	IF vFirstAgent
    THEN
		UPDATE visitAgent SET firstAccessFk = 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 */ ;

--
-- 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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.depth = p.depth + 1',
		'			AND 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, depth INTO @vLeft, @vDepth',
			'	FROM ', vScheme, '.', vTable, 
            '   WHERE id = ', vParentFk
		));
    ELSE      
        CALL util.exec(CONCAT(
			'SELECT c.rgt, p.depth INTO @vLeft, @vDepth',
			'	FROM ', vScheme, '.', vTable, ' p',
			'		JOIN tmp.', vTableClone, ' c ON c.depth = p.depth + 1'
            '       	AND 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, depth)',
		'	VALUES ("', vChild, '", @vLeft + 1, @vLeft + 2, @vDepth + 1)'
	));
  
   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 */;
/*!50003 SET @saved_cs_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 `pbx`.`blacklist_beforeInsert`
	BEFORE INSERT ON `blacklist`
    FOR EACH ROW
BEGIN
	CALL phone_isValid(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 */ ;
/*!50003 SET @saved_cs_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 `pbx`.`blacklist_berforeUpdate`
	BEFORE UPDATE ON `blacklist`
    FOR EACH ROW
BEGIN
	CALL phone_isValid(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 */ ;

--
-- 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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 */;
/*!50003 SET @saved_cs_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 `pbx`.`followme_beforeInsert`
	BEFORE INSERT ON `followme`
    FOR EACH ROW
BEGIN
	CALL pbx.phone_isValid(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 */ ;
/*!50003 SET @saved_cs_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 `pbx`.`followme_beforeUpdate`
	BEFORE UPDATE ON `followme`
    FOR EACH ROW
BEGIN
	CALL pbx.phone_isValid(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 */ ;

--
-- 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=InnoDBDEFAULT 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Queues';
/*!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 `pbx`.`queue_beforeInsert`
	BEFORE INSERT ON `queue`
    FOR EACH ROW
BEGIN
	CALL queue_isValid(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  = 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 `pbx`.`queue_beforeUpdate`
	BEFORE UPDATE ON `queue`
    FOR EACH ROW
BEGIN
	CALL queue_isValid(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 */ ;

--
-- 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`queuePhone_beforeInsert`
	BEFORE INSERT ON `queuePhone`
    FOR EACH ROW
BEGIN
	CALL phone_isValid(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 */ ;
/*!50003 SET @saved_cs_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 `pbx`.`queuePhone_beforeUpdate`
	BEFORE UPDATE ON `queuePhone`
    FOR EACH ROW
BEGIN
	CALL phone_isValid(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 */ ;

--
-- 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=InnoDBDEFAULT 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' COMMENT 'The user id',
  `extension` varchar(128) CHARACTER SET utf8 NOT NULL COMMENT 'The softphone extension',
  `md5Secret` varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'MD5 hash of extension and password',
  `secret` varchar(80) CHARACTER SET utf8 DEFAULT NULL COMMENT 'Deprecated',
  `caller_id` varchar(80) CHARACTER SET utf8 DEFAULT NULL COMMENT 'Deprecated',
  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 */;
/*!50003 SET @saved_cs_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 `pbx`.`sip_beforeInsert`
	BEFORE INSERT ON `sip`
    FOR EACH ROW
BEGIN
	CALL sip_isValid(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 */ ;
/*!50003 SET @saved_cs_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 `sip_afterInsert`
	AFTER INSERT ON `sip`
    FOR EACH ROW
BEGIN
	INSERT INTO sipReg
		SET userId = NEW.user_id;

    UPDATE account.user
		SET sync = FALSE
        WHERE id = 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 */ ;
/*!50003 SET @saved_cs_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 `pbx`.`sip_beforeUpdate`
	BEFORE UPDATE ON `sip`
    FOR EACH ROW
BEGIN
	CALL sip_isValid(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 */ ;
/*!50003 SET @saved_cs_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 `pbx`.`sip_afterUpdate`
	AFTER UPDATE ON `sip`
    FOR EACH ROW
BEGIN
	IF !(OLD.extension <=> NEW.extension) THEN
		UPDATE account.user
			SET sync = FALSE
			WHERE id = NEW.user_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 */ ;

--
-- 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 `md5secret`,
 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 `transport`,
 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=InnoDBDEFAULT 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  = 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 `clientFromPhone`(vPhone VARCHAR(255)) RETURNS int(11)
    DETERMINISTIC
BEGIN
/**
 * @deprecated Use vn.client_getFromPhone()
 */
	RETURN vn.client_getFromPhone(vPhone);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `phone_format` */;
/*!50003 SET @saved_cs_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 `phone_format`(vPhone VARCHAR(255)) RETURNS varchar(255) CHARSET utf8
    DETERMINISTIC
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 */ ;
/*!50003 DROP PROCEDURE IF EXISTS `phone_isValid` */;
/*!50003 SET @saved_cs_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 `phone_isValid`(vPhone VARCHAR(255))
BEGIN
/**
 * Check if an phone has the correct format and
 * throws an exception if it hasn't.
 *
 * @param vPhone The phone number
 */
	DECLARE vIsValid BOOL;

	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 format is invalid';
	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 `queue_isValid` */;
/*!50003 SET @saved_cs_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 `queue_isValid`(vQueue VARCHAR(255))
    DETERMINISTIC
BEGIN
/**
 * Check if an queue has the correct format and
 * throws an exception if it hasn't.
 *
 * @param vQueue The queue number
 */
	DECLARE vIsValid BOOL;

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

	IF NOT vIsValid THEN
		SIGNAL SQLSTATE '45000'
			SET MESSAGE_TEXT = 'Queue format is invalid';
	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 `sip_isValid` */;
/*!50003 SET @saved_cs_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 `sip_isValid`(vExtension VARCHAR(255))
    DETERMINISTIC
BEGIN
/**
 * Check if an extension has the correct format and
 * throws an exception if it hasn't.
 *
 * @param vExtension The extension
 */
	DECLARE vIsValid BOOL;

	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 format is invalid';
	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 `sip_setPassword` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `sip_setPassword`(
	vUser VARCHAR(255),
    vPassword VARCHAR(255)
)
BEGIN
	UPDATE sip SET
		md5Secret = MD5(CONCAT(extension, ':asterisk:', vPassword))
        WHERE user_id = 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 */ ;

--
-- 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 `townKk` (`town_id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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 `vn`.`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`),
  KEY `business_labour_payroll_cod_categoria_idx` (`cod_categoria`),
  KEY `business_labour_payroll_cod_contrato` (`cod_contrato`),
  CONSTRAINT `business_labour_payroll_cod_categoria` FOREIGN KEY (`cod_categoria`) REFERENCES `vn2008`.`payroll_categorias` (`codcategoria`) ON UPDATE CASCADE,
  CONSTRAINT `business_labour_payroll_cod_contrato` FOREIGN KEY (`cod_contrato`) REFERENCES `vn2008`.`payroll_contratos` (`CodContrato`) ON UPDATE CASCADE,
  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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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,
  `isPartial` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`calendar_labour_type_id`),
  UNIQUE KEY `hours_labour_hours_labour_id_key` (`calendar_labour_type_id`)
) ENGINE=InnoDBDEFAULT 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',
  `permissionRate` decimal(3,2) DEFAULT NULL,
  `code` varchar(45) DEFAULT NULL,
  `isAllowedToWork` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`calendar_state_id`)
) ENGINE=InnoDBDEFAULT 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=InnoDBDEFAULT CHARSET=utf8;
/*!40101 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=InnoDBDEFAULT 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 DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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`),
  CONSTRAINT `Person_ibfk_1` FOREIGN KEY (`id_trabajador`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `townKk`
--

DROP TABLE IF EXISTS `townKk`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `townKk` (
  `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 `townKk_ibfk_1` FOREIGN KEY (`province_id`) REFERENCES `province` (`province_id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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=InnoDBDEFAULT 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 `vn`.`warehouse` (`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 `workers20190711_FichadasAbril`
--

DROP TABLE IF EXISTS `workers20190711_FichadasAbril`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workers20190711_FichadasAbril` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `person_id` int(11) NOT NULL DEFAULT '0',
  `nif` varchar(15) CHARACTER SET utf8 DEFAULT NULL,
  `Apellidos` varchar(60) CHARACTER SET utf8 NOT NULL,
  `Nombre` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  `Fecha` date DEFAULT NULL,
  `Hora` int(2) DEFAULT NULL,
  `Minuto` int(2) DEFAULT NULL,
  `sumable` double DEFAULT NULL,
  `jornada` decimal(5,2) NOT NULL DEFAULT '8.00',
  PRIMARY KEY (`id`)
) 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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 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 inboundPick ou ON ou.outboundFk = o.id
		SET o.lack = o.lack + ou.quantity,
			o.isSync = FALSE
		WHERE ou.inboundFk = OLD.id;

	DELETE FROM inboundPick
		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 `inboundPick`
--

DROP TABLE IF EXISTS `inboundPick`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `inboundPick` (
  `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=InnoDBDEFAULT 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 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 inboundPick ou ON ou.inboundFk = i.id
		SET i.available = i.available + ou.quantity,
			i.isSync = FALSE
		WHERE ou.outboundFk = OLD.id;

	DELETE FROM inboundPick
		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_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 `log_clean` ON SCHEDULE EVERY 1 DAY STARTS '2019-06-17 05:00:00' ON COMPLETION PRESERVE ENABLE DO CALL log_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 `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 DISABLE 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 `inbound_addPick` */;
/*!50003 SET @saved_cs_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_addPick`(
	vSelf INT,
    vOutboundFk INT,
    vQuantity INT
)
BEGIN
	INSERT INTO inboundPick
		SET
			inboundFk = vSelf,
			outboundFk = vOutboundFk,
			quantity = vQuantity
		ON DUPLICATE KEY UPDATE
			quantity = quantity + vQuantity;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_removePick` */;
/*!50003 SET @saved_cs_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_removePick`(
	vSelf INT,
    vOutboundFk INT,
    vQuantity INT,
    vTotalQuantity INT
)
BEGIN
	IF vQuantity < vTotalQuantity THEN
		UPDATE inboundPick
			SET quantity = quantity - vQuantity
			WHERE inboundFk = vSelf
				AND outboundFk = vOutboundFk;
	ELSE
		DELETE FROM inboundPick
			WHERE inboundFk = vSelf
				AND outboundFk = vOutboundFk;
	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_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 vSupplied INT)
BEGIN
/**
 * Disassociates inbound picks after the given date until the
 * demanded quantity is satisfied.
 *
 * @param vSelf The inbound reference
 * @param vRequested The requested quantity
 * @param vDate The starting date for the associated outbounds
 * @param vSupplied The supplied quantity
 */
	DECLARE vOutboundFk INT;
	DECLARE vPickQuantity INT;
	DECLARE vPickGranted INT;
	DECLARE vDone BOOL;

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

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;
        
	SET vSupplied = 0;

	OPEN vPicks;

	myLoop: LOOP
		SET vDone = FALSE;
		FETCH vPicks INTO vOutboundFk, vPickQuantity;

		IF vDone THEN
			LEAVE myLoop;
		END IF;

		SET vPickGranted = LEAST(vRequested - vSupplied, vPickQuantity);
		SET vSupplied = vSupplied + vPickGranted;
		CALL inbound_removePick(vSelf, vOutboundFk, vPickGranted, vPickQuantity);
		
		UPDATE outbound
			SET isSync = FALSE,
				lack = lack + vPickGranted
			WHERE id = vOutboundFk;

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

	CLOSE vPicks;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 vSupplied INT;
	DECLARE vSuppliedFromRequest INT;
	DECLARE vOutboundFk INT;
	DECLARE vLack INT;
	DECLARE vHasPicks BOOL;
	DECLARE vDone BOOL;

	DECLARE vOutbounds CURSOR FOR
		SELECT id, lack, lack < quantity
			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;
	END IF;

	OPEN vOutbounds;

	myLoop: LOOP
		SET vDone = FALSE;
		FETCH vOutbounds INTO vOutboundFk, vLack, vHasPicks;

		IF vDone THEN
			LEAVE myLoop;
		END IF;

		SET vSupplied = LEAST(vAvailable, vLack);
        
        IF vSupplied > 0 THEN
			SET vAvailable = vAvailable - vSupplied;
			UPDATE outbound
				SET lack = lack - vSupplied
				WHERE id = vOutboundFk;
		END IF;

		IF vHasPicks AND vAvailable > 0 THEN
			CALL outbound_requestQuantity(vOutboundFk, vAvailable, vDated, vSuppliedFromRequest);
			SET vSupplied = vSupplied + vSuppliedFromRequest;
			SET vAvailable = vAvailable - vSuppliedFromRequest;
		END IF;
        
        IF vSupplied > 0 THEN
			CALL inbound_addPick(vSelf, vOutboundFk, vSupplied);
		END IF;

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

	CLOSE vOutbounds;

	UPDATE inbound
		SET isSync = TRUE,
			available = vAvailable
		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`(IN `vTableName` VARCHAR(255), IN `vNewId` VARCHAR(255), IN `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_add_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 `log_add_beta`(IN `vTableName` VARCHAR(255), IN `vNewId` VARCHAR(255), IN `vOldId` VARCHAR(255))
proc: BEGIN
	-- XXX: Disabled while testing
	DECLARE vLanded DATE;
    DECLARE vWarehouseFk INT;
    DECLARE vBuyerFk INT;
    DECLARE vEntryFk INT;
    DECLARE vItemFk INT;
    DECLARE vItemName VARCHAR(50);
    
    -- 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;
    
    IF vTableName = 'buy' THEN
    
		SELECT IFNULL(tr.landed,'2000-01-01') 
			INTO vLanded
			FROM vn.travel tr
				JOIN vn.entry e ON e.travelFk = tr.id
                JOIN vn.buy b ON b.entryFk = e.id
                JOIN vn.warehouse w ON w.id = tr.warehouseInFk
                WHERE b.id = vNewId
					AND w.isBuyerToBeEmailed;
    
		IF vLanded = CURDATE() THEN
        
			SELECT it.workerFk, b.entryFk, i.id, i.longName
				INTO vBuyerFk, vEntryFk, vItemFk, vItemName
				FROM vn.itemType it
					JOIN vn.item i ON i.typeFk = it.id
					JOIN vn.buy b ON b.itemFk = i.id
                WHERE b.id = vNewId;
                
			CALL vn.mail_insert(CONCAT(account.userGetNameFromId(vBuyerFk),'@verdnatura.es'),
								CONCAT(account.myUserGetName(),'@verdnatura.es'),
                                CONCAT('E-',vEntryFk,' Se ha modificado item ', vItemFk, ' ',vItemName),
                                'Este email se ha generado automáticamente');
           
        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 `log_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 `log_clean`()
BEGIN
	DELETE FROM inbound WHERE dated = vn.getInventoryDate();
	DELETE FROM outbound WHERE dated = vn.getInventoryDate();
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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.`inboundPick`;
	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 20;
	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.shipment >= vn.getInventoryDate()
				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 vHasPendingSync BOOL;
	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

	REPEAT
		OPEN cInbound;
		SET vHasPendingSync = FALSE;

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

			IF vDone THEN
				LEAVE inboundLoop;
			END IF;

			START TRANSACTION;
			CALL inbound_sync(vInboundFk);
			COMMIT;

			SET vHasPendingSync = TRUE;
		END LOOP;

		CLOSE cInbound;
	UNTIL !vHasPendingSync END REPEAT;

	-- Attaches desync outbounds

	REPEAT
		OPEN cOutbound;
		SET vHasPendingSync = FALSE;

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

			IF vDone THEN
				LEAVE outboundLoop;
			END IF;

			START TRANSACTION;
			CALL outbound_sync(vOutboundFk);
			COMMIT;

			SET vHasPendingSync = TRUE;
		END LOOP;

		CLOSE cOutbound;
	UNTIL !vHasPendingSync 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 `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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` 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 vSupplied INT)
BEGIN
/**
 * Disassociates outbound picks after the given date until the
 * demanded quantity is satisfied.
 *
 * @param vSelf The outbound reference
 * @param vRequested The requested quantity
 * @param vDate The starting date for the associated inbounds
 * @param vSupplied The supplied quantity
 */
	DECLARE vInboundFk INT;
	DECLARE vPickQuantity INT;
	DECLARE vPickGranted INT;
	DECLARE vDone BOOL;

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

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	SET vSupplied = 0;

	OPEN vPicks;

	myLoop: LOOP
		SET vDone = FALSE;
		FETCH vPicks INTO vInboundFk, vPickQuantity;

		IF vDone THEN
			LEAVE myLoop;
		END IF;

		SET vPickGranted = LEAST(vRequested - vSupplied, vPickQuantity);
		SET vSupplied = vSupplied + vPickGranted;
		CALL inbound_removePick(vInboundFk, vSelf, vPickGranted, vPickQuantity);
		
		UPDATE inbound
			SET isSync = FALSE,
				available = available + vPickGranted
			WHERE id = vInboundFk;

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

	CLOSE vPicks;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 vSupplied INT;
	DECLARE vSuppliedFromRequest INT;
	DECLARE vInboundFk INT;
	DECLARE vAvailable INT;
	DECLARE vHasPicks BOOL;
	DECLARE vDone BOOL;

	DECLARE vInbounds CURSOR FOR
		SELECT id, available, available < quantity
			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 vInbounds;

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

		IF vDone THEN
			LEAVE myLoop;
		END IF;

		SET vSupplied = LEAST(vLack, vAvailable);

		IF vSupplied > 0 THEN
			SET vLack = vLack - vSupplied;
			UPDATE inbound
				SET available = available - vSupplied
				WHERE id = vInboundFk;
		END IF;

		IF vHasPicks AND vLack > 0 THEN
			CALL inbound_requestQuantity(vInboundFk, vLack, vDated, vSuppliedFromRequest);
			SET vSupplied = vSupplied + vSuppliedFromRequest;
			SET vLack = vLack - vSuppliedFromRequest;
		END IF;

		IF vSupplied > 0 THEN
			CALL inbound_addPick(vInboundFk, vSelf, vSupplied);
		END IF;

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

	CLOSE vInbounds;

	UPDATE outbound
		SET isSync = TRUE,
			lack = vLack
		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=InnoDBDEFAULT 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=InnoDBDEFAULT 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 `crypt` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `crypt`(vText VARCHAR(255), vKey VARCHAR(255)) RETURNS varchar(255) CHARSET utf8
    READS SQL DATA
BEGIN

	DECLARE vResult VARCHAR(255);
    
    CALL vn.crypt(vText, vKey, vResult);

	RETURN 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 `cryptOff` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `cryptOff`(vText VARCHAR(255), vKey VARCHAR(255)) RETURNS varchar(255) CHARSET utf8
    READS SQL DATA
BEGIN

	DECLARE vResult VARCHAR(255);
    
    CALL vn.cryptOff(vText, vKey, vResult);

	RETURN 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 `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 `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              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `firstDayOfYear`(vDate DATE) RETURNS date
    NO SQL
    DETERMINISTIC
BEGIN
/**
 * Returns the date formatted to the first day of year.
 *
 * @param vDate The date to format
 * @return The formatted date
 */
	RETURN DATE_FORMAT(vDate, '%Y-01-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 `compareObjects` */;
/*!50003 SET @saved_cs_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 `compareObjects`(vChain VARCHAR(45),vCompare VARCHAR(45))
    READS SQL DATA
BEGIN
/**
 * Devuelve un listado de todos los procedimientos, funciones
 * eventos, disparadores y vistas que estan incluidos en las dos cadenadas dadas.
 *
 * Es util para buscar una columna de una tabla en concreto
 * @param vChain Cadena a buscar
 * @param vCompare Cadena a buscar y comparar los resultados con la primera cadena
 * @select Listado de objetos
 */
	SET vChain = CONCAT('%', vChain, '%');
    SET vCompare = CONCAT('%', vCompare, '%');
	SELECT * FROM 
	(
		SELECT t1.* 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
		) t1
        JOIN (
			SELECT
					`db`,
					`name`,
					`type`,
					`body`,
					`created`,
					`modified`
				FROM `mysql`.`proc`
				WHERE `body` LIKE vCompare COLLATE utf8_general_ci
			UNION ALL
			SELECT
					`db`,
					`name`,
					'EVENT',
					`body_utf8`,
					`created`,
					`modified`
				FROM `mysql`.`event`
				WHERE `body_utf8` LIKE vCompare 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 vCompare COLLATE utf8_general_ci
			UNION ALL
			SELECT
					`TABLE_SCHEMA`,
					`TABLE_NAME`,
					'VIEW',
					`VIEW_DEFINITION`,
					NULL,
					NULL 
				FROM `information_schema`.`VIEWS`
				WHERE `VIEW_DEFINITION` LIKE vCompare COLLATE utf8_general_ci) t2 ON t2.name = t1.name
		ORDER BY t1.`db`, t1.`name`
	) 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 `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 `proc_changedPrivs` */;
/*!50003 SET @saved_cs_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 `proc_changedPrivs`()
BEGIN
	SELECT s.*
		FROM proc_privs s
			LEFT JOIN mysql.procs_priv p
				ON p.`Host` = s.`Host`
					AND p.`Host` = s.`Host`
					AND p.`Db` = s.`Db`
					AND p.`User` = s.`User`
					AND p.`Routine_name` = s.`Routine_name`
					AND p.`Routine_type` = s.`Routine_type`
		WHERE p.Proc_priv 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 `proc_restorePrivs` */;
/*!50003 SET @saved_cs_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 `proc_restorePrivs`()
BEGIN
/**
 * Restores the privileges saved by proc_savePrivs().
 * This procedure should be called after modifying a procedure,
 * for more info see proc_savePrivs().
 */
	INSERT IGNORE INTO mysql.procs_priv
		SELECT * FROM proc_privs;

	FLUSH PRIVILEGES;
	DROP TEMPORARY TABLE proc_privs;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_savePrivs` */;
/*!50003 SET @saved_cs_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 `proc_savePrivs`()
BEGIN
/**
 * Saves routine privileges, used to simplify the task of keeping
 * routine privileges when they are modified due to the lack of
 * CREATE OR REPLACE [PROCEDURE|FUNCTION].
 * This procedure should be called before modifying a routine, to
 * restore the saved privileges use proc_restorePrivs().
 */
	CREATE TEMPORARY TABLE proc_privs
		ENGINE = MEMORY
		SELECT * FROM mysql.procs_priv;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!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`;

--
-- 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 `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `vn`.`XDiario_beforeInsert` 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 */ ;

--
-- 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`,
 1 AS `code`*/;
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 `client` (`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 `address`
--

DROP TABLE IF EXISTS `address`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `address` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `clientFk` int(11) NOT NULL DEFAULT '0',
  `warehouseFk` smallint(6) unsigned DEFAULT '1',
  `street` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `city` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `provinceFk` smallint(5) unsigned DEFAULT NULL,
  `postalCode` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `phone` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `mobile` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `nickname` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
  `isDefaultAddress` tinyint(1) NOT NULL DEFAULT '0',
  `agencyModeFk` int(11) NOT NULL DEFAULT '2',
  `notes` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `hasInsurance` tinyint(1) NOT NULL DEFAULT '0',
  `porte` double DEFAULT NULL,
  `isActive` tinyint(4) NOT NULL DEFAULT '1',
  `postcodeOLD` int(11) unsigned DEFAULT NULL,
  `longitude` decimal(11,7) DEFAULT NULL,
  `latitude` decimal(11,7) DEFAULT NULL,
  `codPosOld` char(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `isEqualizated` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `Id_Agencia` (`agencyModeFk`),
  KEY `Id_cliente` (`clientFk`),
  KEY `warehouse_id` (`warehouseFk`),
  KEY `province_id` (`provinceFk`),
  KEY `telefono` (`phone`),
  KEY `movil` (`mobile`),
  KEY `CODPOSTAL` (`postalCode`),
  CONSTRAINT `address_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `address_ibfk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `address_ibfk_3` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `address_ibfk_4` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `vn`.`address_beforeInsert`
	BEFORE INSERT ON `vn`.`address` FOR EACH ROW
BEGIN
	DECLARE vIsEqualizated BOOL;

	CALL pbx.phone_isValid(NEW.phone);
	CALL pbx.phone_isValid(NEW.mobile);

	IF NEW.isEqualizated IS NULL THEN
		SELECT isEqualizated 
				INTO vIsEqualizated
			FROM client
			WHERE id = NEW.clientFk;
		
		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 `vn`.`address_beforeUpdate`
	BEFORE UPDATE ON `vn`.`address` FOR EACH ROW
BEGIN
	CALL pbx.phone_isValid(NEW.phone);
	CALL pbx.phone_isValid(NEW.mobile);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `vn`.`address_afterUpdate`
	AFTER UPDATE ON `address` 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 address 
						WHERE clientFk = NEW.clientFk
				) t1
			) > 1
		THEN 
			UPDATE client 
				SET hasToInvoiceByAddress = TRUE
				WHERE id = NEW.clientFk;
		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 `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 `address` (`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 `addressObservation`
--

DROP TABLE IF EXISTS `addressObservation`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `addressObservation` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `addressFk` int(11) NOT NULL,
  `observationTypeFk` tinyint(3) unsigned NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `Id_Consigna` (`addressFk`,`observationTypeFk`),
  KEY `addressObservationFgn_idx` (`observationTypeFk`),
  CONSTRAINT `addressFgn` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `addressObservationFgn` FOREIGN KEY (`observationTypeFk`) REFERENCES `observationType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Observaciones de los consignatarios';
/*!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` (
  `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `warehouseFk` smallint(5) unsigned DEFAULT NULL COMMENT 'A nulo si se puede enrutar desde todos los almacenes',
  `isVolumetric` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'Si el calculo del porte se hacer por volumen',
  `bankFk` int(11) NOT NULL DEFAULT '8' COMMENT 'para realizar los reembolsos',
  `warehouseAliasFk` smallint(5) unsigned DEFAULT NULL,
  `isOwn` tinyint(1) NOT NULL DEFAULT '0',
  `labelZone` tinyint(4) NOT NULL DEFAULT '0',
  `workCenterFk` int(11) DEFAULT NULL,
  `supplierFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `warehouse_id` (`warehouseFk`),
  KEY `Id_Banco` (`bankFk`),
  KEY `agencias_alias_idx` (`warehouseAliasFk`),
  KEY `agency_ibfk_3_idx` (`workCenterFk`),
  KEY `agency_ibfk_4_idx` (`supplierFk`),
  CONSTRAINT `agency_ibfk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `agency_ibfk_2` FOREIGN KEY (`bankFk`) REFERENCES `bank` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `agency_ibfk_3` FOREIGN KEY (`workCenterFk`) REFERENCES `workCenter` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `agency_ibfk_4` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `vn`.`agency_afterInsert` AFTER INSERT ON `vn`.`agency` FOR EACH ROW
BEGIN
	INSERT INTO agencyMode(name,agencyFk) VALUES(NEW.name,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 */ ;

--
-- Table structure for table `agencyMode`
--

DROP TABLE IF EXISTS `agencyMode`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agencyMode` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `description` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `deliveryMethodFk` int(11) DEFAULT '0',
  `m3` double DEFAULT '0',
  `cod71` tinyint(3) unsigned DEFAULT '0',
  `web` smallint(1) unsigned zerofill NOT NULL DEFAULT '0',
  `agencyFk` smallint(6) NOT NULL,
  `agencyServiceFk` tinyint(4) NOT NULL DEFAULT '1',
  `inflation` decimal(5,2) NOT NULL DEFAULT '0.00' COMMENT 'Este valor se utiliza para aumentar el valor del componente porte.',
  `isVolumetric` tinyint(1) NOT NULL DEFAULT '0',
  `reportMail` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `showAgencyName` tinyint(1) DEFAULT '1' COMMENT 'obsoleta',
  `isActive` tinyint(1) NOT NULL DEFAULT '1',
  `isExternalAgency` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'obsoleta',
  `flag` blob COMMENT 'obsoleta',
  `code` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `Agencias` (`name`),
  KEY `Vista` (`deliveryMethodFk`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 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;

--
-- 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 `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=InnoDBDEFAULT 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 `ticket` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDBDEFAULT 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 `country` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `bank`
--

DROP TABLE IF EXISTS `bank`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bank` (
  `id` int(11) NOT NULL DEFAULT '0',
  `bank` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `account` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `cash` smallint(6) NOT NULL DEFAULT '0',
  `warehouseFk` smallint(5) unsigned NOT NULL DEFAULT '1',
  `entityFk` int(10) unsigned NOT NULL,
  `isActive` tinyint(4) NOT NULL DEFAULT '1',
  `currencyFk` tinyint(3) unsigned DEFAULT '1',
  `code` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `BancosBanco` (`bank`),
  KEY `fk_Bancos_entity1_idx` (`entityFk`),
  KEY `foreignkey1_idx` (`cash`),
  KEY `Bancoscurrency_idx` (`currencyFk`),
  CONSTRAINT `Bancoscurrency` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `foreignkey1` FOREIGN KEY (`cash`) REFERENCES `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 `bankEntity`
--

DROP TABLE IF EXISTS `bankEntity`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bankEntity` (
  `countryFk` mediumint(8) unsigned NOT NULL DEFAULT '1',
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `bic` varchar(11) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `bic_UNIQUE` (`bic`),
  KEY `fg_entity1_idx` (`countryFk`),
  CONSTRAINT `fg_entity1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Entidades bancarias	';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `bionicConfig`
--

DROP TABLE IF EXISTS `bionicConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bionicConfig` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `generalInflationCoeficient` double(10,2) NOT NULL,
  `minimumDensityVolumetricWeight` double(10,2) NOT NULL,
  `verdnaturaVolumeBox` int(11) NOT NULL,
  `itemCarryBox` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `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 `bookingPlannerIdx3` (`taxAreaFk`,`taxClassFk`,`countryFk`),
  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 `taxClass` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `bookingPlanner_ibfk_3` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON DELETE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `botanicExport`
--

DROP TABLE IF EXISTS `botanicExport`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `botanicExport` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `ediGenusFk` mediumint(8) unsigned NOT NULL,
  `ediSpecieFk` mediumint(8) unsigned DEFAULT NULL,
  `countryFk` 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 (`id`),
  KEY `Id_Paises` (`countryFk`),
  KEY `botanicExport_ibfk_2_idx` (`ediGenusFk`),
  KEY `botanicExport_ibfk_3_idx` (`ediSpecieFk`),
  CONSTRAINT `botanicExport_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Especifica los generos y especies prohibidos en paises';
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_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 `vn`.`botanicExport_beforeInsert` BEFORE INSERT ON `botanicExport` FOR EACH ROW
BEGIN
	IF (SELECT botanicExport_isUpdatable (NEW.ediGenusFk, NEW.ediSpecieFk, NEW.countryFk, 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `buy`
--

DROP TABLE IF EXISTS `buy`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `buy` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `entryFk` int(11) NOT NULL DEFAULT '0',
  `itemFk` int(11) NOT NULL DEFAULT '90',
  `quantity` int(11) DEFAULT '0',
  `dispatched` int(11) NOT NULL DEFAULT '0',
  `buyingValue` decimal(10,3) DEFAULT '0.000',
  `freightValue` decimal(10,3) DEFAULT '0.000',
  `isIgnored` tinyint(1) NOT NULL DEFAULT '0',
  `stickers` int(11) DEFAULT '0',
  `packing` int(11) DEFAULT '0',
  `grouping` smallint(5) unsigned NOT NULL DEFAULT '1',
  `groupingMode` tinyint(4) NOT NULL DEFAULT '0' COMMENT '0=sin obligar 1=groping 2=packing',
  `containerFk` smallint(5) unsigned DEFAULT NULL,
  `comissionValue` decimal(10,3) DEFAULT '0.000',
  `packageValue` decimal(10,3) DEFAULT '0.000',
  `location` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `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,
  `printedStickers` int(11) DEFAULT '0',
  `workerFk` int(11) DEFAULT '0',
  `isChecked` tinyint(1) NOT NULL DEFAULT '0',
  `isPickedOff` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Esta mercancia no va a la zona de picking.',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `__cm2` int(10) unsigned NOT NULL DEFAULT '0',
  `ektFk` int(11) DEFAULT NULL,
  `weight` decimal(10,2) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `CompresId_Trabajador` (`workerFk`),
  KEY `Id_Cubo` (`packageFk`),
  KEY `Id_Entrada` (`entryFk`),
  KEY `container_id` (`containerFk`),
  KEY `buy_edi_id` (`ektFk`),
  KEY `itemFk_entryFk` (`itemFk`,`entryFk`),
  CONSTRAINT `buy_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `buy_ibfk_2` FOREIGN KEY (`packageFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `buy_id` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `buy_itemfk` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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  = utf8 */ ;
/*!50003 SET character_set_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 `buy_beforeInsert`
	BEFORE INSERT ON `buy`
    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 buy_checkGrouping(NEW.`grouping`);

	SELECT t.warehouseInFk, t.landed INTO vWarehouse, vLanding
		FROM entry e 
			JOIN travel t ON t.id = e.travelFk
		WHERE e.id = NEW.entryFk;

	SELECT b.`grouping`, b.groupingMode INTO vGrouping, vGroupingMode
		FROM buy b
			JOIN entry e ON e.id = b.entryFk
			JOIN travel t ON t.id = e.travelFk
		WHERE t.landed <= vLanding
			AND b.itemFk = NEW.itemFk
			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.groupingMode IS NULL THEN
		SET NEW.groupingMode = 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  = utf8 */ ;
/*!50003 SET character_set_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 `buy_afterInsert`
	AFTER INSERT ON `buy`
    FOR EACH ROW
trig: BEGIN
	CALL stock.log_add('buy', NEW.id, NULL);

	IF @isModeInventory THEN
		LEAVE trig;
	END IF;

    CALL buy_afterUpsert(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 `buy_beforeUpdate`
	BEFORE UPDATE ON `buy`
    FOR EACH ROW
BEGIN 
    IF !(NEW.`grouping` <=> OLD.`grouping`) THEN
		CALL 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  = utf8 */ ;
/*!50003 SET character_set_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 `buy_afterUpdate`
	AFTER UPDATE ON `buy`
    FOR EACH ROW
trig: BEGIN
	IF !(NEW.id <=> OLD.id)
    OR !(NEW.entryFk <=> OLD.entryFk)
    OR !(NEW.itemFk <=> OLD.itemFk)
    OR !(NEW.quantity <=> OLD.quantity)
    OR !(NEW.created <=> OLD.created) THEN
		CALL stock.log_add('buy', NEW.id, OLD.id);
	END IF;
	
	IF @isModeInventory THEN
		LEAVE trig;
	END IF;

    CALL buy_afterUpsert(NEW.id);

	IF (!(NEW.weight <=> OLD.weight) OR !(NEW.packing <=> OLD.packing) OR !(NEW.packageFk <=> OLD.packageFk)) AND NEW.weight THEN
		UPDATE item
			SET density = NEW.weight / (item_getVolume(NEW.itemFk, NEW.packageFk) / 1000000)
			WHERE id = NEW.itemFk;
	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 `buy_beforeDelete`
	BEFORE DELETE ON `buy`
    FOR EACH ROW
BEGIN 
	IF OLD.printedStickers > 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 `buy`
    FOR EACH ROW
BEGIN 
	CALL stock.log_add('buy', NULL, 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 `buyMark`
--

DROP TABLE IF EXISTS `buyMark`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `buyMark` (
  `id` int(11) NOT NULL,
  `comment` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `mark` tinyint(1) DEFAULT NULL,
  `odbcDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  CONSTRAINT `Compres_mark_ibfk_1` FOREIGN KEY (`id`) REFERENCES `buy` (`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 `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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Grupos de clientes';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `chatConfig`
--

DROP TABLE IF EXISTS `chatConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `chatConfig` (
  `id` int(11) 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,
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `claim`
--

DROP TABLE IF EXISTS `claim`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `claim` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `ticketCreated` date NOT NULL,
  `claimDepartmentFk` tinyint(3) unsigned DEFAULT NULL,
  `claimStateFk` int(10) unsigned NOT NULL DEFAULT '1',
  `observation` text COLLATE utf8_unicode_ci,
  `clientFk` int(11) NOT NULL,
  `workerFk` int(11) NOT NULL,
  `responsibility` int(1) unsigned NOT NULL DEFAULT '3',
  `isChargedToMana` tinyint(1) NOT NULL DEFAULT '0',
  `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `ticketFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `cl_dep_id` (`claimDepartmentFk`),
  KEY `cl_est_id` (`claimStateFk`),
  KEY `Id_Cliente` (`clientFk`),
  KEY `Id_Trabajador` (`workerFk`),
  KEY `cl_main_ticketFk_idx` (`ticketFk`),
  CONSTRAINT `cl_main_ticketFk` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `claim_ibfk_3` FOREIGN KEY (`claimStateFk`) REFERENCES `claimState` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `claim_ibfk_4` FOREIGN KEY (`claimDepartmentFk`) REFERENCES `vn2008`.`cl_dep` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `claim_ibfk_5` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Reclamaciones, tabla principal';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `claimBeginning`
--

DROP TABLE IF EXISTS `claimBeginning`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `claimBeginning` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `claimFk` int(10) unsigned NOT NULL,
  `saleFk` int(11) DEFAULT NULL,
  `claimComplaintFk` int(10) unsigned NOT NULL DEFAULT '1',
  `claimRequestFk` int(1) unsigned NOT NULL DEFAULT '1',
  `quantity` double DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `Id_Movimiento` (`saleFk`),
  KEY `cl_main_id` (`claimFk`),
  CONSTRAINT `claimBeginning_ibfk_7` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `claimBeginning_ibfk_8` FOREIGN KEY (`claimFk`) REFERENCES `claim` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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 `vn`.`claimBeginning_afterInsert` 
    AFTER INSERT ON `claimBeginning` 
    FOR EACH ROW
BEGIN
	DECLARE vTicket INT;

	SELECT ticketFk INTO vTicket
		FROM sale
		WHERE id = NEW.saleFk;

	UPDATE claim 
		SET ticketFk = vTicket
		WHERE id = NEW.claimFk;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `claimDestination`
--

DROP TABLE IF EXISTS `claimDestination`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `claimDestination` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `description` 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 `address` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Solucion ofrecida a la reclamación';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `claimDevelopment`
--

DROP TABLE IF EXISTS `claimDevelopment`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `claimDevelopment` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `claimFk` int(10) unsigned NOT NULL,
  `claimResponsibleFk` int(10) unsigned NOT NULL DEFAULT '1',
  `workerFk` int(11) DEFAULT NULL,
  `claimReasonFk` int(10) unsigned NOT NULL DEFAULT '1',
  `claimResultFk` int(10) unsigned NOT NULL DEFAULT '1',
  `claimRedeliveryFk` tinyint(3) unsigned NOT NULL DEFAULT '1',
  `claimDestinationFk` tinyint(3) unsigned NOT NULL DEFAULT '2',
  PRIMARY KEY (`id`),
  KEY `cl_main_id` (`claimFk`),
  KEY `cl_res_id` (`claimResponsibleFk`),
  KEY `Id_Trabajador` (`workerFk`),
  KEY `cl_mot_id` (`claimReasonFk`),
  KEY `cl_con_id` (`claimResultFk`),
  KEY `cl_dev` (`claimRedeliveryFk`),
  KEY `cl_sol` (`claimDestinationFk`),
  CONSTRAINT `claimDevelopment_ibfk_10` FOREIGN KEY (`claimFk`) REFERENCES `claim` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `claimDevelopment_ibfk_11` FOREIGN KEY (`claimRedeliveryFk`) REFERENCES `claimRedelivery` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `claimDevelopment_ibfk_12` FOREIGN KEY (`claimDestinationFk`) REFERENCES `claimDestination` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `claimDevelopment_ibfk_6` FOREIGN KEY (`claimResponsibleFk`) REFERENCES `claimResponsible` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `claimDevelopment_ibfk_7` FOREIGN KEY (`claimReasonFk`) REFERENCES `claimReason` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `claimDevelopment_ibfk_8` FOREIGN KEY (`claimResultFk`) REFERENCES `claimResult` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `claimDevelopment_ibfk_9` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Causas de las reclamaciones';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `claimDms`
--

DROP TABLE IF EXISTS `claimDms`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `claimDms` (
  `claimFk` int(10) unsigned NOT NULL,
  `dmsFk` int(11) NOT NULL,
  PRIMARY KEY (`claimFk`,`dmsFk`),
  KEY `dmsFk_idx` (`dmsFk`),
  CONSTRAINT `claimFk` FOREIGN KEY (`claimFk`) REFERENCES `claim` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `dmsFk` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`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 `claimEnd`
--

DROP TABLE IF EXISTS `claimEnd`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `claimEnd` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `saleFk` int(11) DEFAULT NULL,
  `claimFk` int(10) unsigned NOT NULL,
  `workerFk` int(11) NOT NULL DEFAULT '20',
  `claimDestinationFk` tinyint(4) DEFAULT NULL,
  `isGreuge` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `cl_main_id` (`claimFk`),
  KEY `Id_Trabajador` (`workerFk`),
  KEY `Id_Movimiento` (`saleFk`),
  KEY `cl_sol_id` (`claimDestinationFk`),
  CONSTRAINT `claimEnd_ibfk_1` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `claimEnd_ibfk_3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `claimEnd_ibfk_4` FOREIGN KEY (`claimFk`) REFERENCES `claim` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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 `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 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 `claimOriginFk` FOREIGN KEY (`originFk`) REFERENCES `claim` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `claimUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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;

--
-- Table structure for table `claimReason`
--

DROP TABLE IF EXISTS `claimReason`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `claimReason` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Motivos de las fallos';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `claimRedelivery`
--

DROP TABLE IF EXISTS `claimRedelivery`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `claimRedelivery` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT 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 `claimResponsible`
--

DROP TABLE IF EXISTS `claimResponsible`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `claimResponsible` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `responsability` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'if=1 >sensib >culpa',
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Responsables de las causas';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `claimResult`
--

DROP TABLE IF EXISTS `claimResult`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `claimResult` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Consecuencias de los motivos';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `claimState`
--

DROP TABLE IF EXISTS `claimState`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `claimState` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `description` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `roleFk` int(10) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  KEY `roleFgn_idx` (`roleFk`),
  CONSTRAINT `roleFgn` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Estados posibles de las reclamaciones';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `client`
--

DROP TABLE IF EXISTS `client`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `client` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `discount` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT 'obsoleta (comprobar)',
  `defaultAddressFk` int(11) DEFAULT NULL,
  `street` longtext COLLATE utf8_unicode_ci,
  `fi` varchar(14) COLLATE utf8_unicode_ci DEFAULT NULL,
  `phone` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `fax` varchar(11) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'obsoleta (comprobar)',
  `email` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `cc` varchar(23) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'obsoleta (comprobar)',
  `dueDay` smallint(6) NOT NULL DEFAULT '5',
  `receipt` int(11) DEFAULT '1' COMMENT 'obsoleta',
  `isOfficial` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'obsoleta (comprobar)',
  `isTaxDataChecked` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Deprecated',
  `mobile` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `accountingAccount` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `isEqualizated` tinyint(1) NOT NULL DEFAULT '0',
  `city` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
  `provinceFk` smallint(5) unsigned DEFAULT NULL,
  `postcode` varchar(8) COLLATE utf8_unicode_ci DEFAULT NULL,
  `socialName` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
  `contact` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `wholesaler` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'obsoleta (comprobar)',
  `isReExpedition` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'obsoleta (comprobar)',
  `hasToInvoice` tinyint(1) NOT NULL DEFAULT '1',
  `notes` text COLLATE utf8_unicode_ci COMMENT 'obsoleta (comprobar)',
  `administrativeNotes` text COLLATE utf8_unicode_ci NOT NULL COMMENT 'obsoleta (comprobar)',
  `invoiceCopy` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'obsoleta (comprobar)',
  `hold` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'obsoleta (comprobar)',
  `isFreezed` tinyint(1) NOT NULL DEFAULT '0',
  `salesPersonFk` int(11) DEFAULT NULL,
  `credit` decimal(10,2) NOT NULL DEFAULT '0.00',
  `cyc` double DEFAULT NULL COMMENT 'obsoleta (comprobar)',
  `countryFk` mediumint(8) unsigned NOT NULL DEFAULT '1',
  `isActive` tinyint(1) NOT NULL DEFAULT '1',
  `gestdocFk` int(11) DEFAULT NULL,
  `quality` int(2) DEFAULT '11',
  `payMethodFk` tinyint(3) unsigned NOT NULL DEFAULT '5',
  `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `isToBeMailed` tinyint(1) NOT NULL DEFAULT '1',
  `contactChannelFk` smallint(6) DEFAULT NULL,
  `isVies` tinyint(4) NOT NULL DEFAULT '0',
  `splitHolland` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'obsoleta (comprobar)',
  `sepaFth` tinyint(1) DEFAULT '0' COMMENT 'campo para recibir los escritos de los clientes para el sepa\n\nobsoleta (comprobar)',
  `hasSepaVnl` tinyint(1) DEFAULT '0',
  `coreFth` tinyint(1) DEFAULT '0' COMMENT 'obsoleta (comprobar)',
  `hasCoreVnl` tinyint(1) DEFAULT '0',
  `riskCalculated` date NOT NULL,
  `hasCoreVnh` tinyint(1) DEFAULT '0',
  `isRelevant` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'Define los clientes cuyas ventas hay que tener en cuenta en los calculos estadisticos.',
  `clientTypeFk` int(11) NOT NULL DEFAULT '1',
  `postcodeOld` int(11) unsigned DEFAULT NULL COMMENT 'obsoleta (comprobar)',
  `mailAddress` int(11) DEFAULT NULL,
  `codposOLD` char(5) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'obsoleta (comprobar)',
  `creditInsurance` int(11) DEFAULT NULL,
  `eypbc` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Email\\nYesterday\\nPurchases\\nBy\\nConsigna',
  `hasToInvoiceByAddress` 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`),
  UNIQUE KEY `IF` (`fi`),
  KEY `Id_Trabajador` (`salesPersonFk`),
  KEY `Id_Pais` (`countryFk`),
  KEY `pay_met_id` (`payMethodFk`),
  KEY `canal_nuevo_cliente` (`contactChannelFk`),
  KEY `Cuenta` (`accountingAccount`),
  KEY `province_id` (`provinceFk`),
  KEY `default_address` (`defaultAddressFk`),
  KEY `Telefono` (`phone`),
  KEY `movil` (`mobile`),
  KEY `tipos_de_cliente_idx` (`clientTypeFk`),
  KEY `codpos` (`codposOLD`,`postcode`),
  KEY `fk_Clientes_entity_idx` (`bankEntityFk`),
  KEY `typeFk` (`typeFk`),
  CONSTRAINT `canal_nuevo_cliente` FOREIGN KEY (`contactChannelFk`) REFERENCES `contactChannel` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `client_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `client_ibfk_2` FOREIGN KEY (`payMethodFk`) REFERENCES `payMethod` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `client_ibfk_3` FOREIGN KEY (`salesPersonFk`) REFERENCES `worker` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `client_ibfk_4` FOREIGN KEY (`defaultAddressFk`) REFERENCES `address` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `client_ibfk_5` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `tipos_de_cliente` FOREIGN KEY (`clientTypeFk`) REFERENCES `clientType` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `typeFk` FOREIGN KEY (`typeFk`) REFERENCES `clientType` (`code`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`client_beforeInsert`
	BEFORE INSERT ON `client`
	FOR EACH ROW
BEGIN

	CALL pbx.phone_isValid(NEW.phone);
	CALL pbx.phone_isValid(NEW.mobile);
	CALL pbx.phone_isValid(NEW.fax);

	SET NEW.accountingAccount = 4300000000 + 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 `vn`.`client_beforeUpdate`
	BEFORE UPDATE ON `client`
    FOR EACH ROW
BEGIN
	DECLARE vText VARCHAR(255) DEFAULT NULL;
	-- Comprueba que el formato de los teléfonos es válido

	IF !(NEW.phone <=> OLD.phone) THEN
		CALL pbx.phone_isValid(NEW.phone);
	END IF;
    
    IF !(NEW.mobile <=> OLD.mobile) THEN
		CALL pbx.phone_isValid(NEW.mobile);
	END IF;

    IF !(NEW.fax <=> OLD.fax) THEN
		CALL pbx.phone_isValid(NEW.fax);
	END IF;

	IF NEW.payMethodFk = 4 AND NEW.dueDay = 0 THEN
		SET NEW.dueDay = 5;
    END IF;
    
	-- Avisar al comercial si ha llegado la documentación sepa/core

	IF NEW.hasSepaVnl AND !OLD.hasSepaVnl THEN
		SET vText = 'Sepa de VNL';
	END IF;

	IF NEW.hasCoreVnl AND !OLD.hasCoreVnl THEN
		SET vText = 'Core de VNL';
	END IF;

	IF vText IS NOT NULL
    THEN
		INSERT INTO mail(sender, replyTo, `subject`, body) 
			SELECT
					CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'),
                    'administracion@verdnatura.es',
                    CONCAT('Cliente ', NEW.id),
					CONCAT('Recibida la documentación: ', vText)
				FROM worker w
					LEFT JOIN account.user u ON w.userFk = u.id AND u.active
					LEFT JOIN account.account ac ON ac.id = u.id
				WHERE w.id = NEW.salesPersonFk;
	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 `vn`.`client_afterUpdate`
AFTER UPDATE ON `client` 
FOR EACH ROW
BEGIN
    IF !(NEW.defaultAddressFk <=> OLD.defaultAddressFk) THEN
        UPDATE `address` SET isDefaultAddress = 0
            WHERE clientFk = NEW.id;
            
		UPDATE `address` SET isDefaultAddress = 1
            WHERE id = NEW.defaultAddressFk;      
    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 `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 `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `clientChain_fk2` FOREIGN KEY (`chainFk`) REFERENCES `chain` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `clientCredit`
--

DROP TABLE IF EXISTS `clientCredit`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientCredit` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `clientFk` int(11) NOT NULL,
  `amount` double unsigned NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `workerFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `workers_fk_idx` (`workerFk`),
  KEY `credit_ClienteFk` (`clientFk`),
  CONSTRAINT `credit_ClienteFk` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `workers_fk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

DROP TABLE IF EXISTS `clientCreditLimit`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientCreditLimit` (
  `id` int(11) NOT NULL,
  `maxAmount` int(10) unsigned NOT NULL,
  `roleFk` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `clientDms`
--

DROP TABLE IF EXISTS `clientDms`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientDms` (
  `clientFk` int(11) NOT NULL,
  `dmsFk` int(11) NOT NULL,
  PRIMARY KEY (`dmsFk`),
  KEY `gest_doc_id` (`dmsFk`),
  KEY `fk_clientes_gestdoc_1_idx` (`clientFk`),
  CONSTRAINT `clientDms_ibfk_2` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `fk_clientes_gestdoc_3` FOREIGN KEY (`clientFk`) REFERENCES `client` (`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 `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 `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `clientLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `clientManaCache`
--

DROP TABLE IF EXISTS `clientManaCache`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientManaCache` (
  `clientFk` int(11) NOT NULL,
  `mana` decimal(10,0) NOT NULL DEFAULT '0',
  `dated` date NOT NULL,
  PRIMARY KEY (`clientFk`,`dated`),
  KEY `manaCustomerIdx1` (`dated`),
  CONSTRAINT `cliente_fk` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `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;

--
-- Table structure for table `clientObservation`
--

DROP TABLE IF EXISTS `clientObservation`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientObservation` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `clientFk` int(11) NOT NULL,
  `workerFk` int(11) NOT NULL,
  `text` text COLLATE utf8_unicode_ci NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `Id_Trabajador` (`workerFk`),
  KEY `Id_Cliente` (`clientFk`),
  CONSTRAINT `clientObservation_ibfk_1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `clientObservation_ibfk_2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Todas las observaciones referentes a un ticket';
/*!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 `vn`.`clientObservation_AFTER_INSERT` AFTER INSERT ON `clientObservation` FOR EACH ROW
BEGIN
/*	DECLARE vMailSender VARCHAR(90);
	DECLARE vUserName VARCHAR(30);
	DECLARE vUserId INT ;
	
	SELECT u.name, u.id INTO vUserName, vUserId
		FROM account.user u 
			JOIN vn.worker w ON w.userFk = u.id
		WHERE w.id = NEW.workerFk;
	
	SELECT CONCAT(salesPerson.name,  '@verdnatura.es, ',vUserName, '@verdnatura.es') INTO vMailSender
		FROM vn.client c 
			JOIN vn.worker w ON w.id = c.salesPersonFk 
			JOIN account.user salesPerson ON salesPerson.id = w.userFk    
		WHERE c.id = NEW.clientFk 
			AND salesPerson.id <> vUserId;

	IF vMailSender >'' THEN
		INSERT INTO vn.mail SET
		`sender` = vMailSender,
		`replyTo` = CONCAT(vUserName, '@verdnatura.es'),
		`subject` = CONCAT ('Nota añadida al cliente ',  NEW.clientFk) ,
		`body` = CONCAT(vUserName, ' ha añadido la siguiente nota: ', NEW.`text`);
	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 `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 `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `clientProtected_fk2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) 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;

--
-- Table structure for table `clientSample`
--

DROP TABLE IF EXISTS `clientSample`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientSample` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `clientFk` int(10) unsigned NOT NULL,
  `typeFk` int(10) unsigned NOT NULL,
  `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `workerFk` int(10) unsigned NOT NULL,
  `balance` float NOT NULL,
  `companyFk` smallint(5) unsigned DEFAULT NULL,
  `userFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `empresa_id` (`companyFk`),
  CONSTRAINT `clientSample_ibfk_1` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `clientType`
--

DROP TABLE IF EXISTS `clientType`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientType` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `code` varchar(20) CHARACTER SET utf8 NOT NULL,
  `type` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `isCreatedAsServed` tinyint(1) DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `code_UNIQUE` (`code`)
) ENGINE=InnoDBDEFAULT 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 `cmr`
--

DROP TABLE IF EXISTS `cmr`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cmr` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ticketFk` int(11) NOT NULL,
  `truckPlate` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,
  `observations` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `senderInstruccions` varchar(255) COLLATE utf8_unicode_ci DEFAULT 'Flowers 4º C. Plants 14º C',
  `paymentInstruccions` varchar(255) COLLATE utf8_unicode_ci DEFAULT 'Carriage paid',
  `specialAgreements` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `cmr_fk1_idx` (`ticketFk`),
  CONSTRAINT `cmr_fk1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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`.`cmr_BEFORE_INSERT` BEFORE INSERT ON `cmr` FOR EACH ROW
BEGIN

	DECLARE vLastSenderInstructions VARCHAR(255);
    DECLARE vLastId INT;
    DECLARE vCurrentAgency INT;
    
    SELECT am.agencyFk INTO vCurrentAgency
		FROM vn.agencyMode am
        JOIN vn.ticket t ON t.agencyModeFk = am.id
        WHERE t.id = NEW.ticketFk;
    
     SELECT MAX(cmr.id)  INTO vLastId
		FROM cmr
        JOIN vn.ticket t ON t.id = cmr.ticketFk
        JOIN vn.agencyMode am ON am.id = t.agencyModeFk
        WHERE am.agencyFk = vCurrentAgency 
        ;
        
    SELECT senderInstruccions INTO vLastSenderInstructions
		FROM cmr
        WHERE id = vLastId;
        
	SET NEW.senderInstruccions = vLastSenderInstructions;

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

DROP TABLE IF EXISTS `cmr_list`;
/*!50001 DROP VIEW IF EXISTS `cmr_list`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `cmr_list` AS SELECT 
 1 AS `cmrFk`,
 1 AS `ticketFk`,
 1 AS `truckPlate`,
 1 AS `observations`,
 1 AS `senderInstruccions`,
 1 AS `paymentInstruccions`,
 1 AS `specialAgreements`,
 1 AS `created`,
 1 AS `addressFk`,
 1 AS `shipped`,
 1 AS `clientName`,
 1 AS `clientPostalCode`,
 1 AS `clientStreet`,
 1 AS `clientCity`,
 1 AS `clientProvince`,
 1 AS `clientCountry`,
 1 AS `companyName`,
 1 AS `companyStreet`,
 1 AS `companyPostCode`,
 1 AS `companyCity`,
 1 AS `companyCountry`,
 1 AS `warehouseAddress`,
 1 AS `clientOficialName`,
 1 AS `carrierName`,
 1 AS `carrierStreet`,
 1 AS `carrierPostCode`,
 1 AS `carrierCity`,
 1 AS `carrierCountry`,
 1 AS `phone`,
 1 AS `mobile`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `collection`
--

DROP TABLE IF EXISTS `collection`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `collection` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `workerFk` int(11) DEFAULT NULL,
  `stateFk` tinyint(3) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `ticketCollection_idx` (`workerFk`),
  KEY `collection_id2_idx` (`stateFk`),
  CONSTRAINT `collection_id2` FOREIGN KEY (`stateFk`) REFERENCES `state` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `ticketCollection` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `collectionReportSource`
--

DROP TABLE IF EXISTS `collectionReportSource`;
/*!50001 DROP VIEW IF EXISTS `collectionReportSource`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `collectionReportSource` AS SELECT 
 1 AS `collectionFk`,
 1 AS `ticketFk`,
 1 AS `itemFk`,
 1 AS `concept`,
 1 AS `size`,
 1 AS `quantity`,
 1 AS `nicho`,
 1 AS `level`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `collectionVolumetry`
--

DROP TABLE IF EXISTS `collectionVolumetry`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `collectionVolumetry` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `level` int(10) unsigned NOT NULL DEFAULT '0',
  `lines` int(10) unsigned NOT NULL DEFAULT '1',
  `liters` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `company`
--

DROP TABLE IF EXISTS `company`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `company` (
  `id` smallint(5) unsigned NOT NULL,
  `code` char(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `register` varchar(120) COLLATE utf8_unicode_ci NOT NULL,
  `workerManagerFk` int(11) NOT NULL,
  `registered` date NOT NULL,
  `expired` date DEFAULT NULL,
  `logo` longblob,
  `isOfficial` tinyint(1) unsigned NOT NULL DEFAULT '1',
  `hasCyc` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0',
  `rgb` varchar(6) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `stamp` blob,
  `created` timestamp NOT NULL ON UPDATE CURRENT_TIMESTAMP,
  `clientFk` int(11) DEFAULT NULL,
  `sage200Company` int(2) DEFAULT NULL,
  `supplierAccountFk` mediumint(8) unsigned DEFAULT NULL,
  `isDefaulter` tinyint(4) NOT NULL DEFAULT '0',
  `companyGroupFk` int(11) NOT NULL DEFAULT '1' COMMENT 'usado para calcular los greuges ',
  `companyCode` 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` (`workerManagerFk`),
  KEY `empresa_cliente_idx` (`clientFk`),
  KEY `Id_Proveedores_account` (`supplierAccountFk`),
  KEY `empresa_grupo_fk_idx` (`companyGroupFk`),
  CONSTRAINT `company_ibfk_1` FOREIGN KEY (`workerManagerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `empresa_cliente` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `empresa_fk4` FOREIGN KEY (`supplierAccountFk`) REFERENCES `supplierAccount` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `fk_empresa_grupo` FOREIGN KEY (`companyGroupFk`) REFERENCES `companyGroup` (`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 `companyGroup`
--

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

--
-- Temporary table structure for view `component`
--

DROP TABLE IF EXISTS `component`;
/*!50001 DROP VIEW IF EXISTS `component`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `component` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `typeFk`,
 1 AS `classRate`,
 1 AS `tax`,
 1 AS `isRenewable`,
 1 AS `code`*/;
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`,
 1 AS `code`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `componentType`
--

DROP TABLE IF EXISTS `componentType`;
/*!50001 DROP VIEW IF EXISTS `componentType`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `componentType` AS SELECT 
 1 AS `id`,
 1 AS `type`,
 1 AS `base`,
 1 AS `isMargin`*/;
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=InnoDBDEFAULT 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 AUTO_INCREMENT,
  `ochoa` int(10) unsigned NOT NULL,
  `invoiceOutFk` int(11) DEFAULT '0',
  `bookFk` int(11) DEFAULT '0',
  `serialAFk` int(11) DEFAULT '0',
  `serialEFk` int(11) DEFAULT '0',
  `serialRFk` int(11) DEFAULT '0',
  `serialCFk` int(11) DEFAULT '0',
  `serialHFk` int(11) NOT NULL,
  `serialPFk` int(11) DEFAULT '0',
  `serialTFk` int(11) DEFAULT '0',
  `inventoried` datetime DEFAULT NULL,
  `serialMFk` int(11) DEFAULT '0',
  `itemLog` int(11) DEFAULT '0',
  `weekGoal` int(11) DEFAULT NULL,
  `photosPath` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `cashBoxNumber` int(11) DEFAULT '0',
  `redCode` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `TabletTime` 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,
  `campaignLife` tinyint(3) unsigned NOT NULL,
  `truckDays` tinyint(3) unsigned NOT NULL,
  `transportCharges` double NOT NULL,
  `escanerPath` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `printedTurn` int(4) DEFAULT NULL,
  `truckLength` int(11) DEFAULT '24',
  `fuelConsumption` int(11) DEFAULT NULL,
  `petrol` decimal(10,1) DEFAULT NULL,
  `maintenance` decimal(10,1) DEFAULT NULL,
  `hourPrice` decimal(10,1) DEFAULT NULL,
  `meterPrice` decimal(10,1) DEFAULT NULL,
  `kmPrice` decimal(10,1) DEFAULT NULL,
  `routeOption` int(11) DEFAULT '1',
  `dbproduccion` tinyint(1) NOT NULL DEFAULT '1',
  `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`),
  KEY `fechainv_idx` (`inventoried`)
) ENGINE=InnoDBDEFAULT 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `contactChannel`
--

DROP TABLE IF EXISTS `contactChannel`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `contactChannel` (
  `id` smallint(6) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Canal por el que nos ha conocido un cliente y  se ha dado de';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `country`
--

DROP TABLE IF EXISTS `country`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `country` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `country` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `CEE` tinyint(1) NOT NULL DEFAULT '1',
  `code` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL,
  `currencyFk` tinyint(3) unsigned NOT NULL DEFAULT '1',
  `politicalCountryFk` mediumint(8) unsigned NOT NULL COMMENT 'Pais Real(apaño por culpa del España Exento)',
  `nstGeoFk` int(11) DEFAULT NULL,
  `nstName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `geoFk` int(11) DEFAULT NULL,
  `hasDailyInvoice` tinyint(4) NOT NULL DEFAULT '0',
  `isUeeMember` tinyint(4) NOT NULL DEFAULT '0',
  `ibanLength` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `Id_Paisreal` (`politicalCountryFk`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`country_beforeInsert` 
    BEFORE INSERT ON `country` FOR EACH ROW
BEGIN
    SET NEW.geoFk = zoneGeo_new('country', NEW.country, 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 SET @saved_cs_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 `vn`.`country_beforeUpdate` 
    BEFORE UPDATE ON `country` FOR EACH ROW
BEGIN
	IF !(OLD.geoFk <=> NEW.geoFk) THEN
		CALL zoneGeo_throwNotEditable;
	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 `vn`.`country_afterUpdate` AFTER UPDATE ON `country` FOR EACH ROW
BEGIN
	IF !(OLD.country <=> NEW.country) THEN
		UPDATE zoneGeo SET `name` = NEW.country
			WHERE id = NEW.geoFk;
	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 `vn`.`country_afterDelete` AFTER DELETE ON `country` FOR EACH ROW
BEGIN
	CALL zoneGeo_delete(OLD.geoFk);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `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=InnoDBDEFAULT 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 `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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_beforeUpdate` 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 `client` c
			SET creditInsurance = 0 WHERE c.id = 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 */ ;

--
-- 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Detalla los clientes que tienen seguro de credito';
/*!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`.`creditInsurance_afterInsert` AFTER INSERT ON `creditInsurance` FOR EACH ROW
BEGIN
	UPDATE `client` c
		JOIN vn.creditClassification  cc ON cc.client = c.id
        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 */ ;

--
-- 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` (
  `id` tinyint(3) unsigned NOT NULL,
  `code` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ratio` double NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `Moneda_UNIQUE` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 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;

--
-- Table structure for table `deliveryMethod`
--

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

--
-- Table structure for table `deliveryPoint`
--

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

--
-- Table structure for table `delivery_zip`
--

DROP TABLE IF EXISTS `delivery_zip`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `delivery_zip` (
  `postal_code` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `country_code` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `place_name` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `admin_name1` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `code_name1` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `admin_name2` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `code_name2` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `admin_name3` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `code_name3` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `latitude` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `longitude` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `accuracy` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  KEY `country_code_idx` (`country_code`),
  KEY `place_name_idx` (`place_name`),
  KEY `postal_code_idx` (`postal_code`),
  KEY `admin_name3_idx` (`admin_name3`),
  KEY `admin_name2_idx` (`admin_name2`)
) 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` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `lft` int(11) DEFAULT NULL,
  `rgt` int(11) DEFAULT NULL,
  `workerFk` int(11) DEFAULT NULL COMMENT 'Id_Trabajador es el jefe del departamento',
  `companyFk` int(11) NOT NULL,
  `bossFk` int(11) DEFAULT NULL,
  `x` int(11) DEFAULT NULL,
  `y` int(11) DEFAULT NULL,
  `isProduction` tinyint(4) NOT NULL DEFAULT '0',
  `isSelected` tinyint(1) NOT NULL DEFAULT '0',
  `depth` int(11) NOT NULL DEFAULT '0',
  `sons` decimal(10,0) NOT NULL DEFAULT '0',
  `parentFk` int(10) unsigned DEFAULT NULL,
  `path` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name_UNIQUE` (`name`),
  KEY `fk_department_Trabajadores1_idx` (`workerFk`),
  KEY `dep_org_ibfk_3_idx` (`companyFk`),
  KEY `lft_rgt_depth_idx` (`lft`,`rgt`,`depth`),
  CONSTRAINT `fk_department_Trabajadores1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `vn`.`department_beforeInsert` 
	BEFORE INSERT ON `department` FOR EACH ROW
BEGIN
	UPDATE vn.department_recalc SET isChanged = 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 SET @saved_cs_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 `vn`.`department_afterUpdate` 
	AFTER UPDATE ON `department` FOR EACH ROW
BEGIN
	IF !(OLD.parentFk <=> NEW.parentFk) THEN
		UPDATE vn.department_recalc SET isChanged = TRUE;
	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 `vn`.`department_afterDelete` 
    AFTER DELETE ON `department` FOR EACH ROW
BEGIN
	UPDATE vn.department_recalc SET isChanged = 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 */ ;

--
-- Table structure for table `departmentItemType`
--

DROP TABLE IF EXISTS `departmentItemType`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `departmentItemType` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `departmentFk` int(11) NOT NULL,
  `itemTypeFk` smallint(5) unsigned NOT NULL,
  `workerFk` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `departmentItemTypeIdx1_idx` (`departmentFk`,`itemTypeFk`),
  KEY `departmentItemTypeIdx2_idx` (`itemTypeFk`),
  KEY `departmentItemTypeIdx3_idx` (`workerFk`),
  CONSTRAINT `departmentItemTypeIdx1` FOREIGN KEY (`departmentFk`) REFERENCES `department` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `departmentItemTypeIdx2` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `departmentItemTypeIdx3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 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;

--
-- Table structure for table `department_recalc`
--

DROP TABLE IF EXISTS `department_recalc`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `department_recalc` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `isChanged` tinyint(4) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `device`
--

DROP TABLE IF EXISTS `device`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `device` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `sn` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `model` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `userFk` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `device_fk1_idx` (`userFk`),
  CONSTRAINT `device_fk1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `deviceProduction`
--

DROP TABLE IF EXISTS `deviceProduction`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `deviceProduction` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `imei` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `modelFk` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `macWifi` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `serialNumber` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `departmentFk` int(11) DEFAULT NULL,
  `isOutOfService` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `device_id_UNIQUE` (`id`),
  UNIQUE KEY `sn_UNIQUE` (`imei`),
  KEY `deviceProductionModelsFgn` (`modelFk`),
  KEY `departmentFgn` (`departmentFk`),
  CONSTRAINT `departmentFgn` FOREIGN KEY (`departmentFk`) REFERENCES `department` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `deviceProductionModelsFgn` FOREIGN KEY (`modelFk`) REFERENCES `deviceProductionModels` (`code`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `deviceProductionModels`
--

DROP TABLE IF EXISTS `deviceProductionModels`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `deviceProductionModels` (
  `code` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `deviceProductionUser`
--

DROP TABLE IF EXISTS `deviceProductionUser`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `deviceProductionUser` (
  `deviceProductionFk` int(11) NOT NULL,
  `userFk` int(10) unsigned NOT NULL,
  PRIMARY KEY (`deviceProductionFk`,`userFk`),
  KEY `userFgn_idx` (`userFk`),
  CONSTRAINT `deviceProductionFgn` FOREIGN KEY (`deviceProductionFk`) REFERENCES `deviceProduction` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `userFgn` 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 `dms`
--

DROP TABLE IF EXISTS `dms`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dms` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dmsTypeFk` int(11) NOT NULL DEFAULT '1',
  `reference` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `description` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,
  `companyFk` smallint(5) unsigned NOT NULL DEFAULT '791',
  `hardCopyNumber` mediumint(8) unsigned DEFAULT NULL,
  `contentType` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `file` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,
  `hasFile` tinyint(4) NOT NULL DEFAULT '0',
  `workerFk` int(11) DEFAULT NULL,
  `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `warehouseFk` smallint(5) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `emp_id` (`companyFk`,`hardCopyNumber`,`warehouseFk`),
  KEY `trabajador_id` (`workerFk`),
  KEY `warehouse_id` (`warehouseFk`),
  KEY `dms_dmsTypeFk_idx` (`dmsTypeFk`),
  CONSTRAINT `dms_companyFk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `dms_dmsTypeFk` FOREIGN KEY (`dmsTypeFk`) REFERENCES `dmsType` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `dms_warehouseFk` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `dms_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`dms_beforeInsert` BEFORE INSERT ON `vn`.`dms` FOR EACH ROW
BEGIN
   DECLARE vHardCopyNumber INT;
   DECLARE vDmsTypeCode INT;

	IF NEW.warehouseFk = 44 THEN
		SET NEW.warehouseFk = 1;
	END IF;

	IF NEW.hasFile THEN
		SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber 
            FROM dms 
            WHERE companyFk = NEW.companyFk 
                AND warehouseFk = NEW.warehouseFk ;
    
		SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1) ;
    END IF;
    
	SELECT code INTO vDmsTypeCode 
		FROM dmsType WHERE NEW.dmsTypeFk = id;
	 IF (vDmsTypeCode ='ticket')  THEN
	  UPDATE ticket SET isSigned = 1 WHERE id = NEW.reference;
	 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 `vn`.`dms_beforeUpdate` BEFORE UPDATE ON `vn`.`dms` FOR EACH ROW
BEGIN
	DECLARE vHardCopyNumber INT;
	IF (NEW.hasFile <> 0) AND (OLD.hasFile = 0) AND (NEW.hardCopyNumber IS NULL) THEN

		SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber 
            FROM dms 
            WHERE companyFk = NEW.companyFk  
                AND warehouseFk = NEW.warehouseFk;

		SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1);
    END IF;
	IF ((NEW.hardCopyNumber = 0) OR NEW.hardCopyNumber IS NULL) AND (OLD.hardCopyNumber <> 0)  THEN
    
		SET NEW.hasFile = 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 `dmsType`
--

DROP TABLE IF EXISTS `dmsType`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dmsType` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` 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,
  `code` varchar(45) COLLATE utf8_unicode_ci NOT 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 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 `dms` (`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 `company` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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 `entry` (`id`) 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 `intrastat` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `duaIntrastat_fk2` FOREIGN KEY (`duaFk`) REFERENCES `dua` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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=InnoDBDEFAULT 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 `supplier` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `duaTax_fk3` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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;

--
-- Table structure for table `emergencyMedia`
--

DROP TABLE IF EXISTS `emergencyMedia`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `emergencyMedia` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Table to save all emergency phones',
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `energyInput`
--

DROP TABLE IF EXISTS `energyInput`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `energyInput` (
  `input` int(11) NOT NULL COMMENT 'The input number',
  `description` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `consumption` int(11) NOT NULL COMMENT 'Consumption in watts',
  PRIMARY KEY (`input`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Defines inputs and the power of each one';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `energyMeter`
--

DROP TABLE IF EXISTS `energyMeter`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `energyMeter` (
  `input` int(11) NOT NULL COMMENT 'The input number',
  `period` datetime NOT NULL COMMENT 'Consumption period in hours interval',
  `activeTime` int(11) NOT NULL COMMENT 'Number of seconds active',
  `consumption` decimal(10,2) NOT NULL COMMENT 'Comsumption in watts',
  PRIMARY KEY (`input`,`period`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='History of consumption of each input with one hour intervals';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `entry`
--

DROP TABLE IF EXISTS `entry`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `entry` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `supplierFk` int(11) NOT NULL DEFAULT '644',
  `dated` datetime NOT NULL,
  `ref` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `isBooked` tinyint(1) NOT NULL DEFAULT '0',
  `isInventory` tinyint(1) NOT NULL DEFAULT '0',
  `notes` longtext COLLATE utf8_unicode_ci,
  `isConfirmed` tinyint(1) NOT NULL DEFAULT '0',
  `isOrdered` tinyint(1) NOT NULL DEFAULT '0',
  `isRaid` tinyint(1) NOT NULL DEFAULT '0',
  `commission` float DEFAULT '0',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `evaNotes` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `travelFk` int(11) unsigned DEFAULT NULL,
  `currencyFk` tinyint(3) unsigned DEFAULT '1',
  `companyFk` smallint(5) unsigned NOT NULL DEFAULT '442',
  `gestDocFk` int(11) DEFAULT NULL,
  `invoiceInFk` mediumint(8) unsigned DEFAULT NULL,
  `isBlocked` tinyint(4) NOT NULL DEFAULT '0',
  `loadPriority` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `Id_Proveedor` (`supplierFk`),
  KEY `Fecha` (`dated`),
  KEY `travel_id` (`travelFk`),
  KEY `empresa_id` (`companyFk`),
  KEY `gestdoc_id` (`gestDocFk`),
  KEY `recibida_id` (`invoiceInFk`),
  CONSTRAINT `Entradas_fk8` FOREIGN KEY (`invoiceInFk`) REFERENCES `vn2008`.`recibida` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `entry_ibfk_1` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `entry_ibfk_6` FOREIGN KEY (`travelFk`) REFERENCES `travel` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `entry_ibfk_7` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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 `entry`
    FOR EACH ROW
BEGIN
    SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk);
    SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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_afterInsert`
	AFTER INSERT ON `entry`
    FOR EACH ROW
BEGIN	
	CALL travel_requestRecalc(NEW.travelFk);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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`.`entry_beforeUpdate`
	BEFORE UPDATE ON `entry`
    FOR EACH ROW
BEGIN
    DECLARE vIsVirtual BOOL;
    DECLARE vPrintedCount INT;
    DECLARE vHasDistinctWarehouses BOOL;

	IF !(NEW.travelFk <=> OLD.travelFk) THEN
		SELECT COUNT(*) > 0 INTO vIsVirtual
			FROM entryVirtual WHERE entryFk = NEW.id;

		SELECT !(o.warehouseInFk <=> n.warehouseInFk)
			OR !(o.warehouseOutFk <=> n.warehouseOutFk)
			INTO vHasDistinctWarehouses
			FROM travel o, travel n
			WHERE o.id = OLD.travelFk
				AND n.id = NEW.travelFk;

		IF vIsVirtual AND vHasDistinctWarehouses THEN
			SIGNAL SQLSTATE '45000'
				SET MESSAGE_TEXT = 'A cloned entry cannot be moved to a travel with different warehouses';
		END IF;
        
        IF NEW.travelFk IS NULL THEN
			SELECT COUNT(*) INTO vPrintedCount
				FROM buy
                WHERE entryFk = OLD.id
					AND printedStickers > 0;

			IF vPrintedCount > 0 THEN
				SIGNAL SQLSTATE '45000'
					SET MESSAGE_TEXT = 'An entry that contains lines with printed labels cannot be deleted';
			END IF;
        END IF;
	END IF;

	IF !(NEW.supplierFk <=> OLD.supplierFk) THEN
		SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk);
	END IF;

    IF !(NEW.travelFk <=> OLD.travelFk)
	OR !(NEW.currencyFk <=> OLD.currencyFk) THEN 
		SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk);
	END IF;

	IF !(ABS(NEW.isBooked) <=> ABS(OLD.isBooked)) THEN
		INSERT INTO entryLog SET
			action = 'update',
            description = 'Cambia a Contabilizada',
            userFk = myWorker_getId(),
            originFk = 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 */ ;
/*!50003 SET @saved_cs_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 `entry`
    FOR EACH ROW
BEGIN
	IF !(NEW.id <=> OLD.id)
    OR !(NEW.travelFk <=> OLD.travelFk)
    OR !(NEW.isRaid <=> OLD.isRaid) THEN
		CALL stock.log_add('entry', NEW.id, OLD.id);
	END IF;
	
	IF !(NEW.travelFk <=> OLD.travelFk) THEN
		CALL travel_requestRecalc(OLD.travelFk);
		CALL travel_requestRecalc(NEW.travelFk);
	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_beforeDelete`
	BEFORE DELETE ON `entry`
    FOR EACH ROW
BEGIN
	DELETE FROM buy WHERE entryFk = 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 */ ;
/*!50003 SET @saved_cs_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_afterDelete`
	AFTER DELETE ON `entry`
    FOR EACH ROW
BEGIN	
	CALL travel_requestRecalc(OLD.travelFk);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `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 `entry` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `entryLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `entrySplit`
--

DROP TABLE IF EXISTS `entrySplit`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `entrySplit` (
  `receivedFk` int(11) NOT NULL,
  `delayedFk` int(11) NOT NULL,
  PRIMARY KEY (`receivedFk`,`delayedFk`),
  KEY `entrySplit_fk2_idx` (`delayedFk`),
  CONSTRAINT `entrySplit_fk1` FOREIGN KEY (`receivedFk`) REFERENCES `entry` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `entrySplit_fk2` FOREIGN KEY (`delayedFk`) REFERENCES `entry` (`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 `entryVirtual`
--

DROP TABLE IF EXISTS `entryVirtual`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `entryVirtual` (
  `entryFk` int(11) NOT NULL,
  PRIMARY KEY (`entryFk`),
  CONSTRAINT `entryVirtual_ibfk_1` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='entradas que se van moviendo automaticamente al futuro';
/*!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=InnoDBDEFAULT 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 `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 `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 `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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `expedition`
--

DROP TABLE IF EXISTS `expedition`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expedition` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `agencyModeFk` int(11) NOT NULL,
  `ticketFk` int(10) NOT NULL,
  `isBox` int(11) DEFAULT '1',
  `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `isRefund` bit(1) DEFAULT b'0',
  `isPickUp` bit(1) DEFAULT b'0',
  `itemFk` 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 (`id`),
  KEY `index1` (`agencyModeFk`),
  KEY `index2` (`isBox`),
  KEY `index3` (`created`),
  KEY `index4` (`ticketFk`),
  CONSTRAINT `Id_Agencia` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `ticket_id` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `vn`.`expedition_beforeInsert`
	BEFORE INSERT ON `expedition` FOR EACH ROW
BEGIN
	DECLARE intcounter INT;
    DECLARE vShipFk INT;

	IF NEW.isBox > 0 THEN 

		UPDATE ticket SET packages = nz(packages) + 1 WHERE id = NEW.ticketFk;

		SELECT IFNULL(MAX(counter),0) +1 INTO intcounter 
            FROM expedition e 
				INNER JOIN ticket t1 ON e.ticketFk = t1.id 
                LEFT JOIN ticketState ts ON ts.ticket = t1.id
				INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) 
                    AND t1.warehouseFk = t2.warehouseFk
			WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk 
                AND t1.agencyModeFk = t2.agencyModeFk;

		SET NEW.`counter` = intcounter;
	END IF;
    
    SELECT shipFk INTO vShipFk FROM stowaway WHERE id = NEW.ticketFk;

    IF vShipFk THEN
		CALL stowaway_unboarding(vShipFk, NEW.ticketFk);
    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 `vn`.`expedition_beforeUpdate`
	BEFORE UPDATE ON `expedition` 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 expedition e 
				INNER JOIN ticket t1 ON e.ticketFk = t1.id
				INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) 
			WHERE t1.id = NEW.ticketFk AND counter = NEW.counter) > 0 THEN
			SET NEW.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  = 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 `vn`.`expedition_beforeDelete`
	BEFORE DELETE ON `expedition` FOR EACH ROW
BEGIN
    UPDATE ticket t 
        SET packages = (SELECT COUNT(counter)-1 
		FROM expedition e WHERE e.ticketFk = OLD.ticketFk and e.isBox)
		WHERE t.id = OLD.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 */ ;

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

--
-- Table structure for table `expence`
--

DROP TABLE IF EXISTS `expence`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expence` (
  `id` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `taxTypeFk` tinyint(4) NOT NULL,
  `name` varchar(50) DEFAULT NULL,
  `isConbase` tinyint(4) NOT NULL DEFAULT '1',
  `isWithheld` tinyint(4) NOT NULL DEFAULT '0',
  `isForSale` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`,`taxTypeFk`),
  KEY `iva_tipo_id` (`taxTypeFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 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 `fuelType`
--

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

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

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

--
-- Table structure for table `greuge`
--

DROP TABLE IF EXISTS `greuge`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `greuge` (
  `Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `clientFk` int(10) unsigned NOT NULL,
  `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `amount` decimal(10,2) NOT NULL,
  `shipped` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `greugeTypeFk` int(11) DEFAULT NULL,
  `ticketFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`Id`),
  KEY `greuges_type_fk_idx` (`greugeTypeFk`),
  KEY `Id_Ticket_Greuge_Ticket_idx` (`ticketFk`),
  KEY `Greuges_cliente_idx` (`clientFk`),
  CONSTRAINT `Id_Ticket_Greuge_Ticket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `greuges_type_fk` FOREIGN KEY (`greugeTypeFk`) REFERENCES `greugeType` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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 `vn`.`greuge_beforeUpdate` BEFORE UPDATE ON `greuge` FOR EACH ROW
BEGIN
	DECLARE vMaxDate DATETIME DEFAULT TIMESTAMPADD(YEAR,1,CURDATE());

    IF NEW.shipped > vMaxDate THEN
		SET NEW.shipped = 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 `greugeType`
--

DROP TABLE IF EXISTS `greugeType`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `greugeType` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `code` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

--
-- Table structure for table `ink`
--

DROP TABLE IF EXISTS `ink`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ink` (
  `id` char(3) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `picture` blob NOT NULL,
  `showOrder` int(11) NOT NULL,
  `ball` blob,
  `isCargex` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

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

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

--
-- 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` (
  `id` int(8) unsigned zerofill NOT NULL,
  `description` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `import` tinyint(4) NOT NULL DEFAULT '0',
  `taxClassFk` tinyint(3) unsigned NOT NULL DEFAULT '2',
  `taxCodeFk` tinyint(2) unsigned NOT NULL DEFAULT '64',
  PRIMARY KEY (`id`),
  KEY `iva_group_id` (`taxClassFk`),
  CONSTRAINT `intrastat_ibfk_1` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`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 `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 `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `inventoryFailure_fk2` FOREIGN KEY (`throwerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `inventoryFailure_fk3` FOREIGN KEY (`guiltyFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `inventoryFailure_fk4` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `inventoryFailure_fk5` FOREIGN KEY (`causeFk`) REFERENCES `inventoryFailureCause` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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=InnoDBDEFAULT 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 `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `correcting_fk` FOREIGN KEY (`correctingFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `cplusInvoiceTyoeFk` FOREIGN KEY (`cplusInvoiceType477Fk`) REFERENCES `cplusInvoiceType477` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `invoiceCorrectionType_Fk33` FOREIGN KEY (`invoiceCorrectionTypeFk`) REFERENCES `invoiceCorrectionType` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `invoiceCorrection_ibfk_1` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `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 */;

--
-- 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

DROP TABLE IF EXISTS `invoiceInSerial`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceInSerial` (
  `code` varchar(2) COLLATE utf8_unicode_ci NOT NULL,
  `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `cplusTerIdNifFk` int(11) NOT NULL DEFAULT '1',
  `taxAreaFk` varchar(15) 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 */;

--
-- 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 `taxClass` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `invoiceInTaxBookingAccount_fk3` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `invoiceOut`
--

DROP TABLE IF EXISTS `invoiceOut`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceOut` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `ref` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `serial` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `issued` date DEFAULT NULL,
  `amount` decimal(12,2) DEFAULT '0.00',
  `dued` datetime DEFAULT NULL,
  `bankFk` int(11) DEFAULT NULL,
  `clientFk` int(11) DEFAULT '0',
  `Id_Remesa__` int(11) DEFAULT NULL,
  `Remesar__` tinyint(1) NOT NULL DEFAULT '0',
  `taxableBase7` decimal(12,2) DEFAULT '0.00',
  `taxableBase16` decimal(12,2) DEFAULT '0.00',
  `equ1` decimal(12,2) DEFAULT '0.00',
  `equ4` decimal(12,2) DEFAULT '0.00',
  `vat7` decimal(12,2) DEFAULT '0.00',
  `vat16` decimal(12,2) DEFAULT '0.00',
  `workerFk` int(11) DEFAULT '0',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `companyFk` smallint(5) unsigned NOT NULL DEFAULT '442',
  `liquidacion__` smallint(6) DEFAULT '0',
  `hasPdf` 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 (`id`,`ref`),
  UNIQUE KEY `Id_Factura` (`ref`),
  KEY `Id_Banco` (`bankFk`),
  KEY `Id_Cliente` (`clientFk`),
  KEY `Id_Remesa` (`Id_Remesa__`),
  KEY `Id_Trabajador` (`workerFk`),
  KEY `empresa_id` (`companyFk`),
  KEY `Fecha` (`issued`),
  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` (`dued`),
  CONSTRAINT `invoiceOut_ibfk_1` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `invoiceOut_ibfk_2` FOREIGN KEY (`cplusInvoiceType477Fk`) REFERENCES `cplusInvoiceType477` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `invoiceOut_ibfk_3` FOREIGN KEY (`cplusSubjectOpFk`) REFERENCES `cplusSubjectOp` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `invoiceOut_ibfk_4` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `cplusTaxBreak` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `invoice_bank_id` FOREIGN KEY (`bankFk`) REFERENCES `bank` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `invoice_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `vn`.`invoiceOut_beforeInsert`
	BEFORE INSERT ON `invoiceOut` FOR EACH ROW
-- Edit trigger body code below this line. Do not edit lines above this one
BEGIN
	DECLARE vRef CHAR(9) DEFAULT '0000001';
    DECLARE vMaxId INT;

    SELECT IFNULL(MAX(id),0) INTO vMaxId 
        FROM invoiceOut 
        WHERE serial LIKE NEW.serial
            AND ((Year(NEW.issued) = Year(issued)
            AND companyFk = NEW.companyFk));
    
    IF vMaxId THEN
        
        SELECT RIGHT(MAX(ref), LENGTH(ref)-1) + 1 
            INTO vRef
            FROM invoiceOut
            WHERE serial LIKE NEW.serial
                AND ((Year(NEW.issued) = Year(issued)
                AND length(ref) > 6
                AND companyFk = NEW.companyFk) /*OR (NEW.serial LIKE 'B' AND length(ref) > 7)*/ );
    ELSE
			SELECT CONCAT(sage200Company,RIGHT(YEAR(CURDATE()),1),'00001') INTO vRef
                FROM company 
                WHERE id = NEW.companyFk;
/*Primer digito la empresa, segundo el año, despues la numeracion correlativa con 5 digitos*/
    END IF;

    SELECT CONCAT(NEW.serial, LPAD(vRef,7,'0')) INTO vRef;
    SET NEW.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 SET @saved_cs_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 `vn`.`invoiceOut_afterInsert`
	AFTER INSERT ON `invoiceOut` FOR EACH ROW
BEGIN
	CALL bi.customer_risk_update (NEW.clientFk, NEW.companyFk, NEW.amount);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `vn`.`invoiceOut_beforeUpdate`
	BEFORE UPDATE ON `invoiceOut` FOR EACH ROW
BEGIN
	CALL bi.customer_risk_update (OLD.clientFk, OLD.companyFk, -OLD.amount);
	CALL bi.customer_risk_update (NEW.clientFk, NEW.companyFk, NEW.amount);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `vn`.`invoiceOut_beforeDelete`
	BEFORE DELETE ON `invoiceOut` FOR EACH ROW
BEGIN
	CALL bi.customer_risk_update (OLD.clientFk, OLD.companyFk, -OLD.amount);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `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 `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `invoiceOutExpence_FK_2` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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 `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `invoiceOutTax_ibfk_1` FOREIGN KEY (`pgcFk`) REFERENCES `pgc` (`code`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!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) NOT NULL AUTO_INCREMENT,
  `equivalent` int(11) unsigned DEFAULT NULL,
  `name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `size` int(10) unsigned DEFAULT NULL,
  `stems` int(11) DEFAULT '1',
  `minPrice` double DEFAULT '0',
  `isToPrint` tinyint(1) NOT NULL DEFAULT '0',
  `isDeliveryNote` tinyint(1) NOT NULL DEFAULT '0',
  `taxClassFk` tinyint(4) unsigned NOT NULL DEFAULT '1',
  `family` varchar(3) COLLATE utf8_unicode_ci DEFAULT 'VT',
  `box` tinyint(1) NOT NULL DEFAULT '0',
  `category` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `originFk` tinyint(2) unsigned NOT NULL,
  `doPhoto` tinyint(4) NOT NULL DEFAULT '0',
  `image` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `inkFk` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `niche` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `intrastatFk` int(8) unsigned zerofill DEFAULT NULL,
  `hasMinPrice` tinyint(1) NOT NULL DEFAULT '0',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `isOnOffer` tinyint(4) NOT NULL DEFAULT '0',
  `isBargain` tinyint(4) NOT NULL DEFAULT '0',
  `comment` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `typeFk` smallint(5) unsigned NOT NULL,
  `generic` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0',
  `producerFk` mediumint(3) unsigned DEFAULT NULL,
  `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `density` int(11) 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' COMMENT 'Cantidad máxima de cajas / cubos que cabe en un nicho',
  `upToDown` decimal(10,0) unsigned NOT NULL DEFAULT '0' COMMENT 'Se muestra el precio por kilo ',
  `hasKgPrice` tinyint(1) NOT NULL DEFAULT '0',
  `sectorFk` int(11) DEFAULT '2',
  PRIMARY KEY (`id`),
  KEY `Article` (`name`),
  KEY `Color` (`inkFk`),
  KEY `id_origen` (`originFk`),
  KEY `Codintrastat` (`intrastatFk`),
  KEY `iva_group_id` (`taxClassFk`),
  KEY `tipo_id` (`typeFk`),
  KEY `producer_id` (`producerFk`),
  KEY `expenceFk_idx` (`expenceFk`),
  KEY `ArticlesIsActive_idx` (`isActive`),
  KEY `item_ibfk_6_idx` (`sectorFk`),
  CONSTRAINT `expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `item_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `origin` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `item_ibfk_2` FOREIGN KEY (`intrastatFk`) REFERENCES `intrastat` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `item_ibfk_4` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `item_ibfk_5` FOREIGN KEY (`typeFk`) REFERENCES `itemType` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `item_ibfk_6` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `producer_id` FOREIGN KEY (`producerFk`) REFERENCES `producer` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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`.`item_beforeInsert`
	BEFORE INSERT ON `item` FOR EACH ROW
BEGIN
	DECLARE vDensity DOUBLE;

	IF NEW.density IS NULL THEN
		SELECT density INTO vDensity
			FROM itemType WHERE id = NEW.typeFk;
            
		SET NEW.density = vDensity;
	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 `vn`.`item_afterInsert`
	AFTER INSERT ON `item` FOR EACH ROW
BEGIN
	CALL hedera.image_ref('catalog', NEW.image);

    INSERT INTO vn.itemTaxCountry(itemFk, countryFk, taxClassFk)
        SELECT NEW.id, 1, NEW.taxClassFk;
        
    INSERT INTO vn.itemTaxCountry(itemFk, countryFk, taxClassFk)
        SELECT NEW.id, 5, NEW.taxClassFk;
    
    INSERT INTO vn.itemTaxCountry(itemFk, countryFk, taxClassFk)
        SELECT NEW.id, 30, NEW.taxClassFk;
/*      
    IF NEW.typeFk IS NOT NULL THEN
        INSERT INTO vn.itemTag (itemFk, tagFk, priority)
            SELECT NEW.id, tagFk, priority FROM vn.itemTypeTag 
                WHERE itemTypeFk = NEW.typeFk;
    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 `vn`.`item_afterUpdate`
	AFTER UPDATE ON `item` FOR EACH ROW
BEGIN
	IF !(NEW.image <=> OLD.image) THEN
		CALL hedera.image_unref('catalog', OLD.image);
		CALL hedera.image_ref('catalog', NEW.image);
	END IF;
    IF NEW.density = 0 THEN
		CALL util.throw('error densidad = 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 `vn`.`item_afterDelete`
	AFTER DELETE ON `item` FOR EACH ROW
BEGIN
	CALL hedera.image_unref('catalog', OLD.image);
    
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `itemBarcode`
--

DROP TABLE IF EXISTS `itemBarcode`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemBarcode` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `itemFk` 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` (`itemFk`,`code`),
  KEY `Id_Article` (`itemFk`),
  CONSTRAINT `itemBarcode_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `itemBotanical`
--

DROP TABLE IF EXISTS `itemBotanical`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemBotanical` (
  `itemFk` int(11) NOT NULL,
  `botanical` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `genusFk` mediumint(8) unsigned DEFAULT NULL,
  `specieFk` mediumint(8) unsigned DEFAULT NULL,
  PRIMARY KEY (`itemFk`),
  KEY `genusFgn_idx` (`genusFk`),
  KEY `specieFgn_idx` (`specieFk`)
) 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              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`itemBotanical_beforeInsert` BEFORE INSERT ON `itemBotanical` 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              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`itemBotanical_beforeUpdate` BEFORE UPDATE ON `itemBotanical` 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 */ ;

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

--
-- Table structure for table `itemCategory`
--

DROP TABLE IF EXISTS `itemCategory`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemCategory` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `order` int(10) unsigned DEFAULT NULL,
  `display` tinyint(4) NOT NULL DEFAULT '1',
  `color` char(6) COLLATE utf8_unicode_ci DEFAULT NULL,
  `shortLife` int(11) NOT NULL DEFAULT '0' COMMENT 'Sirve para filtrar aquellos reinos que tienen precios estables',
  `merchandise` tinyint(1) NOT NULL DEFAULT '1',
  `icon` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `code` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `reino_UNIQUE` (`name`),
  KEY `itemCategory_idx3` (`merchandise`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

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

--
-- 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 `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `itemConversor_fk2` FOREIGN KEY (`genItemFk`) REFERENCES `item` (`id`) 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 */;

--
-- Temporary table structure for view `itemEntryIn`
--

DROP TABLE IF EXISTS `itemEntryIn`;
/*!50001 DROP VIEW IF EXISTS `itemEntryIn`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemEntryIn` AS SELECT 
 1 AS `warehouseInFk`,
 1 AS `landed`,
 1 AS `itemFk`,
 1 AS `quantity`,
 1 AS `isReceived`,
 1 AS `isVirtualStock`,
 1 AS `entryFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `itemEntryOut`
--

DROP TABLE IF EXISTS `itemEntryOut`;
/*!50001 DROP VIEW IF EXISTS `itemEntryOut`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemEntryOut` AS SELECT 
 1 AS `warehouseOutFk`,
 1 AS `shipped`,
 1 AS `itemFk`,
 1 AS `quantity`,
 1 AS `isDelivered`,
 1 AS `entryFk`*/;
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 `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `itemLogUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `itemPlacement`
--

DROP TABLE IF EXISTS `itemPlacement`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemPlacement` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `itemFk` int(11) NOT NULL,
  `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '1',
  `code` 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',
  `sectorFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `Id_Article_UNIQUE` (`itemFk`,`warehouseFk`),
  KEY `Articles_nicho_wh_fk` (`warehouseFk`),
  KEY `itemPlacement_fk3_idx` (`id`,`sectorFk`),
  KEY `itemPlacement_fk3_idx1` (`sectorFk`),
  CONSTRAINT `Articles_nicho_wh_fk` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `Articles_nichos_fk` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `itemPlacement_fk3` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `vn`.`itemPlacement_AFTER_DELETE` AFTER DELETE ON `itemPlacement` FOR EACH ROW
BEGIN
	INSERT INTO vn.mail SET
		`sender` = 'jgallego@verdnatura.es',
		`replyTo` = 'jgallego@verdnatura.es',
		`subject` = 'Nicho modificado',
		`body` = CONCAT(account.myUserGetName(), ' ha eliminado la linea de  ', 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 */ ;

--
-- 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',
  `sectorFk` int(11) NOT NULL DEFAULT '2',
  PRIMARY KEY (`id`),
  KEY `itemPlacementSupply_fk1_idx` (`itemFk`),
  KEY `itemPlacementSupply_fk2_idx` (`userFk`),
  KEY `itemPlacementSupply_fk2_idx1` (`repoUserFk`),
  KEY `itemPlacementSupply_fk4_idx` (`sectorFk`),
  CONSTRAINT `itemPlacementSupply_fk1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) 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,
  CONSTRAINT `itemPlacementSupply_fk4` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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`,
 1 AS `sectorFk`*/;
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`,
 1 AS `sectorFk`*/;
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 `item` (`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 `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',
  `userFk` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `itemShelving_fk1_idx` (`itemFk`),
  KEY `itemShelving_fk2_idx` (`shelvingFk`),
  KEY `itemShelving_fk3_idx` (`packagingFk`),
  KEY `itemShelving_fk3_idx1` (`userFk`),
  CONSTRAINT `itemShelving_fk1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) 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 `packaging` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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 */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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`.`itemShelving_BEFORE_INSERT` BEFORE INSERT ON `itemShelving` FOR EACH ROW
BEGIN

	SET NEW.userFk = 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 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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=`z-developer`@`%`*/ /*!50003 TRIGGER `vn`.`itemShelving_BEFORE_UPDATE` BEFORE UPDATE ON `itemShelving` FOR EACH ROW
BEGIN

	SET NEW.userFk = 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 */ ;

--
-- 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`,
 1 AS `hour`,
 1 AS `isPreviousPreparable`,
 1 AS `physicalVolume`*/;
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 DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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`,
 1 AS `parkingFk`,
 1 AS `sectorFk`*/;
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 `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `itemShelvingSale_fk3` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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 */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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`.`itemShelvingSale_AFTER_INSERT` AFTER INSERT ON `itemShelvingSale` FOR EACH ROW
BEGIN

	UPDATE vn.sale
		SET isPicked = TRUE 
        WHERE id = NEW.saleFk;

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

DROP TABLE IF EXISTS `itemShelvingSaleSum`;
/*!50001 DROP VIEW IF EXISTS `itemShelvingSaleSum`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemShelvingSaleSum` AS SELECT 
 1 AS `id`,
 1 AS `itemShelvingFk`,
 1 AS `saleFk`,
 1 AS `quantity`,
 1 AS `created`,
 1 AS `sectorFk`*/;
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 `grouping`,
 1 AS `sector`,
 1 AS `visibleOriginal`,
 1 AS `removed`,
 1 AS `sectorFk`,
 1 AS `warehouseFk`,
 1 AS `shelvingFk`,
 1 AS `parkingCode`,
 1 AS `parkingFk`,
 1 AS `itemShelvingFk`,
 1 AS `created`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `itemShelvingStockFull`
--

DROP TABLE IF EXISTS `itemShelvingStockFull`;
/*!50001 DROP VIEW IF EXISTS `itemShelvingStockFull`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemShelvingStockFull` AS SELECT 
 1 AS `itemFk`,
 1 AS `quantity`,
 1 AS `packing`,
 1 AS `grouping`,
 1 AS `sector`,
 1 AS `removed`,
 1 AS `sectorFk`,
 1 AS `warehouseFk`,
 1 AS `shelvingFk`,
 1 AS `parkingCode`,
 1 AS `parkingFk`,
 1 AS `itemShelvingFk`,
 1 AS `created`*/;
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;

--
-- 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,
  `intValue` int(11) DEFAULT NULL,
  `priority` int(2) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `itemFk` (`itemFk`,`tagFk`,`value`) USING BTREE,
  KEY `tagFk` (`tagFk`,`value`),
  KEY `priorityItem` (`priority`,`itemFk`),
  KEY `value` (`value`),
  KEY `itemFk_2` (`itemFk`,`tagFk`,`intValue`),
  CONSTRAINT `itemTagItemFk` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `itemTagTagFk` FOREIGN KEY (`tagFk`) REFERENCES `tag` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `vn`.`itemTag_beforeInsert`
	BEFORE INSERT ON `itemTag` FOR EACH ROW
BEGIN
	SET NEW.intValue = itemTag_getIntValue(NEW.`value`);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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_INSERT` AFTER INSERT ON `itemTag` FOR EACH ROW
trig: BEGIN
	IF @isTriggerDisabled THEN
		LEAVE trig;
	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  = 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 `vn`.`itemTag_beforeUpdate`
	BEFORE UPDATE ON `itemTag` FOR EACH ROW
BEGIN
    IF !(OLD.`value` <=> NEW.`value`)
    OR !(OLD.intValue <=> NEW.intValue) THEN
		SET NEW.intValue = itemTag_getIntValue(NEW.`value`);
    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 `vn`.`itemTag_afterUpdate`
	AFTER UPDATE ON `itemTag` FOR EACH ROW
trig: BEGIN
	IF @isTriggerDisabled THEN
		LEAVE trig;
	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  = 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 `vn`.`itemTag_afterDelete`
	AFTER DELETE ON `itemTag` FOR EACH ROW
trig: BEGIN
	IF @isTriggerDisabled THEN
		LEAVE trig;
	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`),
  CONSTRAINT `countryFK_paises` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `itemFK_Article` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `taxClassFK_Iva_Group` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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 `itemTicketOut`
--

DROP TABLE IF EXISTS `itemTicketOut`;
/*!50001 DROP VIEW IF EXISTS `itemTicketOut`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemTicketOut` AS SELECT 
 1 AS `warehouseFk`,
 1 AS `shipped`,
 1 AS `itemFk`,
 1 AS `quantity`,
 1 AS `isPicked`,
 1 AS `reserved`,
 1 AS `refFk`,
 1 AS `saleFk`,
 1 AS `ticketFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `itemType`
--

DROP TABLE IF EXISTS `itemType`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemType` (
  `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `code` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `order` int(11) DEFAULT '0',
  `temperature` tinyint(1) unsigned NOT NULL DEFAULT '0',
  `categoryFk` int(10) unsigned NOT NULL,
  `workerFk` int(11) NOT NULL,
  `isInventory` tinyint(4) NOT NULL DEFAULT '1' COMMENT 'Se utiliza tanto en el cálculo del inventario, como en el del informe del inventario valorado',
  `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `f11` tinyint(4) NOT NULL DEFAULT '0',
  `father` smallint(5) DEFAULT NULL,
  `transaction` tinyint(4) NOT NULL DEFAULT '0',
  `making` 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',
  `topMargin` double NOT NULL DEFAULT '0.3',
  `profit` double NOT NULL DEFAULT '0.02',
  `isFV` 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',
  `isBox` 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 (`code`),
  UNIQUE KEY `tipo_id_UNIQUE` (`id`),
  UNIQUE KEY `Tipo_UNIQUE` (`name`,`categoryFk`),
  KEY `Trabajador` (`workerFk`),
  KEY `reino_id` (`categoryFk`),
  KEY `Tipos_fk3_idx` (`making`),
  KEY `tipos_fk4_idx` (`roleCodeFk`),
  KEY `warehouseFk5_idx` (`warehouseFk`),
  CONSTRAINT `Tipos_fk3` FOREIGN KEY (`making`) REFERENCES `confectionType` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `Trabajador` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `itemType_ibfk_1` FOREIGN KEY (`categoryFk`) REFERENCES `itemCategory` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `itemType_ibfk_2` FOREIGN KEY (`roleCodeFk`) REFERENCES `account`.`role` (`name`) ON UPDATE CASCADE,
  CONSTRAINT `warehouseFk5` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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  = 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 `vn`.`itemType_beforeUpdate` BEFORE UPDATE ON `itemType` FOR EACH ROW
-- Edit trigger body code below this line. Do not edit lines above this one
BEGIN
	/*
    Jgallego 12-08-2019 
    
    DECLARE strCOD VARCHAR(40);

	SELECT redCode INTO strCOD FROM config 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 `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 `itemType` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDBDEFAULT 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 `item` (`id`) 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 */;

--
-- Table structure for table `ledgerConfig`
--

DROP TABLE IF EXISTS `ledgerConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ledgerConfig` (
  `lastBookEntry` int(11) NOT NULL,
  PRIMARY KEY (`lastBookEntry`)
) 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` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `sender` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `replyTo` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `subject` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `body` text COLLATE utf8_unicode_ci NOT NULL,
  `sent` tinyint(2) NOT NULL DEFAULT '0',
  `creationDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `attachment` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `status` 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`),
  KEY `sent_idx` (`sent`),
  KEY `creation_idx` (`creationDate`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

DROP TABLE IF EXISTS `mailTemplates`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mailTemplates` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET utf8 NOT NULL,
  `attachmentPath` text CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `mandate`
--

DROP TABLE IF EXISTS `mandate`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mandate` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `clientFk` int(11) NOT NULL,
  `companyFk` smallint(5) unsigned NOT NULL,
  `code` varchar(32) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `finished` timestamp NULL DEFAULT NULL,
  `mandateTypeFk` smallint(5) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `mandato_fgkey1_idx` (`clientFk`),
  KEY `mandato_fgkey2_idx` (`companyFk`),
  KEY `mandato_fgkey3_idx` (`mandateTypeFk`),
  CONSTRAINT `mandato_fgkey1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `mandato_fgkey2` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `mandato_fgkey3` FOREIGN KEY (`mandateTypeFk`) REFERENCES `mandateType` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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`.`mandate_beforeInsert` 
    BEFORE INSERT ON `mandate`
    FOR EACH ROW
BEGIN
	IF (NEW.code IS NULL) THEN
		SET NEW.code=CONCAT(NEW.clientFk,'-',(SELECT AUTO_INCREMENT 
		    FROM information_schema.TABLES 
		    WHERE TABLE_SCHEMA='vn' and TABLE_NAME='mandate'));
    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 `mandateType`
--

DROP TABLE IF EXISTS `mandateType`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mandateType` (
  `id` smallint(5) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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,
  `isFit` 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 `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

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

--
-- Table structure for table `observationType`
--

DROP TABLE IF EXISTS `observationType`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `observationType` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `description` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `orderTicket`
--

DROP TABLE IF EXISTS `orderTicket`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `orderTicket` (
  `orderFk` int(10) unsigned NOT NULL,
  `ticketFk` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`ticketFk`,`orderFk`),
  KEY `order_id` (`orderFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `origin`
--

DROP TABLE IF EXISTS `origin`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `origin` (
  `id` tinyint(2) unsigned NOT NULL AUTO_INCREMENT,
  `code` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `warehouseFk` smallint(5) unsigned DEFAULT '4',
  `flag` blob,
  `nl` tinyint(4) NOT NULL DEFAULT '0',
  `countryFk` mediumint(8) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `Abreviatura` (`code`),
  KEY `warehouse_id` (`warehouseFk`),
  KEY `Id_Paises` (`countryFk`),
  CONSTRAINT `origin_ibfk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

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

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

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

DROP TABLE IF EXISTS `packageChecked`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `packageChecked` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `itemFk` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `entryFk_UNIQUE` (`itemFk`),
  KEY `fkItem_idx` (`itemFk`)
) ENGINE=InnoDBDEFAULT 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 `packaging` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `packageEquivalent_fk2` FOREIGN KEY (`equivalentFk`) REFERENCES `packaging` (`id`) 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;

--
-- Table structure for table `packaging`
--

DROP TABLE IF EXISTS `packaging`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `packaging` (
  `id` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `volume` decimal(10,2) DEFAULT '0.00',
  `width` decimal(10,2) DEFAULT '0.00',
  `depth` decimal(10,2) DEFAULT '0.00',
  `height` decimal(10,2) DEFAULT '0.00',
  `value` decimal(10,2) DEFAULT '0.00',
  `isPackageReturnable` tinyint(1) NOT NULL DEFAULT '0',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `packagingReturnFk` int(11) DEFAULT NULL,
  `lower` int(11) DEFAULT NULL,
  `upload` int(11) DEFAULT NULL,
  `base` decimal(10,2) DEFAULT NULL,
  `itemFk` int(11) DEFAULT NULL,
  `price` decimal(10,2) NOT NULL,
  `isBox` tinyint(1) NOT NULL DEFAULT '0',
  `cubicPackage` decimal(10,2) DEFAULT NULL,
  `returnCost` decimal(10,2) NOT NULL DEFAULT '0.00',
  `cmrName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `Article` (`itemFk`),
  CONSTRAINT `Article` FOREIGN KEY (`itemFk`) REFERENCES `item` (`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 `packagingConfig`
--

DROP TABLE IF EXISTS `packagingConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `packagingConfig` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `upperGap` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `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,
  `pickingOrder` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `column_UNIQUE` (`column`,`row`,`sectorFk`),
  UNIQUE KEY `code_UNIQUE` (`code`),
  KEY `parking_fk1_idx` (`sectorFk`),
  CONSTRAINT `parking_fk1` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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 */ ;

--
-- Table structure for table `payDem`
--

DROP TABLE IF EXISTS `payDem`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payDem` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `payDem` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `payMethod`
--

DROP TABLE IF EXISTS `payMethod`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payMethod` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `code` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
  `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `solution` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `outstandingDebt` tinyint(3) unsigned zerofill NOT NULL DEFAULT '000',
  `graceDays` int(11) unsigned NOT NULL DEFAULT '0',
  `ibanRequired` tinyint(3) DEFAULT '0',
  `isNotified` tinyint(3) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 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=InnoDBDEFAULT 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`),
  CONSTRAINT `Person_ibfk_1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `personMedia`
--

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

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

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

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

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

--
-- Table structure for table `plantpassport`
--

DROP TABLE IF EXISTS `plantpassport`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `plantpassport` (
  `producerFk` mediumint(3) unsigned NOT NULL,
  `plantpassportAuthorityFk` mediumint(3) unsigned NOT NULL,
  `number` varchar(25) CHARACTER SET utf8 DEFAULT NULL,
  `isRequested` tinyint(2) NOT NULL DEFAULT '0',
  PRIMARY KEY (`producerFk`,`plantpassportAuthorityFk`),
  KEY `plantpassport_authority_idx` (`plantpassportAuthorityFk`),
  KEY `producer_id_idx` (`producerFk`),
  CONSTRAINT `plantpassport_authority` FOREIGN KEY (`plantpassportAuthorityFk`) REFERENCES `plantpassportAuthority` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `producer` FOREIGN KEY (`producerFk`) REFERENCES `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 `plantpassportAuthority`
--

DROP TABLE IF EXISTS `plantpassportAuthority`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `plantpassportAuthority` (
  `id` mediumint(3) unsigned NOT NULL,
  `denomination` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `countryFk` mediumint(8) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `denomination_UNIQUE` (`denomination`),
  KEY `Pais_id_idx` (`countryFk`),
  CONSTRAINT `Pais_id` FOREIGN KEY (`countryFk`) REFERENCES `country` (`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 `postCode`
--

DROP TABLE IF EXISTS `postCode`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `postCode` (
  `code` varchar(30) 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 */;
/*!50003 SET @saved_cs_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 `vn`.`postCode_beforeInsert`
	BEFORE INSERT ON `postCode` FOR EACH ROW
BEGIN
    SET NEW.geoFk = zoneGeo_new('postCode', NEW.`code`,
		(SELECT geoFk FROM town WHERE id = NEW.townFk));
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `postCode_beforeUpdate`
	BEFORE UPDATE ON `postCode` FOR EACH ROW
BEGIN
	IF !(OLD.geoFk <=> NEW.geoFk) THEN
		CALL zoneGeo_throwNotEditable;
	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 `vn`.`postCode_afterUpdate`
	AFTER UPDATE ON `postCode` FOR EACH ROW
BEGIN
	IF !(OLD.townFk <=> NEW.townFk) THEN
		CALL zoneGeo_setParent(NEW.geoFk,
			(SELECT geoFk FROM town WHERE id = NEW.townFk));
	END IF;

	IF !(OLD.`code` <=> NEW.`code`) THEN
		UPDATE zoneGeo SET `name` = NEW.`code`
			WHERE id = NEW.geoFk;
	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 `vn`.`postCode_afterDelete`
	AFTER DELETE ON `postCode` FOR EACH ROW
BEGIN
	CALL zoneGeo_delete(OLD.geoFk);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `postCodeBack__`
--

DROP TABLE IF EXISTS `postCodeBack__`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `postCodeBack__` (
  `code` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `townFk` int(11) NOT NULL,
  `geoFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`code`,`townFk`),
  KEY `postCodeTownFk_idx2` (`townFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 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=InnoDBDEFAULT 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 `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `priceBuilderWarehouse_fk2` FOREIGN KEY (`priceBuilderFk`) REFERENCES `priceBuilder__` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 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 `itemType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `priceBuilder_fk2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `priceFixed`
--

DROP TABLE IF EXISTS `priceFixed`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `priceFixed` (
  `itemFk` int(10) NOT NULL,
  `rate0` double NOT NULL,
  `rate1` double NOT NULL,
  `rate2` double NOT NULL,
  `rate3` double NOT NULL,
  `started` date NOT NULL,
  `ended` date NOT NULL,
  `bonus` double NOT NULL DEFAULT '0',
  `warehouseFk` smallint(5) unsigned NOT NULL DEFAULT '0',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `grouping` smallint(5) DEFAULT NULL,
  `packing` int(11) DEFAULT NULL,
  `box` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`itemFk`,`started`,`ended`,`warehouseFk`),
  UNIQUE KEY `price_fixed_id_UNIQUE` (`id`),
  KEY `item_id` (`itemFk`),
  KEY `date_start` (`started`),
  KEY `date_end` (`ended`),
  KEY `warehouse_id` (`warehouseFk`),
  CONSTRAINT `priceFixed_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `vn`.`priceFixed_beforeInsert` BEFORE INSERT ON `vn`.`priceFixed`
 FOR EACH ROW 
 BEGIN
	DECLARE vDated DATE;
	IF NEW.started > NEW.ended THEN
		SET vDated = NEW.started;
		SET NEW.started = NEW.ended;
		SET NEW.ended = vDated;
	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 `vn`.`priceFixed_beforeUpdate` BEFORE UPDATE ON `vn`.`priceFixed`
 FOR EACH ROW
BEGIN
	DECLARE vDated DATE;
	IF NEW.started > NEW.ended THEN
		SET vDated = NEW.started;
		SET NEW.started = NEW.ended;
		SET NEW.ended = vDated;
	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 `printServerQueue`
--

DROP TABLE IF EXISTS `printServerQueue`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `printServerQueue` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `printerFk` tinyint(3) unsigned DEFAULT NULL,
  `priorityFk` tinyint(3) unsigned DEFAULT NULL,
  `reportFk` tinyint(3) unsigned DEFAULT '0',
  `statusFk` tinyint(3) unsigned DEFAULT '1',
  `started` datetime DEFAULT NULL,
  `finished` datetime DEFAULT NULL,
  `param1` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `workerFk` int(11) DEFAULT '20',
  `param2` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `param3` text COLLATE utf8_unicode_ci,
  `error` text COLLATE utf8_unicode_ci,
  PRIMARY KEY (`id`),
  UNIQUE KEY `Id_Impresora_2` (`printerFk`,`priorityFk`,`reportFk`,`statusFk`,`param1`,`workerFk`,`param2`),
  KEY `Id_estado` (`statusFk`),
  KEY `Id_Impresora` (`printerFk`),
  KEY `Id_Informe` (`reportFk`),
  KEY `Id_Prioridad` (`priorityFk`),
  KEY `Id_Trabajador` (`workerFk`),
  CONSTRAINT `printServerQueue_ibfk_3` FOREIGN KEY (`priorityFk`) REFERENCES `queuePriority` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `printServerQueue_ibfk_4` FOREIGN KEY (`printerFk`) REFERENCES `vn2008`.`Impresoras` (`Id_Impresora`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `printServerQueue2`
--

DROP TABLE IF EXISTS `printServerQueue2`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `printServerQueue2` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `printerFk` tinyint(3) unsigned DEFAULT NULL,
  `priorityFk` tinyint(3) unsigned DEFAULT NULL,
  `reportFk` tinyint(3) unsigned DEFAULT '0',
  `statusFk` tinyint(3) unsigned DEFAULT '1',
  `started` datetime DEFAULT NULL,
  `finished` datetime DEFAULT NULL,
  `param1` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `workerFk` int(11) DEFAULT '20',
  `param2` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `param3` text COLLATE utf8_unicode_ci,
  `error` text COLLATE utf8_unicode_ci,
  PRIMARY KEY (`id`),
  UNIQUE KEY `Id_Impresora_2` (`printerFk`,`priorityFk`,`reportFk`,`statusFk`,`param1`,`workerFk`,`param2`),
  KEY `Id_estado` (`statusFk`),
  KEY `Id_Impresora` (`printerFk`),
  KEY `Id_Informe` (`reportFk`),
  KEY `Id_Prioridad` (`priorityFk`),
  KEY `Id_Trabajador` (`workerFk`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 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 */;

--
-- 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` (
  `id` mediumint(3) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `isVisible` tinyint(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `professionalCategory`
--

DROP TABLE IF EXISTS `professionalCategory`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `professionalCategory` (
  `id` int(11) NOT NULL,
  `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `salary` decimal(10,2) DEFAULT NULL,
  `salaryorSeniority` decimal(10,2) DEFAULT NULL,
  `year` int(2) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

DROP TABLE IF EXISTS `profile`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `profile` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `personFk` int(11) DEFAULT NULL,
  `profileTypeFk` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  KEY `personFk` (`personFk`),
  KEY `profileTypeFk` (`profileTypeFk`),
  CONSTRAINT `profile_ibfk_1` FOREIGN KEY (`personFk`) REFERENCES `person` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `profile_ibfk_2` FOREIGN KEY (`profileTypeFk`) REFERENCES `profileType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!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` (
  `id` smallint(6) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `countryFk` mediumint(8) unsigned NOT NULL,
  `warehouseFk` smallint(6) unsigned DEFAULT NULL COMMENT 'warehouse responsable de las rutas',
  `zoneFk` tinyint(4) DEFAULT NULL,
  `nstGeoFk` int(11) DEFAULT NULL,
  `nstName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `geoFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `Paises_Id` (`countryFk`),
  KEY `warehouse_Id` (`warehouseFk`),
  KEY `provicne_zone_fk_idx` (`zoneFk`),
  CONSTRAINT `province_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `province_zone_fk` FOREIGN KEY (`zoneFk`) REFERENCES `vn2008`.`zones` (`zone_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `warehouse_Id` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `vn`.`province_beforeInsert`
	BEFORE INSERT ON `province` FOR EACH ROW
BEGIN
    SET NEW.geoFk = zoneGeo_new('province', NEW.`name`,
		(SELECT geoFk FROM country WHERE id = NEW.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 SET @saved_cs_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 `vn`.`province_beforeUpdate` 
    BEFORE UPDATE ON `province` FOR EACH ROW 
BEGIN
	IF !(OLD.geoFk <=> NEW.geoFk) THEN
		CALL zoneGeo_throwNotEditable;
	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 `vn`.`province_afterUpdate`
	AFTER UPDATE ON `province` FOR EACH ROW
BEGIN
	IF !(OLD.countryFk <=> NEW.countryFk) THEN
		CALL zoneGeo_setParent(NEW.geoFk,
			(SELECT geoFk FROM country WHERE id = NEW.countryFk));
	END IF;

	IF !(OLD.`name` <=> NEW.`name`) THEN
		UPDATE zoneGeo SET `name` = NEW.`name`
			WHERE id = NEW.geoFk;
	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 `vn`.`province_afterDelete` 
    AFTER DELETE ON `province` FOR EACH ROW
BEGIN
	CALL zoneGeo_delete(OLD.geoFk); 
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `punchState`
--

DROP TABLE IF EXISTS `punchState`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `punchState` (
  `workerFk` int(11) NOT NULL,
  `state` tinyint(4) DEFAULT '0',
  PRIMARY KEY (`workerFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Table for storing punches that have cars with errors';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `queuePriority`
--

DROP TABLE IF EXISTS `queuePriority`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `queuePriority` (
  `id` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `priority` varchar(50) 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 `rateConfig`
--

DROP TABLE IF EXISTS `rateConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `rateConfig` (
  `id` int(11) NOT NULL,
  `rate0` int(11) DEFAULT NULL,
  `rate1` int(11) DEFAULT NULL,
  `rate2` int(11) DEFAULT NULL,
  `rate3` 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 `receipt`
--

DROP TABLE IF EXISTS `receipt`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `receipt` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `invoiceFk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `amountPaid` decimal(10,2) NOT NULL DEFAULT '0.00',
  `amountUnpaid` decimal(10,2) NOT NULL DEFAULT '0.00',
  `payed` datetime DEFAULT NULL,
  `workerFk` int(11) DEFAULT NULL,
  `bankFk` int(11) DEFAULT '0',
  `clientFk` int(11) DEFAULT '0',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `companyFk` smallint(5) unsigned NOT NULL DEFAULT '442',
  `isConciliate` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0',
  PRIMARY KEY (`Id`),
  KEY `Id_Banco` (`bankFk`),
  KEY `Id_Trabajador` (`workerFk`),
  KEY `empresa_id` (`companyFk`),
  KEY `clientDate` (`clientFk`,`payed`),
  KEY `id_factura` (`invoiceFk`),
  CONSTRAINT `receiptWorkerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `receipt_ibfk_1` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `receipt_ibfk_2` FOREIGN KEY (`bankFk`) REFERENCES `bank` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `recibo_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `vn`.`receipt_afterInsert` AFTER INSERT ON `receipt` FOR EACH ROW
	CALL bi.customer_risk_update (NEW.clientFk, NEW.companyFk, -NEW.amountPaid) */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `vn`.`receipt_beforeUpdate` BEFORE UPDATE ON `receipt` FOR EACH ROW
BEGIN
	CALL bi.customer_risk_update (OLD.clientFk, OLD.companyFk, OLD.amountPaid);
	CALL bi.customer_risk_update (NEW.clientFk, NEW.companyFk, -NEW.amountPaid);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `vn`.`receipt_beforeDelete` BEFORE DELETE ON `receipt` FOR EACH ROW
	CALL bi.customer_risk_update (OLD.clientFk, OLD.companyFk, OLD.amountPaid) */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `clientFk` int(11) NOT NULL DEFAULT '0',
  `started` date NOT NULL COMMENT 'Fecha a partir de la que comienza el recobro',
  `finished` 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 (`id`),
  KEY `cliente_idx` (`clientFk`),
  CONSTRAINT `cliente333` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `cliente_cliente` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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 `referenceCurrent`
--

DROP TABLE IF EXISTS `referenceCurrent`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `referenceCurrent` (
  `dated` date NOT NULL,
  `value` decimal(10,4) NOT NULL,
  `currencyFk` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`dated`,`currencyFk`),
  KEY `referenceCurrent_currencyFk _idx` (`currencyFk`),
  CONSTRAINT `referenceCurrent_currencyFk ` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`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 `referenceRate`
--

DROP TABLE IF EXISTS `referenceRate`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `referenceRate` (
  `currencyFk` tinyint(3) unsigned NOT NULL,
  `dated` date NOT NULL,
  `value` float unsigned NOT NULL,
  PRIMARY KEY (`currencyFk`,`dated`),
  KEY `date` (`dated`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 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;

--
-- 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` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `workerFk` int(11) DEFAULT NULL,
  `created` date NOT NULL,
  `vehicleFk` int(10) unsigned DEFAULT NULL,
  `agencyModeFk` int(11) DEFAULT NULL,
  `time` datetime DEFAULT NULL,
  `isOk` tinyint(1) unsigned NOT NULL DEFAULT '0',
  `kmStart` mediumint(9) NOT NULL,
  `kmEnd` mediumint(9) NOT NULL,
  `started` datetime NOT NULL,
  `finished` datetime NOT NULL,
  `gestdocFk` int(11) DEFAULT NULL,
  `cost` double unsigned DEFAULT NULL,
  `m3` decimal(10,1) unsigned DEFAULT NULL,
  `description` text COLLATE utf8_unicode_ci,
  `zoneFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `Id_Agencia` (`agencyModeFk`),
  KEY `Fecha` (`created`),
  KEY `gestdoc_id` (`gestdocFk`),
  KEY `route_ibfk_2_idx` (`workerFk`),
  KEY `fk_route_1_idx` (`zoneFk`),
  CONSTRAINT `fk_route_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `route_ibfk_1` FOREIGN KEY (`gestdocFk`) REFERENCES `dms` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `route_ibfk_2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `vn`.`route_beforeUpdate` 
	BEFORE UPDATE ON `route` FOR EACH ROW
BEGIN
	IF NEW.isOk <> FALSE AND OLD.isOk = FALSE THEN
			SET NEW.m3 = ( SELECT SUM(litros)/1000 
								FROM  vn.saleVolume s 
									JOIN vn.ticket t ON s.ticketFk = t.id 
								WHERE t.routeFk = 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 */ ;
/*!50003 SET @saved_cs_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 `vn`.`route_afterUpdate` 
	AFTER UPDATE ON `route` FOR EACH ROW
BEGIN
	IF IFNULL(NEW.gestdocFk,0) <> IFNULL(OLD.gestdocFk,0) AND NEW.gestdocFk > 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 ticketDms(ticketFk,dmsFk)
			SELECT id, NEW.gestdocFk FROM ticket WHERE routeFk = NEW.id
		ON DUPLICATE KEY UPDATE dmsFk = NEW.gestdocFk;

		-- Update del firmado 
		UPDATE ticket t 
            JOIN ticketDms tg ON t.id = tg.ticketFk 
			SET isSigned = 1  WHERE t.routeFk = 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 `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=InnoDBDEFAULT 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 `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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 `route` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `frmWorker` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `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 `route` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `routeLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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,
  `m3Management` decimal(10,2) 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `routeUserPercentage`
--

DROP TABLE IF EXISTS `routeUserPercentage`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `routeUserPercentage` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `workerFk` int(11) NOT NULL,
  `percentage` decimal(10,2) NOT NULL,
  `dated` date NOT NULL,
  PRIMARY KEY (`id`),
  KEY `routeUserPercentageFk_idx` (`workerFk`),
  CONSTRAINT `routeUserPercentageFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `sale`
--

DROP TABLE IF EXISTS `sale`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sale` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `itemFk` int(11) NOT NULL,
  `ticketFk` int(11) NOT NULL,
  `concept` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `quantity` decimal(10,2) NOT NULL DEFAULT '0.00',
  `originalQuantity` double(9,1) DEFAULT NULL,
  `price` decimal(10,2) DEFAULT '0.00',
  `discount` tinyint(2) unsigned NOT NULL DEFAULT '0',
  `priceFixed` decimal(10,2) NOT NULL DEFAULT '0.00',
  `reserved` tinyint(1) NOT NULL DEFAULT '0',
  `isPicked` tinyint(1) NOT NULL DEFAULT '0',
  `isPriceFixed` tinyint(1) NOT NULL DEFAULT '0',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `Id_Ticket` (`ticketFk`),
  KEY `itemFk_ticketFk` (`itemFk`,`ticketFk`),
  CONSTRAINT `movement_ticket_id` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `sale_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `sale`
    FOR EACH ROW
BEGIN	
	CALL stock.log_add('sale', NEW.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 */ ;
/*!50003 SET @saved_cs_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 `sale`
    FOR EACH ROW
BEGIN

	IF NEW.discount > 100 THEN
		SET NEW.discount = 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 `sale`
    FOR EACH ROW
BEGIN	
    IF !(NEW.id <=> OLD.id)
    OR !(NEW.ticketFk <=> OLD.ticketFk)
    OR !(NEW.itemFk <=> OLD.itemFk)
    OR !(NEW.quantity <=> OLD.quantity)
    OR !(NEW.created <=> OLD.created)
    OR !(NEW.isPicked <=> OLD.isPicked) THEN
		CALL stock.log_add('sale', NEW.id, OLD.id);
	END IF;

	IF !(OLD.ticketFk <=> NEW.ticketFk) THEN
		UPDATE ticketRequest SET ticketFk = NEW.ticketFk
			WHERE saleFk = 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 */ ;
/*!50003 SET @saved_cs_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 `sale`
    FOR EACH ROW
BEGIN	
    CALL stock.log_add('sale', NULL, 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 `saleChecked`
--

DROP TABLE IF EXISTS `saleChecked`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `saleChecked` (
  `saleFk` int(11) NOT NULL,
  `isChecked` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`saleFk`),
  CONSTRAINT `fk_Movimientos_checked_1` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`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 `saleComponent`
--

DROP TABLE IF EXISTS `saleComponent`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `saleComponent` (
  `saleFk` int(11) NOT NULL,
  `componentFk` int(11) NOT NULL,
  `value` double NOT NULL,
  `isGreuge` tinyint(4) NOT NULL DEFAULT '0',
  `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`saleFk`,`componentFk`),
  KEY `fk_mov_comp_idx` (`componentFk`),
  CONSTRAINT `mc_fk1` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `mc_fk2` FOREIGN KEY (`componentFk`) 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 */;

--
-- Temporary table structure for view `saleFreight`
--

DROP TABLE IF EXISTS `saleFreight`;
/*!50001 DROP VIEW IF EXISTS `saleFreight`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `saleFreight` AS SELECT 
 1 AS `ticketFk`,
 1 AS `clientFk`,
 1 AS `routeFk`,
 1 AS `saleFk`,
 1 AS `zoneFk`,
 1 AS `companyFk`,
 1 AS `shipped`,
 1 AS `price`,
 1 AS `freight`,
 1 AS `volume`*/;
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=InnoDBDEFAULT 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 `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `saleState_fk2` FOREIGN KEY (`stateFk`) REFERENCES `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 */;

--
-- Table structure for table `saleTracking`
--

DROP TABLE IF EXISTS `saleTracking`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `saleTracking` (
  `saleFk` int(11) NOT NULL,
  `isChecked` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `originalQuantity` double DEFAULT NULL,
  `workerFk` int(11) NOT NULL,
  `actionFk` int(11) DEFAULT NULL,
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `stateFk` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `stateFk_UNIQUE` (`stateFk`,`saleFk`),
  KEY `Id_Movimiento` (`saleFk`),
  KEY `fgnStateFk_idx` (`stateFk`),
  KEY `saleTracking_idx5` (`created`),
  KEY `saleTracking_fk2_idx` (`actionFk`),
  CONSTRAINT `fgnStateFk` FOREIGN KEY (`stateFk`) REFERENCES `state` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `saleTracking_fk2` FOREIGN KEY (`actionFk`) REFERENCES `vncontrol`.`accion` (`accion_id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `vn`.`saleTracking_beforeInsert` BEFORE INSERT ON `saleTracking` FOR EACH ROW
BEGIN
	IF(NEW.stateFk = 14) THEN
		SET NEW.actionFk = 3;
	END IF;

	IF(NEW.stateFk = 8) THEN
		SET NEW.actionFk = 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 */ ;

--
-- Temporary table structure for view `saleValue`
--

DROP TABLE IF EXISTS `saleValue`;
/*!50001 DROP VIEW IF EXISTS `saleValue`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `saleValue` AS SELECT 
 1 AS `warehouse`,
 1 AS `client`,
 1 AS `clientTypeFk`,
 1 AS `buyer`,
 1 AS `family`,
 1 AS `itemFk`,
 1 AS `concept`,
 1 AS `quantity`,
 1 AS `cost`,
 1 AS `value`,
 1 AS `year`,
 1 AS `week`*/;
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 `ticketFk`,
 1 AS `saleFk`,
 1 AS `litros`,
 1 AS `routeFk`,
 1 AS `shipped`,
 1 AS `volume`,
 1 AS `physicalWeight`,
 1 AS `weight`,
 1 AS `physicalVolume`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `sample`
--

DROP TABLE IF EXISTS `sample`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sample` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `code` varchar(20) CHARACTER SET utf8 NOT NULL,
  `description` varchar(105) COLLATE utf8_unicode_ci NOT NULL,
  `isVisible` tinyint(4) NOT NULL DEFAULT '1',
  `hasCompany` varchar(45) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 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',
  `isPreviousPreparedByPacking` tinyint(4) NOT NULL DEFAULT '1',
  `code` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `pickingPlacement` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `path` int(11) DEFAULT NULL,
  `isPreviousPrepared` tinyint(1) NOT NULL DEFAULT '0',
  `isPackagingArea` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`,`warehouseFk`),
  UNIQUE KEY `code_UNIQUE` (`code`),
  KEY `sector_fk1_idx` (`warehouseFk`),
  CONSTRAINT `sector_fk1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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,
  `workerFk` int(11) NOT NULL,
  `started` date NOT NULL,
  `ended` date NOT NULL,
  `workerSubstitute` int(11) NOT NULL,
  `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `Worker` (`workerFk`),
  KEY `Suplent` (`workerSubstitute`),
  CONSTRAINT `Suplent_key` FOREIGN KEY (`workerSubstitute`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `Trabajador_key` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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`.`sharingCart_beforeInsert` BEFORE INSERT ON `sharingCart` FOR EACH ROW

BEGIN
	IF NEW.workerFk = NEW.workerSubstitute THEN
		CALL util.throw ('worker and workerSubstitute must be different');
	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 `vn`.`sharingCart_beforeUpdate` BEFORE UPDATE ON `sharingCart` FOR EACH ROW
BEGIN
	IF NEW.workerFk = NEW.workerSubstitute THEN
		CALL util.throw ('worker and workerSubstitute must be different');
	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 `sharingCartDaily`
--

DROP TABLE IF EXISTS `sharingCartDaily`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sharingCartDaily` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ownerFk` int(11) NOT NULL,
  `substituteFk` int(11) NOT NULL,
  `dated` date NOT NULL,
  `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `sharingCartDailyWorker_idx` (`ownerFk`,`dated`),
  KEY `sharingCartDailySubstitute_idx` (`substituteFk`),
  CONSTRAINT `sharingCartDailySubstitute` FOREIGN KEY (`substituteFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `sharingCartDailyWorker` FOREIGN KEY (`ownerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='para calcular las comisiones de las sustituciones de los comerciales';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- 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,
  `workerFk` int(11) NOT NULL,
  `started` date NOT NULL,
  `ended` date NOT NULL,
  `clientFk` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `Worker` (`workerFk`),
  KEY `Client` (`clientFk`),
  CONSTRAINT `Clients_key` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `Trabajadores_key` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `vn`.`sharingClient_beforeInsert` BEFORE INSERT ON `sharingClient` FOR EACH ROW
BEGIN
	SET NEW.ended = GREATEST(CURDATE(),NEW.ended);
	SET NEW.started = GREATEST(CURDATE(),NEW.started);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `vn`.`sharingClient_beforeUpdate` BEFORE UPDATE ON `sharingClient` FOR EACH ROW
BEGIN
	SET NEW.ended = GREATEST(CURDATE(),NEW.ended);
	SET NEW.started = GREATEST(CURDATE(),NEW.started);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `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 ON UPDATE 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
    
		UPDATE item i 
			JOIN itemShelving ish ON ish.itemFk = i.id
            JOIN shelving sh ON sh.code = ish.shelvingFk
            JOIN parking p ON p.id = sh.parkingFk
            SET i.sectorFk = p.sectorFk
            WHERE sh.`code` = OLD.`code`;
        
    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=InnoDBDEFAULT 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='SMS configuration parameters';
/*!40101 SET character_set_client = @saved_cs_client */;

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

DROP TABLE IF EXISTS `solunionCAP`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `solunionCAP` (
  `creditInsurance` int(11) NOT NULL,
  `dateStart` date NOT NULL,
  `dateEnd` date NOT NULL,
  `dateLeaving` date DEFAULT NULL,
  PRIMARY KEY (`creditInsurance`,`dateStart`),
  KEY `solunionCAPdateLeavingIdx` (`dateLeaving`),
  CONSTRAINT `solunionCAP` FOREIGN KEY (`creditInsurance`) REFERENCES `creditInsurance` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`solunionCAP_AFTER_INSERT` AFTER INSERT ON `solunionCAP` FOR EACH ROW
BEGIN
	UPDATE vn2008.Clientes c
		JOIN creditClassification cc ON c.Id_Cliente = cc.client 
		JOIN creditInsurance ci ON ci.creditClassification = cc.id
	SET creditInsurance = ci.credit * 2 WHERE ci.id = NEW.creditInsurance;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`solunionCAP_AFTER_UPDATE` AFTER UPDATE ON `solunionCAP` FOR EACH ROW
BEGIN
	IF NEW.dateLeaving IS NOT NULL THEN
		UPDATE vn2008.Clientes c
			JOIN creditClassification cc ON c.Id_Cliente = cc.client 
			JOIN creditInsurance ci ON ci.creditClassification = cc.id
		SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance;
	ELSE
		UPDATE vn2008.Clientes c
			JOIN creditClassification cc ON c.Id_Cliente = cc.client 
			JOIN creditInsurance ci ON ci.creditClassification = cc.id
		SET creditInsurance = ci.credit * 2 WHERE ci.id = OLD.creditInsurance;
	END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`solunionCAP_BEFORE_DELETE` BEFORE DELETE ON `solunionCAP` FOR EACH ROW
BEGIN
	UPDATE vn2008.Clientes c
		JOIN creditClassification cc ON c.Id_Cliente = cc.client 
		JOIN creditInsurance ci ON ci.creditClassification = cc.id
	SET creditInsurance = ci.credit  WHERE ci.id = OLD.creditInsurance;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;

--
-- Table structure for table `specialPrice`
--

DROP TABLE IF EXISTS `specialPrice`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `specialPrice` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `clientFk` int(11) NOT NULL DEFAULT '0',
  `itemFk` int(11) NOT NULL DEFAULT '0',
  `value` double NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `Id_Cliente_2` (`clientFk`,`itemFk`),
  KEY `Id_Article` (`itemFk`),
  KEY `Id_Cliente` (`clientFk`),
  CONSTRAINT `sp_article_id` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `sp_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `{01A99AF1-3D3F-4B15-AC0C-C7A834F319A3}` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `{EE4ADEF6-0AC6-401F-B7C4-D797972FC065}` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 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,
  `alertLevel` int(11) NOT NULL DEFAULT '0',
  `code` varchar(45) CHARACTER SET utf8 NOT NULL,
  `sectorProdPriority` tinyint(3) DEFAULT NULL,
  `nextStateFk` tinyint(4) NOT NULL COMMENT 'Estado al que tiene que cambiar el ticket despues de preparacion previa',
  `isPreviousPreparable` tinyint(1) NOT NULL DEFAULT '0',
  `isPicked` tinyint(1) NOT NULL DEFAULT '0',
  `isPreparable` tinyint(1) NOT NULL DEFAULT '0',
  `semaphore` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `code_UNIQUE` (`code`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 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=InnoDBDEFAULT 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 */;

--
-- 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` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `account` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `street` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `postCode__` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'deprecada',
  `city` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `provinceFk` smallint(5) unsigned DEFAULT NULL,
  `countryFk` mediumint(8) unsigned DEFAULT NULL,
  `nif` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `isOfficial` tinyint(1) NOT NULL DEFAULT '1',
  `isFarmer` tinyint(1) NOT NULL DEFAULT '0',
  `retAccount` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `phone` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Fax` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL,
  `commission` float NOT NULL DEFAULT '0',
  `nickname` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `payMethodFk` tinyint(3) unsigned NOT NULL,
  `payDay` tinyint(4) unsigned DEFAULT NULL,
  `payDemFk` tinyint(3) unsigned NOT NULL DEFAULT '7',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `isSerious` tinyint(1) unsigned zerofill DEFAULT '1',
  `note` text COLLATE utf8_unicode_ci,
  `postcodeFk` int(11) unsigned DEFAULT NULL,
  `postCode` char(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `isActive` tinyint(4) DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `cuenta` (`account`),
  UNIQUE KEY `NIF` (`nif`),
  KEY `pais_id` (`countryFk`),
  KEY `pay_met_id` (`payMethodFk`),
  KEY `province_id` (`provinceFk`),
  KEY `pay_dem_id` (`payDemFk`),
  KEY `codpos` (`postCode`,`postCode__`),
  CONSTRAINT `Id_Pais` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `pay_dem_id` FOREIGN KEY (`payDemFk`) REFERENCES `payDem` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `pay_met_id` FOREIGN KEY (`payMethodFk`) REFERENCES `payMethod` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `province_id` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `supplierAccount`
--

DROP TABLE IF EXISTS `supplierAccount`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `supplierAccount` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `supplierFk` 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 COMMENT 'obsoleta(comprobar)',
  `bicSufix` varchar(3) CHARACTER SET utf8 NOT NULL DEFAULT '',
  `bankEntityFk` int(10) DEFAULT NULL,
  `bankFk` int(11) DEFAULT NULL COMMENT 'obsoleta(comprobar)',
  PRIMARY KEY (`id`),
  KEY `fk_proveedores_proveedores_account_idx` (`supplierFk`),
  KEY `fk_Proveedores_account_entity1_idx` (`bankEntityFk`),
  KEY `fk_banco_prov_account_idx` (`bankFk`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `supplierExpense`
--

DROP TABLE IF EXISTS `supplierExpense`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `supplierExpense` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `dated` date NOT NULL,
  `supplierFk` int(11) NOT NULL,
  `currencyFk` tinyint(3) unsigned NOT NULL DEFAULT '2',
  `amount` decimal(10,2) NOT NULL DEFAULT '0.00',
  `description` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `companyFk` smallint(5) unsigned NOT NULL DEFAULT '442',
  `dmsFk` int(11) DEFAULT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `isConciliated` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0',
  `dueDated` date NOT NULL,
  PRIMARY KEY (`id`),
  KEY `empresa_id` (`companyFk`),
  KEY `supplierExDated` (`dated`),
  KEY `id_moneda` (`currencyFk`),
  KEY `proveedor_pago` (`supplierFk`),
  KEY `gestdoc_id` (`dmsFk`),
  KEY `dueDatedIdx` (`dueDated`),
  CONSTRAINT `gestdoc_fk` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `pago_ibfk_1` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `pago_moneda` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `proveedor_pago` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 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 `tablet`
--

DROP TABLE IF EXISTS `tablet`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tablet` (
  `uuid` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `place` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `macwifi` varchar(45) COLLATE utf8_unicode_ci DEFAULT '0',
  PRIMARY KEY (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `tabletDepartment`
--

DROP TABLE IF EXISTS `tabletDepartment`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tabletDepartment` (
  `tabletFk` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `departmentFk` int(11) NOT NULL,
  PRIMARY KEY (`tabletFk`,`departmentFk`),
  KEY `departmentFk_idx` (`departmentFk`),
  CONSTRAINT `departmentFk` FOREIGN KEY (`departmentFk`) REFERENCES `department` (`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 `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,
  `code` varchar(45) CHARACTER SET utf8 NOT NULL,
  `name` varchar(25) CHARACTER SET utf8 NOT NULL,
  `isFree` tinyint(1) NOT NULL DEFAULT '1',
  `isQuantitatif` tinyint(4) NOT NULL DEFAULT '0',
  `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=InnoDBDEFAULT 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 */;

--
-- Table structure for table `taxClass`
--

DROP TABLE IF EXISTS `taxClass`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `taxClass` (
  `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 (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `taxClassCode`
--

DROP TABLE IF EXISTS `taxClassCode`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `taxClassCode` (
  `taxClassFk` tinyint(3) unsigned NOT NULL,
  `effectived` date NOT NULL,
  `taxCodeFk` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`taxClassFk`,`effectived`,`taxCodeFk`),
  KEY `iva_codigo_id` (`taxCodeFk`),
  CONSTRAINT `taxClassCode_ibfk_1` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `taxClassCode_ibfk_2` FOREIGN KEY (`taxCodeFk`) REFERENCES `taxCode` (`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 `taxCode`
--

DROP TABLE IF EXISTS `taxCode`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `taxCode` (
  `id` tinyint(2) unsigned NOT NULL AUTO_INCREMENT,
  `dated` date NOT NULL,
  `code` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `taxTypeFk` tinyint(2) NOT NULL,
  `rate` decimal(4,1) NOT NULL DEFAULT '0.0',
  `equalizationTax` decimal(4,1) NOT NULL DEFAULT '0.0',
  `type` 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` (`taxTypeFk`),
  KEY `codigo` (`code`),
  KEY `tipo_index` (`type`),
  CONSTRAINT `taxCode_ibfk_1` FOREIGN KEY (`taxTypeFk`) REFERENCES `taxType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `taxType`
--

DROP TABLE IF EXISTS `taxType`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `taxType` (
  `id` tinyint(2) NOT NULL AUTO_INCREMENT,
  `nickname` varchar(6) COLLATE utf8_unicode_ci NOT NULL,
  `isAccrued` tinyint(4) NOT NULL DEFAULT '0',
  `serial` char(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `TIPOOPE` varchar(1) COLLATE utf8_unicode_ci NOT NULL DEFAULT ' ' COMMENT 'respetar el nombre de la columna, se utiliza en contaplus',
  `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `countryFk` mediumint(8) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `serie_id` (`serial`),
  KEY `Id_Pais` (`countryFk`),
  CONSTRAINT `taxType_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!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` (
  `id` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `model` enum('TL30','SENSITECH','TREKVIEW1','TREKVIEW2','DISPOSABLE','TEMPMATE') 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 `ticket`
--

DROP TABLE IF EXISTS `ticket`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticket` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `clientFk` int(11) NOT NULL DEFAULT '0',
  `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '1',
  `shipped` datetime NOT NULL,
  `nickname` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `notes` longtext COLLATE utf8_unicode_ci,
  `refFk` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `invoiceOutFk` int(10) unsigned DEFAULT NULL COMMENT 'eliminar',
  `isBooked` tinyint(1) NOT NULL DEFAULT '0',
  `addressFk` int(11) NOT NULL DEFAULT '0',
  `workerFk` int(11) DEFAULT NULL,
  `observations` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'eliminar',
  `isSigned` tinyint(1) NOT NULL DEFAULT '0',
  `isLabeled` tinyint(1) NOT NULL DEFAULT '0',
  `isPrinted` tinyint(1) NOT NULL DEFAULT '0',
  `packages` smallint(10) unsigned DEFAULT '0',
  `location` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `hour` int(11) DEFAULT '0',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `isBlocked` tinyint(1) NOT NULL DEFAULT '1',
  `solution` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `routeFk` int(10) unsigned DEFAULT NULL,
  `priority` tinyint(3) unsigned DEFAULT NULL,
  `hasPriority` tinyint(1) unsigned NOT NULL DEFAULT '1',
  `companyFk` smallint(5) unsigned NOT NULL DEFAULT '442',
  `agencyModeFk` int(11) DEFAULT NULL,
  `landed` date DEFAULT NULL,
  `isBoxed` tinyint(2) NOT NULL DEFAULT '0',
  `isDeleted` tinyint(2) NOT NULL DEFAULT '0',
  `zoneFk` int(11) DEFAULT NULL,
  `collectionFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `Id_Cliente` (`clientFk`),
  KEY `Id_Consigna` (`addressFk`),
  KEY `Id_Trabajador` (`workerFk`),
  KEY `warehouse_id` (`warehouseFk`),
  KEY `empresa_id` (`companyFk`),
  KEY `Id_Agencia` (`agencyModeFk`),
  KEY `Factura` (`refFk`),
  KEY `Id_Ruta` (`routeFk`),
  KEY `warehouse_date` (`warehouseFk`,`shipped`),
  KEY `Fecha` (`shipped`,`clientFk`),
  KEY `tickets_zone_fk_idx` (`zoneFk`),
  KEY `tickets_fk11_idx` (`collectionFk`),
  CONSTRAINT `ticket_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `ticket_ibfk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `ticket_ibfk_5` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `ticket_ibfk_6` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `ticket_ibfk_8` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`),
  CONSTRAINT `ticket_ibfk_9` FOREIGN KEY (`routeFk`) REFERENCES `route` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `tickets_fk10` FOREIGN KEY (`refFk`) REFERENCES `invoiceOut` (`ref`) ON UPDATE CASCADE,
  CONSTRAINT `tickets_fk11` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `tickets_zone_fk` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `ticket`
    FOR EACH ROW
BEGIN
	DECLARE vClientType VARCHAR(255);
	DECLARE vStateCode VARCHAR(255);
	
	-- Borrar cuando se cambie el insert ticket en la APP móvil

    SELECT typeFk INTO vClientType
		FROM vn.`client` WHERE id = NEW.clientFk;

	IF vClientType = 'loses' THEN
		SET vStateCode = 'DELIVERED';
	ELSE
		SET vStateCode = 'FREE';
	END IF;

	INSERT INTO vncontrol.inter(Id_Ticket, state_id, Id_Trabajador)
		SELECT NEW.id, id, vn.myWorker_getId() 
			FROM state 
			WHERE `code` = vStateCode COLLATE utf8_general_ci;
            
	-- Borrar al acabar el proceso de cambio de nichos a carros
  /*  IF NEW.warehouseFk IN (1,44) THEN

		INSERT INTO vn.ticketObservation(ticketFk, description, observationTypeFk)
			VALUES(NEW.id,'NO OLVIDES ESCANEAR LAS MATRICULAS',1)
            ON DUPLICATE KEY UPDATE description = CONCAT(description,'. Y NO OLVIDES ESCANEAR LAS MATRICULAS');
    
    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 `ticket`
    FOR EACH ROW
BEGIN
	IF !(NEW.shipped <=> OLD.shipped) THEN
		IF YEAR(NEW.shipped) < 2000 THEN
			SIGNAL SQLSTATE '46000'
				SET MESSAGE_TEXT = 'Year cannot be lesser than 2000';
		END IF;

		IF YEAR(NEW.shipped) = 2000 THEN
			SET NEW.isDeleted = TRUE;
		END IF;
	END IF;
	
	IF !(NEW.isDeleted <=> OLD.isDeleted) AND NEW.isDeleted THEN
		SET NEW.shipped = DATE_FORMAT(NEW.shipped, '2000-%m-%d %T');
		SET NEW.landed = DATE_FORMAT(NEW.landed, '2000-%m-%d %T');
		SET NEW.routeFk = 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  = 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_afterUpdate`
	AFTER UPDATE ON `ticket`
    FOR EACH ROW
BEGIN
    IF !(NEW.id <=> OLD.id)
    OR !(NEW.warehouseFk <=> OLD.warehouseFk)
    OR !(NEW.shipped <=> OLD.shipped) THEN
		CALL stock.log_add('ticket', NEW.id, OLD.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 `ticket_beforeDelete`
	BEFORE DELETE ON `ticket`
    FOR EACH ROW
BEGIN	
	DELETE FROM sale WHERE ticketFk = OLD.id;

    DELETE FROM ticketDms WHERE ticketFk = 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 `ticketCollection`
--

DROP TABLE IF EXISTS `ticketCollection`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketCollection` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ticketFk` int(11) NOT NULL,
  `collectionFk` int(11) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `level` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `ticketCollection_fk1_idx` (`collectionFk`),
  KEY `ticketCollection_fk2_idx` (`ticketFk`),
  CONSTRAINT `ticketCollection_fk1` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `ticketCollection_fk2` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `ticketDms`
--

DROP TABLE IF EXISTS `ticketDms`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketDms` (
  `ticketFk` int(11) NOT NULL,
  `dmsFk` int(11) NOT NULL,
  PRIMARY KEY (`ticketFk`,`dmsFk`),
  KEY `gestdoc_id` (`dmsFk`),
  CONSTRAINT `ticketDms_dmsFk` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `ticketDms_ticketFk` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) 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  = 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 `vn`.`ticketDms_beforeDelete` BEFORE DELETE ON `ticketDms` FOR EACH ROW
BEGIN
    UPDATE dms 
        SET dmsTypeFk = (SELECT id FROM dmsType WHERE `code` = 'trash')
    WHERE id = OLD.dmsFk;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `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`),
  KEY `created_idx` (`created`),
  KEY `selected_idx` (`selected`),
  CONSTRAINT `ticketDown_fk1` FOREIGN KEY (`selected`) REFERENCES `ticketDown_SelectionType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) 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 */;

--
-- Table structure for table `ticketDown_SelectionType`
--

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

--
-- Temporary table structure for view `ticketGetVolume__`
--

DROP TABLE IF EXISTS `ticketGetVolume__`;
/*!50001 DROP VIEW IF EXISTS `ticketGetVolume__`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketGetVolume__` AS SELECT 
 1 AS `ticketFk`,
 1 AS `routeFk`,
 1 AS `saleFk`,
 1 AS `shipped`,
 1 AS `volume`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `ticketLastState`
--

DROP TABLE IF EXISTS `ticketLastState`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketLastState` (
  `ticketFk` int(11) NOT NULL DEFAULT '0',
  `ticketTrackingFk` int(11) NOT NULL,
  `name` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`ticketFk`),
  KEY `double_foreign` (`ticketFk`,`ticketTrackingFk`),
  CONSTRAINT `Id_Ticket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `double_foreign` FOREIGN KEY (`ticketFk`, `ticketTrackingFk`) 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 `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 `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `ticketLog_user` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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;

--
-- Table structure for table `ticketObservation`
--

DROP TABLE IF EXISTS `ticketObservation`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketObservation` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `ticketFk` int(11) NOT NULL,
  `observationTypeFk` tinyint(3) unsigned NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `Id_Ticket` (`ticketFk`,`observationTypeFk`),
  KEY `observation_type_id` (`observationTypeFk`),
  CONSTRAINT `ticketObservation_ibfk_1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `ticketObservation_ibfk_2` FOREIGN KEY (`observationTypeFk`) REFERENCES `observationType` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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 `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 `ticket` (`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 `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 `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `ticketPackaging_fk2` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `ticketPackaging_fk3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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 `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `ticketPackagingStartingStock_fk2` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `ticketPackagingStartingStock_fk3` FOREIGN KEY (`itemFk`) REFERENCES `item` (`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 `ticketParking`
--

DROP TABLE IF EXISTS `ticketParking`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketParking` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ticketFk` int(11) NOT NULL,
  `parkingFk` int(11) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `ticketParking_idx1` (`ticketFk`,`parkingFk`),
  UNIQUE KEY `ticketFk_UNIQUE` (`ticketFk`),
  KEY `ticketParking_fk1_idx` (`parkingFk`),
  CONSTRAINT `ticketParking_fk1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `ticketParking_fk2` FOREIGN KEY (`parkingFk`) REFERENCES `parking` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los distintos lugares donde puede estar aparcado cada uno de los prepedidos';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary table structure for view `ticketPreviousPreparingList`
--

DROP TABLE IF EXISTS `ticketPreviousPreparingList`;
/*!50001 DROP VIEW IF EXISTS `ticketPreviousPreparingList`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketPreviousPreparingList` AS SELECT 
 1 AS `ticketFk`,
 1 AS `code`,
 1 AS `saleLines`,
 1 AS `alreadyMadeSaleLines`,
 1 AS `madeRate`,
 1 AS `created`,
 1 AS `sectorFk`,
 1 AS `parking`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `ticketRequest`
--

DROP TABLE IF EXISTS `ticketRequest`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketRequest` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ordered` datetime DEFAULT NULL,
  `shipped` datetime DEFAULT NULL,
  `salesPersonCode` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `buyerCode` varchar(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'NOE',
  `quantity` int(11) DEFAULT NULL,
  `price` double DEFAULT NULL,
  `price__` double DEFAULT NULL,
  `itemFk` double DEFAULT NULL,
  `clientFk` int(11) DEFAULT NULL,
  `response` longtext COLLATE utf8_unicode_ci,
  `ok__` tinyint(1) NOT NULL DEFAULT '0',
  `total` int(11) DEFAULT NULL,
  `buyed` datetime DEFAULT NULL,
  `ko__` tinyint(1) NOT NULL DEFAULT '0',
  `saleFk` int(11) DEFAULT NULL,
  `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `isOk` tinyint(1) DEFAULT NULL,
  `requesterFk` int(11) DEFAULT NULL,
  `attenderFk` int(11) DEFAULT NULL,
  `ticketFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `Id_Movimiento_UNIQUE` (`saleFk`),
  KEY `Id_ARTICLE` (`itemFk`),
  KEY `Id_CLIENTE` (`clientFk`),
  KEY `Id_Comprador` (`buyerCode`),
  KEY `Id_Movimiento` (`saleFk`),
  KEY `Id_Vendedor` (`salesPersonCode`),
  KEY `fgnRequester_idx` (`requesterFk`),
  KEY `fgnAtender_idx` (`attenderFk`),
  KEY `fgnTicket_idx` (`ticketFk`),
  CONSTRAINT `fgbMovimiento` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `fgnAtender` FOREIGN KEY (`attenderFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `fgnRequester` FOREIGN KEY (`requesterFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `fgnTicket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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`.`ticketRequest_beforeInsert` BEFORE INSERT ON `ticketRequest` FOR EACH ROW
BEGIN
    IF NEW.ticketFk IS NULL THEN
        SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk);
    END IF;

    IF NEW.requesterFk IS NULL THEN
        SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode);
    END IF;

    IF NEW.attenderFk IS NULL THEN
        SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode);
    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 `vn`.`ticketRequest_beforeUpdate` BEFORE UPDATE ON `ticketRequest` FOR EACH ROW
BEGIN
    IF NEW.saleFk <> OLD.saleFk THEN
        SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk);
    END IF;

    IF NEW.salesPersonCode <> OLD.salesPersonCode THEN
        SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode);
    END IF;

    IF NEW.buyerCode <> OLD.buyerCode THEN
        SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode);
    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 `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,
  `ticketServiceTypeFk` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `ticketServiceIvaGroup_idx` (`taxClassFk`),
  KEY `fgn_ticketFk_idx` (`ticketFk`),
  KEY `ticketService_ticketServiceType_idx` (`ticketServiceTypeFk`),
  CONSTRAINT `fgn_ticketFk` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `ticketServiceIvaGroup` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `ticketService_ticketServiceType` FOREIGN KEY (`ticketServiceTypeFk`) REFERENCES `ticketServiceType` (`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) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `expenceFk` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '7001000000',
  PRIMARY KEY (`id`),
  KEY `ticketServiceType_expence_idx` (`expenceFk`),
  CONSTRAINT `ticketServiceType_expence` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 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`,
 1 AS `isPreviousPreparable`,
 1 AS `isPicked`*/;
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`,
 1 AS `isPicked`*/;
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 `ticket` (`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 `ticketUpdateAction`
--

DROP TABLE IF EXISTS `ticketUpdateAction`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketUpdateAction` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT 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 `ticketWeekly`
--

DROP TABLE IF EXISTS `ticketWeekly`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketWeekly` (
  `ticketFk` int(11) NOT NULL AUTO_INCREMENT,
  `weekDay` tinyint(1) DEFAULT NULL COMMENT 'funcion de mysql Lunes = 0, Domingo = 6',
  PRIMARY KEY (`ticketFk`),
  CONSTRAINT `Id_Ticket_fk` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `till`
--

DROP TABLE IF EXISTS `till`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `till` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dated` date NOT NULL,
  `isAccountable` tinyint(1) NOT NULL DEFAULT '0',
  `serie` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL,
  `number` int(11) DEFAULT NULL,
  `concept` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `in` decimal(10,2) DEFAULT NULL,
  `out` decimal(10,2) DEFAULT NULL,
  `bankFk` int(11) DEFAULT '1',
  `workerFk` int(11) DEFAULT NULL,
  `companyFk` smallint(5) unsigned DEFAULT '442' COMMENT 'kakear',
  `isLinked` tinyint(4) DEFAULT '0',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `isOk` tinyint(4) NOT NULL DEFAULT '0',
  `warehouseFk` smallint(5) unsigned NOT NULL DEFAULT '1' COMMENT 'to kak\\n',
  `isConciliate` tinyint(4) NOT NULL DEFAULT '0',
  `supplierAccountFk` mediumint(8) unsigned NOT NULL,
  `calculatedCode` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `InForeignValue` decimal(10,2) DEFAULT NULL,
  `OutForeignValue` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_calculated_UNIQUE` (`calculatedCode`),
  KEY `CajasCajafecha` (`dated`),
  KEY `Id_Banco` (`bankFk`),
  KEY `Id_Trabajador` (`workerFk`),
  KEY `empresa_id` (`companyFk`),
  KEY `warehouse_id` (`warehouseFk`),
  KEY `fk_Cajas_Proveedores_account1_idx` (`supplierAccountFk`),
  CONSTRAINT `till_ibfk_2` FOREIGN KEY (`bankFk`) REFERENCES `bank` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `till_ibfk_3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `vn`.`till_beforeInsert` BEFORE INSERT ON `till` FOR EACH ROW
BEGIN
	IF IFNULL(NEW.concept,"") = "" 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 `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 */;

--
-- Table structure for table `town`
--

DROP TABLE IF EXISTS `town`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `town` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `provinceFk` smallint(6) unsigned NOT NULL,
  `geoFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `name_idx` (`name`),
  KEY `townProvinceFk` (`provinceFk`),
  CONSTRAINT `townProvinceFk` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `vn`.`town_beforeInsert`
	BEFORE INSERT ON `town` FOR EACH ROW
BEGIN
    SET NEW.geoFk = zoneGeo_new('town', NEW.`name`,
		(SELECT geoFk FROM province WHERE id = NEW.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 SET @saved_cs_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 `town_beforeUpdate`
	BEFORE UPDATE ON `town` FOR EACH ROW
BEGIN
	IF !(OLD.geoFk <=> NEW.geoFk) THEN
		CALL zoneGeo_throwNotEditable;
	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 `vn`.`town_afterUpdate`
	AFTER UPDATE ON `town` FOR EACH ROW
BEGIN
	IF !(OLD.provinceFk <=> NEW.provinceFk) THEN
		CALL zoneGeo_setParent(NEW.geoFk,
			(SELECT geoFk FROM province WHERE id = NEW.provinceFk));
	END IF;

	IF !(OLD.`name` <=> NEW.`name`) THEN
		UPDATE zoneGeo SET `name` = NEW.`name`
			WHERE id = NEW.geoFk;
	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 `vn`.`town_afterDelete`
	AFTER DELETE ON `town` FOR EACH ROW
BEGIN
	CALL zoneGeo_delete(OLD.geoFk);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `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=InnoDBDEFAULT 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` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `amount` double DEFAULT NULL,
  `remark` longtext COLLATE utf8_unicode_ci,
  `hasDiscount` tinyint(1) NOT NULL DEFAULT '0',
  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 `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Lista de las formaciones';
/*!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,
  `shipped` date DEFAULT NULL,
  `shipmentHour` time DEFAULT NULL,
  `landed` date NOT NULL,
  `landingHour` time DEFAULT NULL,
  `warehouseInFk` smallint(6) unsigned DEFAULT NULL,
  `warehouseOutFk` smallint(6) unsigned DEFAULT NULL,
  `agencyFk` int(11) DEFAULT NULL,
  `ref` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `isDelivered` tinyint(1) NOT NULL DEFAULT '0',
  `isReceived` 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` (`shipped`,`landed`,`warehouseInFk`,`warehouseOutFk`,`agencyFk`,`ref`),
  KEY `agency_id` (`agencyFk`),
  KEY `shipment` (`shipped`),
  KEY `landing` (`landed`),
  KEY `warehouse_landing` (`warehouseInFk`,`landed`),
  KEY `warehouse_out_shipment` (`warehouseOutFk`,`shipped`),
  KEY `travel_ibfk_4_idx` (`cargoSupplierFk`),
  CONSTRAINT `travel_ibfk_1` FOREIGN KEY (`warehouseInFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `travel_ibfk_2` FOREIGN KEY (`warehouseOutFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `travel_ibfk_3` FOREIGN KEY (`agencyFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `travel_ibfk_4` FOREIGN KEY (`cargoSupplierFk`) REFERENCES `vn2008`.`Proveedores_cargueras` (`Id_Proveedor`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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  = utf8 */ ;
/*!50003 SET character_set_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 `travel_beforeInsert`
	BEFORE INSERT ON `travel`
    FOR EACH ROW
BEGIN
	CALL travel_checkDates(NEW.shipped, NEW.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 SET @saved_cs_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.landed <=> OLD.landed)
	OR !(NEW.shipped <=> OLD.shipped) THEN
		CALL travel_checkDates(NEW.shipped, NEW.landed);
	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', NEW.id, OLD.id);

    IF !(NEW.shipped <=> OLD.shipped) THEN
		UPDATE entry 
            SET commission = entry_getCommission(travelFk, currencyFk,supplierFk)
			WHERE travelFk = NEW.id;
    END IF;
/*
	IF !(ABS(NEW.isDelivered) <=> ABS(OLD.isDelivered))
    THEN
		INSERT INTO vn2008.travel_dits SET
			idaccion_dits = 89,
			Id_Trabajador = myWorker_getId(),
            Id_Ticket = NEW.id,
            value_old = OLD.isDelivered,
            value_new = NEW.isDelivered;
	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 `travelLog`
--

DROP TABLE IF EXISTS `travelLog`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `travelLog` (
  `id` int(11) unsigned 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 `travelLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `travel` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `travelLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

DROP TABLE IF EXISTS `travelObservation`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `travelObservation` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `originFk` int(11) NOT NULL,
  `userFk` int(11) NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT 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 */;

--
-- Table structure for table `travelThermograph`
--

DROP TABLE IF EXISTS `travelThermograph`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `travelThermograph` (
  `thermographFk` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `created` date NOT NULL,
  `warehouseFk` smallint(6) unsigned NOT NULL,
  `travelFk` int(10) unsigned DEFAULT NULL,
  `temperature` enum('COOL','WARM') COLLATE utf8_unicode_ci NOT NULL,
  `result` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `dmsFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`thermographFk`,`created`),
  KEY `thermograph_fk_idx` (`thermographFk`),
  KEY `gestdoc_fk_idx` (`dmsFk`),
  KEY `travel_id` (`travelFk`),
  KEY `warehouse_id` (`warehouseFk`),
  CONSTRAINT `travelThermographDmsFgn` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `travelThermographThermographFgn` FOREIGN KEY (`thermographFk`) REFERENCES `thermograph` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `travelThermographTravelFgn` FOREIGN KEY (`travelFk`) REFERENCES `travel` (`id`),
  CONSTRAINT `travelThermographWarehouseFgn` FOREIGN KEY (`warehouseFk`) 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 */;

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

--
-- Table structure for table `userLog`
--

DROP TABLE IF EXISTS `userLog`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `userLog` (
  `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 `userLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `userLog_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 `userPhone`
--

DROP TABLE IF EXISTS `userPhone`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `userPhone` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userFk` int(10) unsigned NOT NULL,
  `typeFk` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `phone` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `UserFk_Phone` (`userFk`,`typeFk`,`phone`),
  KEY `fgnTypeFk` (`typeFk`),
  CONSTRAINT `fgnTypeFk` FOREIGN KEY (`typeFk`) REFERENCES `userPhoneType` (`code`) ON UPDATE CASCADE,
  CONSTRAINT `fgnUserFk` 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 `userPhoneType`
--

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

--
-- Table structure for table `vehicle`
--

DROP TABLE IF EXISTS `vehicle`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `vehicle` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `numberPlate` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `model` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `tradeMark` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `companyFk` smallint(5) unsigned NOT NULL DEFAULT '442',
  `m3` double DEFAULT NULL,
  `isActive` tinyint(4) NOT NULL DEFAULT '1',
  `warehouseFk` smallint(6) unsigned DEFAULT NULL,
  `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `deliveryPointFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `empresa_id` (`companyFk`),
  KEY `provinceFk_idx` (`warehouseFk`),
  KEY `vehicle_deliveryPointFk_idx` (`deliveryPointFk`),
  CONSTRAINT `provinceFk` FOREIGN KEY (`warehouseFk`) REFERENCES `province` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `vehicle_deliveryPointFk` FOREIGN KEY (`deliveryPointFk`) REFERENCES `deliveryPoint` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `vehicle_ibfk_1` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 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,
  `isFeedStock` tinyint(1) unsigned NOT NULL DEFAULT '0',
  `addressName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `delay` double NOT NULL DEFAULT '0.004',
  `hasAvailable` tinyint(4) NOT NULL DEFAULT '0',
  `isForTicket` tinyint(2) unsigned zerofill NOT NULL DEFAULT '00',
  `countryFk` mediumint(8) unsigned NOT NULL DEFAULT '1',
  `labelZone` tinyint(4) NOT NULL DEFAULT '0',
  `hasComission` tinyint(4) NOT NULL DEFAULT '0',
  `isInventory` tinyint(2) NOT NULL DEFAULT '0',
  `isComparative` 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' COMMENT 'Determina si se incluye en el informe de inventario valorado',
  `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',
  `hasStowaway` tinyint(1) NOT NULL DEFAULT '0',
  `hasDms` tinyint(1) NOT NULL DEFAULT '0',
  `pickUpAgencyModeFk` int(11) DEFAULT NULL,
  `isBuyerToBeEmailed` tinyint(2) NOT NULL DEFAULT '0',
  `aliasFk` smallint(5) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name_UNIQUE` (`name`),
  KEY `Id_Paises` (`countryFk`),
  KEY `isComparativeIdx` (`isComparative`),
  KEY `warehouse_ibfk_1_idx` (`aliasFk`),
  CONSTRAINT `warehouse_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`),
  CONSTRAINT `warehouse_ibfk_2` FOREIGN KEY (`aliasFk`) REFERENCES `warehouseAlias` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `warehouse_afterInsert` AFTER INSERT ON `warehouse` FOR EACH ROW
BEGIN
	IF NEW.isFeedStock THEN
		INSERT INTO warehouseAlias(`name`) VALUES(NEW.`name`);
		INSERT INTO warehouseJoined(warehouseFk, warehouseAliasFk)  
			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  = 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 `warehouse_afterUpdate` AFTER UPDATE ON `warehouse` FOR EACH ROW
BEGIN
	IF NEW.isFeedStock IS TRUE and OLD.isFeedStock IS FALSE then
		INSERT INTO warehouseAlias(`name`) VALUES(NEW.`name`);
		INSERT INTO warehouseJoined(warehouseFk, warehouseAliasFk) 
			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 `warehouseAlias`
--

DROP TABLE IF EXISTS `warehouseAlias`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `warehouseAlias` (
  `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

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

--
-- Table structure for table `workCenterHoliday`
--

DROP TABLE IF EXISTS `workCenterHoliday`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workCenterHoliday` (
  `workCenterFk` int(11) NOT NULL,
  `days` double NOT NULL,
  `year` smallint(6) NOT NULL,
  PRIMARY KEY (`workCenterFk`,`year`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `worker`
--

DROP TABLE IF EXISTS `worker`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `worker` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `code` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `firstName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `lastName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `password` varchar(50) CHARACTER SET utf8 DEFAULT 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,
  `typeBussines` varchar(30) CHARACTER SET utf8 DEFAULT 'no dejar vacio' COMMENT 'campo obsoleto, actualmente se rellena en laboral',
  `laborCategory` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `started` datetime DEFAULT NULL,
  `ended` datetime DEFAULT NULL,
  `notes` varchar(254) COLLATE utf8_unicode_ci DEFAULT NULL,
  `photo` blob,
  `fi` varchar(9) COLLATE utf8_unicode_ci DEFAULT NULL,
  `address` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `birthed` date NOT NULL,
  `maritalStatus` enum('soltero/a','casado/a') COLLATE utf8_unicode_ci NOT NULL,
  `phone` varchar(9) COLLATE utf8_unicode_ci NOT NULL,
  `companyFk` smallint(5) unsigned NOT NULL,
  `clientFk` int(11) DEFAULT NULL,
  `userFk` int(10) unsigned DEFAULT NULL,
  `bossFk` int(11) NOT NULL DEFAULT '2',
  `fiDueDate` datetime DEFAULT NULL,
  `hasMachineryAutorized` tinyint(2) DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `CodigoTrabajador_UNIQUE` (`code`),
  UNIQUE KEY `user` (`user`),
  UNIQUE KEY `user_id_UNIQUE` (`userFk`),
  UNIQUE KEY `Id_Cliente_Interno` (`clientFk`),
  KEY `sub` (`sub`),
  KEY `boss_idx` (`bossFk`),
  KEY `empresa_id` (`companyFk`),
  CONSTRAINT `Clientes` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `worker_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_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`.`worker_beforeInsert`
	BEFORE INSERT ON `worker` FOR EACH ROW
BEGIN
	IF NEW.password = '' THEN 
		SET NEW.password = 'FALLO';
	END IF;
    
    SET NEW.id = NEW.userFk;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `vn`.`worker_beforeUpdate`
	BEFORE UPDATE ON `worker` 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 `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 `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fg_workerFk_worker` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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 */;

--
-- Table structure for table `workerConfig`
--

DROP TABLE IF EXISTS `workerConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerConfig` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `defaultWorkerFk` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `defaultWorkerFk` (`defaultWorkerFk`),
  CONSTRAINT `workerConfig_ibfk_1` FOREIGN KEY (`defaultWorkerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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 `worker` (`userFk`) ON UPDATE CASCADE,
  CONSTRAINT `workerDocument_ibfk_2` FOREIGN KEY (`document`) REFERENCES `dms` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workerEmergencyBoss`
--

DROP TABLE IF EXISTS `workerEmergencyBoss`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerEmergencyBoss` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Table to save all responsible people phones',
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT 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=InnoDBDEFAULT 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=InnoDBDEFAULT 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 `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workerMana`
--

DROP TABLE IF EXISTS `workerMana`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerMana` (
  `workerFk` int(11) NOT NULL,
  `size` int(11) NOT NULL DEFAULT '300',
  `amount` int(11) NOT NULL DEFAULT '0',
  `pricesModifierRate` double NOT NULL DEFAULT '0',
  `isPricesModifierActivated` tinyint(1) NOT NULL DEFAULT '1',
  `minRate` decimal(3,2) NOT NULL DEFAULT '-0.05',
  `maxRate` decimal(3,2) NOT NULL DEFAULT '0.05',
  PRIMARY KEY (`workerFk`),
  KEY `fk_mana_spellers_Trabajadores_idx` (`workerFk`),
  CONSTRAINT `fk_mana_spellers_Trabajadores` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workerManaExcluded`
--

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

--
-- Temporary table structure for view `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 `size`,
 1 AS `amount`,
 1 AS `pricesModifierRate`,
 1 AS `isPricesModifierActivated`,
 1 AS `minRate`,
 1 AS `maxRate`*/;
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;

--
-- 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,
  `workerFk` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_idx` (`workerFk`),
  KEY `team_idx` (`team`),
  CONSTRAINT `user_team` FOREIGN KEY (`workerFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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 `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,
  `direction` enum('in','out','middle') COLLATE utf8_unicode_ci DEFAULT 'middle',
  PRIMARY KEY (`id`),
  UNIQUE KEY `userFk_Timed_uniq` (`userFk`,`timed`),
  KEY `warehouseFkfk1_idx` (`warehouseFk`),
  CONSTRAINT `warehouseFk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `workerTimeControl_fk1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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 `warehouse` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workerTimeControlLog`
--

DROP TABLE IF EXISTS `workerTimeControlLog`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerTimeControlLog` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userFk` int(10) NOT NULL,
  `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Log de fichadas, se rellena cuando el fichador(tablet) no autoriza el fichaje (PROC:vn.workerTimeControl_check)';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workerTimeControlParams`
--

DROP TABLE IF EXISTS `workerTimeControlParams`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerTimeControlParams` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dayBreak` int(11) NOT NULL,
  `weekBreak` int(11) NOT NULL,
  `weekScope` int(11) NOT NULL,
  `dayWorkMax` int(11) NOT NULL,
  `dayStayMax` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='All values in seconds';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workerTimeControlPin`
--

DROP TABLE IF EXISTS `workerTimeControlPin`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerTimeControlPin` (
  `workerFk` int(11) NOT NULL,
  `pin` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`workerFk`),
  CONSTRAINT `workerFk_.1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

--
-- Temporary table structure for view `workerTimeControlUserInfo`
--

DROP TABLE IF EXISTS `workerTimeControlUserInfo`;
/*!50001 DROP VIEW IF EXISTS `workerTimeControlUserInfo`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `workerTimeControlUserInfo` AS SELECT 
 1 AS `userFk`,
 1 AS `name`,
 1 AS `surname`,
 1 AS `user`,
 1 AS `password`,
 1 AS `bcryptPassword`,
 1 AS `departmentFk`,
 1 AS `dni`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary table structure for view `workerTimeControlWorking`
--

DROP TABLE IF EXISTS `workerTimeControlWorking`;
/*!50001 DROP VIEW IF EXISTS `workerTimeControlWorking`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `workerTimeControlWorking` AS SELECT 
 1 AS `userFk`,
 1 AS `timed`,
 1 AS `name`,
 1 AS `surname`,
 1 AS `phone`,
 1 AS `workerPhone`,
 1 AS `department`,
 1 AS `workerCenter`,
 1 AS `maxOrder`*/;
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 `workers20190711`
--

DROP TABLE IF EXISTS `workers20190711`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workers20190711` (
  `person_id` int(11) NOT NULL DEFAULT '0',
  `business_id` int(11) NOT NULL DEFAULT '0',
  `Apellidos` varchar(60) CHARACTER SET utf8 NOT NULL,
  `Nombre` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  `nif` varchar(15) CHARACTER SET utf8 DEFAULT NULL,
  `Fecha_Inicio` date DEFAULT NULL,
  `Fecha_Fin` date DEFAULT NULL,
  `departamento` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `Jornada_Semanal` smallint(6) DEFAULT NULL,
  `Codigo_Contrato` int(11) DEFAULT NULL,
  `userFk` int(11) NOT NULL,
  PRIMARY KEY (`person_id`),
  UNIQUE KEY `userFk_UNIQUE` (`userFk`),
  UNIQUE KEY `nif_UNIQUE` (`nif`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workers20190711_FichadasAbril`
--

DROP TABLE IF EXISTS `workers20190711_FichadasAbril`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workers20190711_FichadasAbril` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `person_id` int(11) NOT NULL DEFAULT '0',
  `nif` varchar(15) CHARACTER SET utf8 DEFAULT NULL,
  `Apellidos` varchar(60) CHARACTER SET utf8 NOT NULL,
  `Nombre` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  `Fecha` date DEFAULT NULL,
  `Hora` int(2) DEFAULT NULL,
  `Minuto` int(2) DEFAULT NULL,
  `sumable` double DEFAULT NULL,
  `jornada` decimal(5,2) NOT NULL DEFAULT '8.00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workers20190711_FichadasJulio11`
--

DROP TABLE IF EXISTS `workers20190711_FichadasJulio11`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workers20190711_FichadasJulio11` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `person_id` int(11) NOT NULL DEFAULT '0',
  `nif` varchar(15) CHARACTER SET utf8 DEFAULT NULL,
  `Apellidos` varchar(60) CHARACTER SET utf8 NOT NULL,
  `Nombre` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  `Fecha` date DEFAULT NULL,
  `Hora` int(2) DEFAULT NULL,
  `Minuto` int(2) DEFAULT NULL,
  `sumable` double DEFAULT NULL,
  `jornada` decimal(5,2) NOT NULL DEFAULT '8.00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workers20190711_FichadasJunio`
--

DROP TABLE IF EXISTS `workers20190711_FichadasJunio`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workers20190711_FichadasJunio` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `person_id` int(11) NOT NULL DEFAULT '0',
  `nif` varchar(15) CHARACTER SET utf8 DEFAULT NULL,
  `Apellidos` varchar(60) CHARACTER SET utf8 NOT NULL,
  `Nombre` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  `Fecha` date DEFAULT NULL,
  `Hora` int(2) DEFAULT NULL,
  `Minuto` int(2) DEFAULT NULL,
  `sumable` double DEFAULT NULL,
  `jornada` decimal(5,2) NOT NULL DEFAULT '8.00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workers20190711_FichadasMayo`
--

DROP TABLE IF EXISTS `workers20190711_FichadasMayo`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workers20190711_FichadasMayo` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `person_id` int(11) NOT NULL DEFAULT '0',
  `nif` varchar(15) CHARACTER SET utf8 DEFAULT NULL,
  `Apellidos` varchar(60) CHARACTER SET utf8 NOT NULL,
  `Nombre` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  `Fecha` date DEFAULT NULL,
  `Hora` int(2) DEFAULT NULL,
  `Minuto` int(2) DEFAULT NULL,
  `sumable` double DEFAULT NULL,
  `jornada` decimal(5,2) NOT NULL DEFAULT '8.00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workers20190711_FichadasOctubre`
--

DROP TABLE IF EXISTS `workers20190711_FichadasOctubre`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workers20190711_FichadasOctubre` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `person_id` int(11) NOT NULL DEFAULT '0',
  `nif` varchar(15) CHARACTER SET utf8 DEFAULT NULL,
  `Apellidos` varchar(60) CHARACTER SET utf8 NOT NULL,
  `Nombre` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  `Fecha` date DEFAULT NULL,
  `Hora` int(2) DEFAULT NULL,
  `Minuto` int(2) DEFAULT NULL,
  `sumable` double DEFAULT NULL,
  `jornada` decimal(5,2) NOT NULL DEFAULT '8.00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

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

DROP TABLE IF EXISTS `workingHours`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workingHours` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `timeIn` datetime NOT NULL,
  `timeOut` datetime DEFAULT NULL,
  `userId` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_working_hour_idx` (`userId`),
  CONSTRAINT `user_working_hour` FOREIGN KEY (`userId`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT 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 DEFAULT 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',
  `inflation` decimal(5,2) NOT NULL DEFAULT '1.00',
  PRIMARY KEY (`id`),
  KEY `fk_zone_1_idx` (`warehouseFk__`),
  KEY `fk_zone_2_idx` (`agencyModeFk`),
  KEY `zone_name_idx` (`name`),
  CONSTRAINT `fk_zone_1` FOREIGN KEY (`warehouseFk__`) REFERENCES `warehouse` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `fk_zone_2` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDBDEFAULT 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,
  `price` double NOT NULL,
  `bonus` double 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 `zoneEvent`
--

DROP TABLE IF EXISTS `zoneEvent`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneEvent` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `zoneFk` int(11) NOT NULL,
  `type` enum('day','indefinitely','range') NOT NULL,
  `dated` date DEFAULT NULL,
  `started` date DEFAULT NULL,
  `ended` date DEFAULT NULL,
  `weekDays` set('mon','tue','wed','thu','fri','sat','sun') NOT NULL,
  `hour` datetime DEFAULT NULL,
  `travelingDays` int(11) DEFAULT NULL,
  `price` decimal(10,2) DEFAULT NULL,
  `bonus` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `zoneFk` (`zoneFk`),
  CONSTRAINT `zoneEvent_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `zoneExclusion`
--

DROP TABLE IF EXISTS `zoneExclusion`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneExclusion` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `zoneFk` int(11) NOT NULL,
  `dated` date NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `zoneFk_2` (`zoneFk`,`dated`),
  KEY `zoneFk` (`zoneFk`),
  CONSTRAINT `zoneExclusion_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8;
/*!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 AUTO_INCREMENT,
  `type` set('country','province','town','postCode') CHARACTER SET utf8 NOT NULL,
  `name` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `parentFk` int(10) unsigned DEFAULT NULL,
  `path` varchar(255) 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`),
  KEY `lft_rgt_depth_idx` (`lft`,`rgt`,`depth`),
  KEY `name_idx` (`name`),
  KEY `parentFk` (`parentFk`),
  KEY `path` (`path`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`zoneGeo_beforeInsert`
	BEFORE INSERT ON `zoneGeo` FOR EACH ROW
BEGIN
	CALL zoneGeo_checkName(NEW.`name`);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = 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 `vn`.`zoneGeo_beforeUpdate`
	BEFORE UPDATE ON `zoneGeo` FOR EACH ROW
BEGIN
	IF !(OLD.`name` <=> NEW.`name`) THEN
		CALL zoneGeo_checkName(NEW.`name`);
	END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;

--
-- Table structure for table `zoneGeoRecalc`
--

DROP TABLE IF EXISTS `zoneGeoRecalc`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneGeoRecalc` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `isChanged` tinyint(4) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDBDEFAULT CHARSET=utf8;
/*!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 `zoneFk2` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `zoneGeoFk2` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`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 `zoneWarehouse`
--

DROP TABLE IF EXISTS `zoneWarehouse`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneWarehouse` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `zoneFk` int(11) NOT NULL,
  `warehouseFk` smallint(6) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `zoneFk` (`zoneFk`,`warehouseFk`),
  KEY `warehouseFk` (`warehouseFk`),
  CONSTRAINT `zoneWarehouse_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8;
/*!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 `department_doCalc` */;
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 `department_doCalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-11-15 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL vn.department_doCalc */ ;;
/*!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 `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 `printQueue_check` */;;
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 `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2019-11-08 00:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Notifica en caso de que el servidor de impresión este parado' DO BEGIN

	DECLARE vCurrentCount INT;
	DECLARE vCheckSum INT;
    DECLARE vIsAlreadyNotified BOOLEAN;
    DECLARE vTableQueue TEXT;
	DECLARE vLineQueue TEXT;
    DECLARE vDone BOOL DEFAULT FALSE;
    DECLARE vCur CURSOR FOR 
    	SELECT  CONCAT('<tr>
							<td>', IFNULL(pq.id, ''), '</td>
							<td>', IFNULL(p.path, ''),'</td>
							<td>', IFNULL(i.Informe, ''),'</td>
							<td>', IFNULL(e.Estado, ''),'</td>
							<td>', IFNULL(w.firstname, ''), " ", IFNULL(w.lastName, ''),'</td>
							<td>', IFNULL(pq.`error`, ''),'</td>
						</tr>')
            FROM vn.printingQueue pq
                LEFT JOIN vn.worker w ON w.id = pq.worker
                LEFT JOIN vn.printer p ON p.id = pq.printer
                LEFT JOIN vn2008.Informes i ON i.Id_Informe = pq.report
                JOIN  vn2008.Estados e ON e.Id_Estado = pq.state
            LIMIT 30;
	
    DECLARE CONTINUE HANDLER FOR NOT FOUND
    SET vDone = TRUE; 		

	SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum
		FROM vn.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 AND vCurrentCount  > 0
	THEN

		SELECT  '<table  cellspacing="10">
					<tr>
						<td>Id Cola</td>
						<td>Ruta Impresora</td>
						<td>Informe</td>
						<td>Estado</td>
						<td>Trabajador</td>
						<td>Error</td>
                     </tr>' INTO vTableQueue;
			
		OPEN vCur;
	  
		l: LOOP
			
			SET vDone = FALSE;
            
			FETCH vCur INTO vLineQueue;
            
            IF vDone THEN
				LEAVE l;
			END IF;
            
            SELECT CONCAT(vTableQueue, vLineQueue) INTO vTableQueue;
			
		END LOOP;
	  
		CLOSE vCur;     
               
        INSERT INTO vn2008.mail (`to`, subject, text)
			VALUES ('cau@verdnatura.es, sysadmin@verdnatura.es',
				'servidor de impresion parado', 
                CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '</table>'));
		 
         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=`root`@`%`*/ /*!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 */ ;;
/*!50106 DROP EVENT IF EXISTS `zoneGeo_doCalc` */;;
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 `zoneGeo_doCalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-09-13 15:30:47' ON COMPLETION PRESERVE ENABLE DO CALL vn.zoneGeo_doCalc */ ;;
/*!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 `address_getGeo` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `address_getGeo`(vSelf INT) RETURNS int(11)
    DETERMINISTIC
BEGIN
/**
 * Returns the geo for the passed address.
 *
 * @param vSelf The address id
 * @return The geo id
 */
 	DECLARE vGeoFk INT;

	SELECT p.geoFk INTO vGeoFk
		FROM address a 
			JOIN town t ON t.provinceFk = a.provinceFk
			JOIN postCode p ON p.townFk = t.id AND p.`code` = a.postalCode
		WHERE a.id = vSelf
		ORDER BY (a.city SOUNDS LIKE t.`name`) DESC
		LIMIT 1;

	RETURN vGeoFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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),
    vAddress INT,
    vAgencyMode INT) RETURNS decimal(10,3)
    DETERMINISTIC
BEGIN
	DECLARE vGeneralInflationCoeficient INT;
    DECLARE vVerdnaturaVolumeBox BIGINT;
    DECLARE vClientFk INT;
    DECLARE vComponentRecovery VARCHAR(50) DEFAULT 'debtCollection';
	DECLARE vComponentMana VARCHAR(50) DEFAULT 'autoMana';
	DECLARE vComponentPort VARCHAR(50) DEFAULT 'delivery';
	DECLARE vComponentMargin VARCHAR(50) DEFAULT 'margin';
	DECLARE vComponentCost VARCHAR(50) DEFAULT 'purchaseValue';
    DECLARE vComponentCostValue DECIMAL(10,2);
	DECLARE vItem INT DEFAULT 98;
    DECLARE vItemCarryBox INT;
	
    SELECT generalInflationCoeFicient, verdnaturaVolumeBox, itemCarryBox
			INTO vGeneralInflationCoeficient, vVerdnaturaVolumeBox, vItemCarryBox
		FROM bionicConfig;
    
    SELECT clientFk INTO vClientFk FROM address WHERE id = vAddress;

	-- Creamos la tabla tmp.bionicComponent
    DROP TEMPORARY TABLE IF EXISTS tmp.bionicComponent;
    CREATE TEMPORARY TABLE tmp.bionicComponent(
		`warehouseFk` smallint(5) unsigned NOT NULL,
		`itemFk` int(11) NOT NULL,
		`componentFk` int(10) unsigned NOT NULL,
		`value` decimal(10,4) NOT NULL,
		UNIQUE KEY `itemWarehouseComponent` (`itemFk`,`warehouseFk`,`componentFk`) USING HASH,
		KEY `itemWarehouse` (`itemFk`,`warehouseFk`) USING BTREE
	) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

   -- Margin
	INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
		SELECT vWarehouse, vItem, id, vMargin
			FROM component
			WHERE code = vComponentMargin;

   -- Recobro
	INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
		SELECT vWarehouse, vItem, c.id, ROUND(LEAST(cr.recobro,0.25), 3) 
			FROM bi.claims_ratio cr
				JOIN component c ON c.code = vComponentRecovery
				WHERE cr.Id_Cliente = vClientFk AND cr.recobro > 0.009;
                            
	-- Componente de maná automático, en función del maná acumulado por el comercial.
	INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
		SELECT vWarehouse, vItem, co.id, ROUND(ms.prices_modifier_rate, 3)
			FROM client c 
				JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador
                JOIN component co ON co.code = vComponentMana
			WHERE ms.prices_modifier_activated AND c.id = vClientFk LIMIT 1;
 
	-- Reparto
	INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
		SELECT vWarehouse, vItem, co.id, vGeneralInflationCoeficient
				* ROUND(
						vM3
						* az.price
						* az.inflation
						/ vVerdnaturaVolumeBox, 4
						)
			FROM agencyMode ag
				JOIN address a ON a.id = vAddress AND ag.id = vAgencyMode
				JOIN agencyProvince ap ON ap.agencyFk = ag.agencyFk 
					AND ap.warehouseFk = vWarehouse AND ap.provinceFk = a.provinceFk
				JOIN agencyModeZone az ON az.agencyModeFk = vAgencyMode 
					AND az.zone = ap.zone AND az.itemFk = 71 AND az.warehouseFk = vWarehouse
				JOIN component co ON co.code = vComponentPort;
    
    -- Coste
	SELECT vRetailedPrice - SUM(`value`) INTO vComponentCostValue
		FROM tmp.bionicComponent;

	INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
		SELECT vWarehouse, vItem, id,vComponentCostValue
			FROM component 
            WHERE code = vComponentCost;
        
    RETURN vComponentCostValue;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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),
    vAddress INT,
    vAgencyMode INT) RETURNS decimal(10,3)
    DETERMINISTIC
BEGIN
	DECLARE vGeneralInflationCoeficient INT;
    DECLARE vVerdnaturaVolumeBox BIGINT;
    DECLARE vClientFk INT;
    DECLARE vComponentRecovery VARCHAR(50) DEFAULT 'debtCollection';
	DECLARE vComponentMana VARCHAR(50) DEFAULT 'autoMana';
	DECLARE vComponentPort VARCHAR(50) DEFAULT 'delivery';
	DECLARE vComponentMargin VARCHAR(50) DEFAULT 'margin';
	DECLARE vComponentCost VARCHAR(50) DEFAULT 'purchaseValue';
    DECLARE vComponentCostValue DECIMAL(10,2);
	DECLARE vItem INT DEFAULT 98;
    DECLARE vItemCarryBox INT;
	
    SELECT generalInflationCoeFicient, verdnaturaVolumeBox, itemCarryBox
			INTO vGeneralInflationCoeficient, vVerdnaturaVolumeBox, vItemCarryBox
		FROM bionicConfig;
    
    SELECT clientFk INTO vClientFk FROM address WHERE id = vAddress;

	-- Creamos la tabla tmp.bionicComponent
    DROP TEMPORARY TABLE IF EXISTS tmp.bionicComponent;
    CREATE TEMPORARY TABLE tmp.bionicComponent(
		`warehouseFk` smallint(5) unsigned NOT NULL,
		`itemFk` int(11) NOT NULL,
		`componentFk` int(10) unsigned NOT NULL,
		`value` decimal(10,4) NOT NULL,
		UNIQUE KEY `itemWarehouseComponent` (`itemFk`,`warehouseFk`,`componentFk`) USING HASH,
		KEY `itemWarehouse` (`itemFk`,`warehouseFk`) USING BTREE
	) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

   -- Margin
	INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
		SELECT vWarehouse, vItem, id, vMargin
			FROM component
			WHERE code = vComponentMargin;

   -- Recobro
	INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
		SELECT vWarehouse, vItem, c.id, ROUND(LEAST(cr.recobro,0.25), 3) 
			FROM bi.claims_ratio cr
				JOIN component c ON c.code = vComponentRecovery
				WHERE cr.Id_Cliente = vClientFk AND cr.recobro > 0.009;
                            
	-- Componente de maná automático, en función del maná acumulado por el comercial.
	INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
		SELECT vWarehouse, vItem, co.id, ROUND(ms.prices_modifier_rate, 3)
			FROM client c 
				JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador
                JOIN component co ON co.code = vComponentMana
			WHERE ms.prices_modifier_activated AND c.id = vClientFk LIMIT 1;
 
	-- Reparto
	INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
		SELECT vWarehouse, vItem, co.id, vGeneralInflationCoeficient
				* ROUND(
						vM3
						* az.price
						* az.inflation
						/ vVerdnaturaVolumeBox, 4
						)
			FROM agencyMode ag
				JOIN address a ON a.id = vAddress AND ag.id = vAgencyMode
				JOIN agencyProvince ap ON ap.agencyFk = ag.agencyFk 
					AND ap.warehouseFk = vWarehouse AND ap.provinceFk = a.provinceFk
				JOIN agencyModeZone az ON az.agencyModeFk = vAgencyMode 
					AND az.zone = ap.zone AND az.itemFk = 71 AND az.warehouseFk = vWarehouse
				JOIN component co ON co.code = vComponentPort;
    
    -- Coste
	SELECT vRetailedPrice - SUM(`value`) INTO vComponentCostValue
		FROM tmp.bionicComponent;

	INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`)
		SELECT vWarehouse, vItem, id,vComponentCostValue
			FROM component 
            WHERE code = vComponentCost;
        
    RETURN vComponentCostValue;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `botanicExport_isUpdatable` */;
/*!50003 SET @saved_cs_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 `botanicExport_isUpdatable`(vEdiGenusFk MEDIUMINT,vEdiSpecieFk MEDIUMINT,
	vCountryFk MEDIUMINT,vRestriction MEDIUMINT) RETURNS int(11)
    DETERMINISTIC
BEGIN
	DECLARE vIsUpdatable INTEGER;
	SELECT COUNT(*) INTO vIsUpdatable 
		FROM botanicExport 
		WHERE ediGenusFk = vEdiGenusFk 
			AND (vEdiSpecieFk = ediSpecieFk OR IFNULL(vEdiSpecieFk,ediSpecieFk) IS NULL)
            AND (vCountryFk = countryFk OR IFNULL(vCountryFk,countryFk) IS NULL)
            AND vRestriction = restriction;
RETURN vIsUpdatable;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `buy_getUnitVolume` */;
/*!50003 SET @saved_cs_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 `buy_getUnitVolume`(vSelf INT) RETURNS int(11)
    DETERMINISTIC
BEGIN
/**
 * Calculates the unit volume occupied by a buy.
 *
 * @param vSelf The buy id
 * @return The unit volume in cubic centimeters
 */
	DECLARE vItem INT;
	DECLARE vPackaging VARCHAR(10);
	DECLARE vPacking INT;

	SELECT itemFk, packageFk, packing
		INTO vItem, vPackaging, vPacking
		FROM buy
		WHERE id = vSelf;

	RETURN IFNULL(ROUND(item_getVolume(vItem, vPackaging) / vPacking), 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 `buy_getVolume` */;
/*!50003 SET @saved_cs_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 `buy_getVolume`(vSelf INT) RETURNS int(11)
    DETERMINISTIC
BEGIN
/**
 * Calculates the volume occupied by a buy.
 *
 * @param vSelf The buy id
 * @return The volume in cubic centimeters
 */
	DECLARE vItem INT;
	DECLARE vPackaging VARCHAR(10);

	SELECT itemFk, packageFk INTO vItem, vPackaging
		FROM buy
		WHERE id = vSelf;

	RETURN item_getVolume(vItem, vPackaging);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `buy_hasNotifyPassport` */;
/*!50003 SET @saved_cs_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 `buy_hasNotifyPassport`(vBuyFk INT, vItemFk INT) RETURNS tinyint(1)
    READS SQL DATA
BEGIN
	DECLARE vHasPassport BOOL;
	DECLARE vIsAlreadySent BOOL;
	DECLARE vItemCategoryFk INT;
    SELECT id INTO vItemCategoryFk FROM itemCategory WHERE code = 'plant';
    
	SELECT COUNT(*) INTO vHasPassport
		FROM botanicExport be
            JOIN itemBotanical ib
				ON be.ediGenusFk = ib.genusFk
					AND IFNULL(be.ediSpecieFk, ib.specieFk) = ib.specieFk
					AND be.restriction = 'pasaporte fitosanitario'
			JOIN item i ON i.id = ib.itemFk
			JOIN itemType it ON it.id = i.typeFk
		WHERE ib.itemFk = vItemFk
			AND it.categoryFk = vItemCategoryFk;

	IF vHasPassport THEN
		SELECT COUNT(*) INTO vIsAlreadySent
			FROM mail m
				JOIN buy b ON b.id = vBuyFk
			WHERE m.`body` LIKE CONCAT('%', b.ektFk, '%')
            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 `catalog_componentReverse` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `catalog_componentReverse`(vWarehouse INT,
    vCost DECIMAL(10,3),
    vM3 DECIMAL(10,3),
    vAddressFk INT,
    vZoneFk INT) RETURNS decimal(10,3)
    DETERMINISTIC
BEGIN
	/* Calcula los componentes para un cliente a partir de un coste y volumen
	* @param vWarehouse 
	* @param vCost Valor de coste del articulo
	* @param vM3 m3 del articulo
    * @param vAddressFk 
    * @param vZoneFk
	* @return vRetailedPrice precio de venta sin iva 
	* @return tmp.catalog_component (warehouseFk, itemFk, componentFk, cost)
	*/
    
    DECLARE vBoxVolume BIGINT;    
    DECLARE vCustomer INT;
    DECLARE vComponentRecovery INT DEFAULT 17;
	DECLARE vComponentMana INT DEFAULT 39;
	DECLARE vDeliveryComponent INT DEFAULT 15;
	DECLARE vComponentMargin INT DEFAULT 29;
	DECLARE vComponentCost INT DEFAULT 28;
    DECLARE vRetailedPrice DECIMAL(10,2);
	DECLARE vItem INT DEFAULT 98;
    
	SELECT volume INTO vBoxVolume
		FROM vn.packaging
        WHERE id = '94';
    
    SELECT clientFk INTO vCustomer FROM address WHERE id = vAddressFk;

    DROP TEMPORARY TABLE IF EXISTS tmp.catalog_component;
    CREATE TEMPORARY TABLE tmp.catalog_component (
		`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));

	-- Cost
	INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost)
		SELECT vWarehouse, vItem, vComponentCost, vCost
			FROM vn.rate
				WHERE dated <= CURDATE()
					AND warehouseFk = vWarehouse
				ORDER BY dated DESC
				LIMIT 1;	     
                
   -- Margen
	INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost)
		SELECT vWarehouse, vItem, vComponentMargin, (vCost / ((100 - rate2) / 100)) - vCost 
			FROM vn.rate
				WHERE dated <= CURDATE()
					AND warehouseFk = vWarehouse
				ORDER BY dated DESC
				LIMIT 1;	     
        
   -- Recobro
	INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, 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.catalog_component (warehouseFk, itemFk, componentFk, 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.catalog_component (warehouseFk, itemFk, componentFk, cost)
		SELECT vWarehouse, vItem, vDeliveryComponent,
				ROUND(
						vM3 
						* (z.price - z.bonus)
						* z.inflation 
						/ vBoxVolume, 4
						)
			FROM zone z 
            WHERE z.id = vZoneFk;
            
    -- Precio de venta
	SELECT SUM(cost) INTO vRetailedPrice
		FROM tmp.catalog_component;

    RETURN 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 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  = 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 `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(amountPaid)
				FROM receipt
				WHERE clientFk = vClient
					AND payed > 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)
    DETERMINISTIC
BEGIN
/**
 * Devuelve el mana del cliente.
 *
 * @param vClient Id del cliente
 * @return Mana del cliente
 */
	DECLARE vMana DECIMAL(10,2);
	DECLARE vFromDated DATE;
    DECLARE vHasMana BOOLEAN;
	DECLARE vManaComponent INT;
	DECLARE vAutoManaComponent INT;
    DECLARE vManaBank INT;
    DECLARE vManaGreugeType INT;
    
    SELECT id INTO vManaGreugeType FROM greugeType WHERE code = 'mana';
    SELECT id INTO vManaBank FROM bank WHERE code = 'mana';
    SELECT id INTO vManaComponent FROM component WHERE code = 'mana';
    SELECT id INTO vAutoManaComponent FROM component WHERE code = 'autoMana';
    
	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 clientManaCache;

	SELECT sum(mana) INTO vMana
		FROM 
			(
			SELECT mana
				FROM clientManaCache
				WHERE clientFk = vClient
				AND dated = vFromDated			
			UNION ALL
			SELECT s.quantity * value
				 FROM ticket t
					JOIN address a ON a.id = t.addressFk
					JOIN sale s on s.ticketFk = t.id
					JOIN saleComponent sc on sc.saleFk = s.id
						WHERE sc.componentFk IN (vManaComponent, vAutoManaComponent)
							AND t.shipped > vFromDated 
							AND t.shipped < TIMESTAMPADD(DAY,1,CURDATE())
							AND a.clientFk = vClient
			UNION ALL
			SELECT - amountPaid
				FROM receipt r
					JOIN `client` c ON c.id = r.clientFk
				WHERE r.bankFk = vManaBank
					AND r.payed > vFromDated
					AND r.payed <= CURDATE()
					AND c.id = vClient
			UNION ALL
			SELECT  g.amount
				FROM greuge g
					JOIN `client` c ON c.id = g.clientFk
				WHERE g.greugeTypeFk = vManaGreugeType
					AND g.shipped > vFromDated
					AND g.shipped <= CURDATE()
					AND c.id = 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  = 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 `clientGetSalesPerson`(vClientFk INT, vDated DATE) RETURNS int(11)
    DETERMINISTIC
BEGIN
/**
 * DEPRECATED: use client_getSalesPerson
 **/
	RETURN client_getSalesPerson(vClientFk, 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 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 `client_getFromPhone` */;
/*!50003 SET @saved_cs_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 `client_getFromPhone`(vPhone VARCHAR(255)) RETURNS int(11)
    DETERMINISTIC
BEGIN
/**
 * Searchs a customer associated to the phone number.
 *
 * @param vPhone The phone number
 * @return The client id or %NULL if not found
 */
	DECLARE vClient INT DEFAULT NULL;

	-- SET vPhone = vPhone COLLATE 'utf8_unicode_ci';

	DROP TEMPORARY TABLE IF EXISTS tClient;
	CREATE TEMPORARY TABLE tClient
		ENGINE = MEMORY
		SELECT id clientFk
			FROM `client`
			WHERE phone = vPhone
				OR mobile = vPhone
		UNION
		SELECT clientFk
			FROM address
			WHERE phone = vPhone
				OR mobile = 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.clientFk INTO vClient
		FROM tClient t
			JOIN `client` c ON c.id = t.clientFk
		WHERE c.isActive
		LIMIT 1;

	DROP TEMPORARY TABLE tClient;

	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 `client_getSalesPerson` */;
/*!50003 SET @saved_cs_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 `client_getSalesPerson`(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 vSalesPersonFk INT DEFAULT NULL;
	DECLARE vWorkerSubstituteFk INT DEFAULT NULL;
	DECLARE vLoop BOOLEAN;

	-- Obtiene el comercial original y el de sharingclient

	SELECT c.salesPersonFk, s.workerFk
		INTO vSalesPersonFk, vWorkerSubstituteFk
		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 vWorkerSubstituteFk IS NOT NULL
	THEN
		SET vSalesPersonFk = vWorkerSubstituteFk;
	ELSEIF vSalesPersonFk IS NOT NULL
	THEN
		DROP TEMPORARY TABLE IF EXISTS tmp.stack;
		CREATE TEMPORARY TABLE tmp.stack
			(INDEX (substitute))
			ENGINE = MEMORY
			SELECT vSalesPersonFk substitute;

		l: LOOP
			SELECT workerSubstitute INTO vWorkerSubstituteFk
				FROM sharingCart 
				WHERE vDated BETWEEN started AND ended
					AND workerFk = vSalesPersonFk
				ORDER BY id
				LIMIT 1;
				
			IF vWorkerSubstituteFk IS NULL THEN
				LEAVE l;
			END IF;
				
			SELECT COUNT(*) > 0 INTO vLoop
				FROM tmp.stack WHERE substitute = vWorkerSubstituteFk;

			IF vLoop THEN
				LEAVE l;
			END IF;
			
			INSERT INTO tmp.stack SET
				substitute = vWorkerSubstituteFk;
			
			SET vSalesPersonFk = vWorkerSubstituteFk;
		END LOOP;
		
		DROP TEMPORARY TABLE tmp.stack;
	END IF;

	RETURN vSalesPersonFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `client_getSalesPersonByTicket` */;
/*!50003 SET @saved_cs_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 `client_getSalesPersonByTicket`(vTicketFk INT) RETURNS int(11)
    DETERMINISTIC
BEGIN
/**
 * Dado un id ticket, devuelve su comercial.
 * Para más información ir a client_getSalesPerson()
 *
 * @param vClientFk El id del cliente
 * @param vDated Fecha a comprobar
 * @return El id del comercial para la fecha dada
 **/
    DECLARE vClientFk INT;
    DECLARE vDated DATE;
    
    SELECT clientFk, shipped
		INTO vClientFk, vDated
        FROM ticket WHERE id = vTicketFk;
        
	RETURN client_getSalesPerson(vClientFk, 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 FUNCTION IF EXISTS `client_getSalesPersonCode` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `client_getSalesPersonCode`(vClientFk INT, vDated 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 client_getSalesPerson()
 *
 * @param vClientFk El id del cliente
 * @param vDated Fecha a comprobar
 * @return El código del comercial para la fecha dada
 **/
    DECLARE vWorkerCode CHAR(3);
    DECLARE vSalesPersonFk INT;
    
    SET vSalesPersonFk = client_getSalesPerson(vClientFk, vDated);

	SELECT code
		INTO vWorkerCode
		FROM worker 
		WHERE id = vSalesPersonFk;

	RETURN vWorkerCode;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `client_getSalesPersonCodeByTicket` */;
/*!50003 SET @saved_cs_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 `client_getSalesPersonCodeByTicket`(vTicketFk INT) RETURNS varchar(3) CHARSET utf8
    DETERMINISTIC
BEGIN
/**
 * Dado un id ticket, devuelve su comercial.
 * Para más información ir a client_getSalesPerson()
 *
 * @param vClientFk El id del cliente
 * @param vDated Fecha a comprobar
 * @return El código del comercial para la fecha dada
 **/
    DECLARE vClientFk INT;
    DECLARE vDated DATE;
    
    SELECT clientFk, shipped
		INTO vClientFk, vDated
        FROM ticket WHERE id = vTicketFk;
        
	RETURN client_getSalesPersonCode(vClientFk, 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 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
	-- DEPRECATED: use entry_getComission
	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_getCommission` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `entry_getCommission`(
    vTravelFk INT,
    vCurrencyFk INT,
    vSupplierFk INT
) RETURNS int(11)
    READS SQL DATA
BEGIN
    DECLARE vCommission INT;
    DECLARE vCurrentCommission INT;
    DECLARE vIsCurrencyUsd INT;
    DECLARE vLastEntryFk INT;
    
    SELECT count(*) INTO vIsCurrencyUsd
            FROM currency c
            WHERE c.code = 'USD' AND id = vCurrencyFk;
    
    IF NOT vIsCurrencyUsd THEN
    
		SELECT e.id INTO vLastEntryFk
			FROM vn.entry e
				JOIN vn.travel tr ON tr.id = e.travelFk
                WHERE e.supplierFk = vSupplierFk
                ORDER BY tr.landed DESC
                LIMIT 1;
        
        IF vLastEntryFk THEN
        
			SELECT commission INTO vCurrentCommission
				FROM vn.entry
                WHERE id = vLastEntryFk;
        
        ELSE
        
			SELECT commission INTO vCurrentCommission
				FROM supplier s
				WHERE s.id = vSupplierFk;
        
		END IF;
        
        RETURN vCurrentCommission;
        
    ELSE

		SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission
			FROM travel t
				LEFT JOIN referenceCurrent r ON r.currencyFk = vCurrencyFk AND r.`dated` <= t.shipped
			WHERE t.id = vTravelFk
			ORDER BY r.`dated` DESC
			LIMIT 1;
        
		RETURN IFNULL(vCommission, 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 DROP FUNCTION IF EXISTS `entry_getCommission__` */;
/*!50003 SET @saved_cs_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_getCommission__`(
    vTravelFk INT,
    vCurrencyFk INT,
    vSupplierFk INT
) RETURNS int(11)
    READS SQL DATA
BEGIN
	-- bernat: working in this file
    DECLARE vCommission INT;
    DECLARE vCurrentCommission INT;
    DECLARE vIsCurrencyUsd INT;
    
    SELECT count(*) INTO vIsCurrencyUsd
            FROM currency c
            WHERE c.code = 'USD' AND id = vCurrencyFk;
    
    IF NOT vIsCurrencyUsd THEN
        SELECT commission INTO vCurrentCommission
            FROM supplier s
            WHERE s.id = vSupplierFk;
        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;
        
    RETURN IFNULL(vCommission, 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 `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  = 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 `getAlert3State`(vTicket INT) RETURNS varchar(45) CHARSET utf8 COLLATE utf8_unicode_ci
    READS SQL DATA
BEGIN
	DECLARE vDeliveryType INTEGER DEFAULT 0;
	DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE;
	DECLARE vCode VARCHAR(45);
		
	SELECT am.deliveryMethodFk
	INTO vDeliveryType 
		FROM ticket t
			JOIN agencyMode am ON am.id = t.agencyModeFk
	WHERE t.id = vTicket;
		
		CASE vDeliveryType
			WHEN 1 THEN -- AGENCIAS
				SET vCode = 'DELIVERED';
					   
			WHEN 2 THEN -- REPARTO
				SET vCode = 'ON_DELIVERY';
					
			ELSE -- MERCADO, OTROS
				SELECT MIN(t.warehouseFk <> w.id) INTO isWaitingForPickUp
					FROM ticket t 
						LEFT JOIN warehouse w
							ON w.pickUpagencyModeFk = t.agencyModeFk
					WHERE t.id = 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 `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  = 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 `getAlert3State__`(vTicket INT) RETURNS varchar(45) CHARSET utf8 COLLATE utf8_unicode_ci
    READS SQL DATA
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 `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)
    READS SQL DATA
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;
    
		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)
    READS SQL DATA
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
 *
 * #UPDATED PAK 2019/08/16
 * #PENDING REVIEW
 **/
 
	DECLARE vToday DATETIME DEFAULT CURDATE();
	DECLARE vYesterday DATETIME;
	DECLARE vTodayvMidniight DATETIME DEFAULT midnight(vToday);
	DECLARE vTicket INT DEFAULT NULL;
    DECLARE PREVIOUS_PREPARATION INT;
    DECLARE vHasBeenPreviouslyPrepared INT DEFAULT 0;
        
    -- Si hay algun ticket previamente seleccionado, y se ha quedado sin empezar, lo recupera en primer lugar.
   /* 
	SELECT i.Id_Ticket INTO vTicket
		FROM vncontrol.inter i
			JOIN vn.state s ON s.id = i.state_id
			LEFT JOIN
				(SELECT DISTINCT s.ticketFk
					FROM vn.sale s
						JOIN vn.saleTracking st ON st.saleFk = s.id
                        JOIN vn.ticketStateToday tst ON tst.ticket = s.ticketFk
                        WHERE st.created > CURDATE()
                        -- AND tst.`code` = 'ON_PREPARATION'
				) sub ON sub.ticketFk = i.Id_Ticket
		WHERE odbc_date > CURDATE()
			AND s.`code` = 'ON_PREPARATION'
			AND i.Id_Trabajador = vWorker
			AND sub.ticketFk IS NULL
		LIMIT 1;
        
	IF vTicket IS NULL THEN
    */
		SELECT id INTO PREVIOUS_PREPARATION
			FROM vn.state
			WHERE code LIKE 'PREVIOUS_PREPARATION';

		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';
			   
		DELETE wc.* 													
			FROM tmp.workerComercial wc
				JOIN `grant` g ON g.worker = wc.worker
				JOIN grantGroup gg ON g.`group` = gg.id 
			WHERE gg.description  = 'Gerencia';  
			
		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
					, IF (HOUR(t.shipped),HOUR(t.shipped),HOUR(z.`hour`)) as Hora
					, HOUR(t.shipped) as Departure
					, IF (MINUTE(t.shipped),MINUTE(t.shipped),MINUTE(z.`hour`)) 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
					LEFT JOIN vn.zone z ON z.id = t.zoneFk
				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')
						OR 
							(tls.code = 'PRINTED PREVIOUS')
					);
		 
		 
		SELECT ticket INTO vTicket
			FROM tmp.production_buffer
			ORDER BY (code = 'PICKER_DESIGNED') DESC, (code = 'PRINTED PREVIOUS') DESC ,Hora, Minuto,   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;

	-- 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  = 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 `getUser`() RETURNS int(11)
    DETERMINISTIC
BEGIN
/**
 * @deprecated Use account.userGetId()
 */
    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  = 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 `getWorker`() RETURNS int(11)
    DETERMINISTIC
BEGIN
/**
 * @deprecated Use myWorker_getId()
 */
    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)
    DETERMINISTIC
BEGIN 

/*	Calcula si existe alguna base imponible negativa
*	Requiere la tabla temporal vn.ticketToInvoice(id)
*
*	returns BOOLEAN
*/
	DECLARE hasAnyNegativeBase BOOLEAN;
    
	DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
	CREATE TEMPORARY TABLE tmp.ticket
		(KEY (ticketFk))
		ENGINE = MEMORY
		SELECT id ticketFk
			FROM ticketToInvoice;
            
	CALL ticket_getTax(NULL);

	SELECT COUNT(*) INTO hasAnyNegativeBase
		FROM(
			SELECT SUM(taxableBase) as taxableBase
				FROM tmp.ticketTax
				GROUP BY pgcFk
				HAVING taxableBase < 0
			) t;

	DROP TEMPORARY TABLE tmp.ticketTax;
	DROP TEMPORARY TABLE tmp.ticket;
    
	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 `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)
    DETERMINISTIC
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 `hasZone` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `hasZone`(vLanded DATE, vAddress INT, vAgencyModeFk INT) RETURNS tinyint(1)
    DETERMINISTIC
BEGIN
	DECLARE vHasZone BOOLEAN DEFAULT FALSE;

	SELECT COUNT(*), id zoneFk, isIncluded INTO vHasZone, @trash, @trash 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
					AND zc.delivered = vLanded
					AND z.agencyModeFk = vAgencyModeFk
					AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE)
				WHERE zi.isIncluded
			ORDER BY z.id, landed ASC, zgFather.depth DESC) t 
		GROUP BY id
		HAVING isIncluded > 0 LIMIT 1;
	RETURN vHasZone;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `invoiceOut_getPath` */;
/*!50003 SET @saved_cs_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 `invoiceOut_getPath`(vSelf INT) RETURNS varchar(255) CHARSET utf8
    DETERMINISTIC
BEGIN
	DECLARE vIssued DATE;
	DECLARE vSerial VARCHAR(15);

	SELECT issued, ref 
		INTO vIssued, vSerial
		FROM invoiceOut WHERE id = vSelf;

	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 `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
    DETERMINISTIC
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 vTaxArea VARCHAR(25);
	DECLARE vSerie CHAR(1);

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

	SELECT clientTaxArea(vClientFk, vCompanyFk) INTO vTaxArea;
    SELECT invoiceSerialArea(vType,vTaxArea) INTO vSerie;
	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 `invoiceSerialArea` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceSerialArea`(vType CHAR(1), vTaxArea VARCHAR(25)) RETURNS char(1) CHARSET utf8 COLLATE utf8_unicode_ci
    DETERMINISTIC
BEGIN
	
	DECLARE vSerie CHAR(1);
    
	IF vType = 'R' THEN
		SELECT 
			CASE vTaxArea 
				WHEN 'CEE'
			THEN 'H'
				WHEN 'WORLD'
			THEN 'E'
				WHEN 'NATIONAL' 
			THEN 'T'
		END
		INTO vSerie;
		-- Factura multiple
	ELSEIF vType = 'M' THEN
		SELECT 
			CASE vTaxArea 
				WHEN 'CEE'
			THEN 'H'
				WHEN 'WORLD'
			THEN 'E'
				WHEN 'NATIONAL' 
			THEN 'M'
		END
		INTO vSerie;
	-- Factura global
	ELSEIF vType = 'G' THEN
		SELECT 
			CASE vTaxArea 
				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)
    DETERMINISTIC
BEGIN

	DECLARE vPacking INTEGER DEFAULT 0;
    DECLARE vItemFk INTEGER;
    
    SELECT vn.barcodeToItem(vBarcode) INTO vItemFk;
    
    SELECT IFNULL(packing,0) INTO vPacking 
		FROM vn.buy 
        WHERE id = CAST(vBarcode AS DECIMAL(18,0));
    
    
    
    
    IF NOT vPacking THEN
		CALL cache.last_buy_refresh(FALSE);
		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 `itemShelvingPlacementSupply_ClosestGet` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `itemShelvingPlacementSupply_ClosestGet`(vParkingFk INT) RETURNS int(11)
    READS SQL DATA
BEGIN

	/* Devuelve el parking más cercano.*/
	DECLARE vColumn INT;
    DECLARE vClosestParkingFk INT;
    DECLARE vSectorFk INT;
    
	SELECT p.column, sectorFk INTO vColumn, vSectorFk
		FROM vn.parking p
        WHERE p.id = vParkingFk;
    
    SELECT itemShelvingFk INTO vClosestParkingFk
		FROM
		(
			SELECT ABS(p.column - vColumn) as distance, itemShelvingFk
				FROM vn.itemShelvingPlacementSupplyStock ispss
					JOIN vn.parking p ON p.id = ispss.parkingFk
                    JOIN vn.itemPlacementSupplyList ipsl ON ipsl.sectorFk = ispss.sectorFk AND ipsl.itemFk = ispss.itemFk
				WHERE p.sectorFk = vSectorFk
					AND ipsl.saldo > 0
		) sub 
        ORDER BY distance
        LIMIT 1;
            
	RETURN vClosestParkingFk;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `itemTag_getIntValue` */;
/*!50003 SET @saved_cs_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 `itemTag_getIntValue`(vValue VARCHAR(255)) RETURNS int(11)
    DETERMINISTIC
BEGIN
	IF vValue NOT REGEXP '^-?[0-9]+' THEN
		RETURN NULL;
	END IF;

	RETURN CAST(vValue AS SIGNED);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `item_getVolume` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `item_getVolume`(vSelf INT, vPackaging VARCHAR(10)) RETURNS int(11)
    DETERMINISTIC
BEGIN
/**
 * Calculates the volume occupied by an item together
 * with its packaging.
 *
 * @param vSelf The item id
 * @param vPackaging The packaging id
 * @return The volume in cubic centimeters
 */
	DECLARE vVolume INT;

	SELECT SUM(IF(p.volume > 0,
			p.volume,
			p.width * p.depth * IF(p.height, p.height, i.size + 10)
		)) INTO vVolume
		FROM packaging p
			JOIN item i ON i.id = vSelf
		WHERE p.id = vPackaging;
		
	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 `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 `myWorker_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 `myWorker_getId`() RETURNS int(11)
    DETERMINISTIC
BEGIN
/**
 * Returns the current worker id or the default worker id
 * if current user cannot be retrieved.
 *
 * @return The worker id
 */
    DECLARE vWorker INT;
    
    SELECT IFNULL(w.id, c.defaultWorkerFk) INTO vWorker
        FROM worker w, workerConfig c
        WHERE w.userFk = account.userGetId();
    
    RETURN 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 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  = 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 `nz`(vQuantity DOUBLE) RETURNS double
    DETERMINISTIC
BEGIN

	DECLARE vResult DOUBLE;

	SET vResult = IFNULL(vQuantity,0);

	RETURN 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 `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 saleVolume
			WHERE ticketFk = 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,1)
    DETERMINISTIC
BEGIN

/* 
 *  Devuelve el volumen estimado del ticket sumado, en cajas
 *
 *	vTicketId 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 `till_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`@`%` FUNCTION `till_new`(
	 vClient INT
	,vBank INT
	,vAmount DOUBLE
	,vConcept VARCHAR(25)
	,vDated DATE
	,vSerie CHAR(1)
	,vBatch TINYINT
	,vNumber INT
	,vCompany SMALLINT
	,vWorker INT
) RETURNS int(11)
    DETERMINISTIC
BEGIN
	DECLARE vAccount VARCHAR(12);
	DECLARE vSubaccount VARCHAR(12);
	DECLARE vAsiento INT DEFAULT NULL;

	-- Inserta el registro en cajas

	INSERT INTO till
	SET
		workerFk = vWorker
		,bankFk = vBank
		,`in` = vAmount
		,concept = vConcept
		,dated = vDated
		,serie = vSerie
		,isAccountable = vBatch
		,`number` = vNumber
		,companyFk = vCompany;

	-- Inserta los asientos contables

	SELECT account INTO vAccount
		FROM bank WHERE id = vBank;

	SELECT accountingAccount INTO vSubaccount
		FROM `client` WHERE id = vClient;

	SET vAsiento = xdiario_new
	(
		vAsiento
		,vDated
		,vAccount
		,vSubaccount
		,vConcept
		,vAmount
		,0
		,0
		,NULL -- Serie
		,NULL -- Factura
		,NULL -- IVA
		,NULL -- Recargo
		,FALSE -- Auxiliar
		,vCompany
	);
	DO xdiario_new
	(
		vAsiento
		,vDated
		,vSubaccount
		,vAccount
		,vConcept
		,0
		,vAmount
		,0
		,NULL -- Serie
		,NULL -- Factura
		,NULL -- IVA
		,NULL -- Recargo
		,FALSE -- Auxiliar
		,vCompany
	);

	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 `timeWorkerControl_getDirection` */;
/*!50003 SET @saved_cs_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 `timeWorkerControl_getDirection`(vUserFk INT, vTimed DATETIME) RETURNS varchar(6) CHARSET utf8 COLLATE utf8_unicode_ci
    READS SQL DATA
BEGIN
/**
 * Verifica la dirección de la fichada 
 * @param vUserFk Identificador del trabajador
 * @param vTimed Hora de la fichada
 * @return Retorna sentido de la fichada 'in, out, middle'
 */

	DECLARE vPrevious DATETIME ;
    DECLARE vNext DATETIME ;
    DECLARE vPreviousDirection VARCHAR(3) ;
    DECLARE vNextDirection VARCHAR(3) ;
    DECLARE vDayStayMax INT;
    DECLARE vTimedSeconds INT;
    DECLARE vLastTimeIn INT;
	
    SELECT UNIX_TIMESTAMP(vTimed) INTO vTimedSeconds;
    
    SELECT dayStayMax INTO vDayStayMax
		FROM vn.workerTimeControlParams;

    SELECT timed, direction INTO vNext,vNextDirection
		FROM vn.workerTimeControl 
        WHERE userFk = vUserFk 
			AND direction IN ('in','out')
            AND timed > vTimed
		ORDER BY timed ASC
        LIMIT 1;
        
    SELECT timed, direction INTO vPrevious, vPreviousDirection
		FROM vn.workerTimeControl 
        WHERE userFk = vUserFk 
			AND direction IN ('in','out')
            AND timed < vTimed
		ORDER BY timed DESC
        LIMIT 1;   
	
    IF (vTimedSeconds - UNIX_TIMESTAMP(vPrevious) + UNIX_TIMESTAMP(vNext) - vTimedSeconds)<= vDayStayMax AND vPreviousDirection = 'in'  AND vNextDirection = 'out' THEN 
		RETURN 'middle';
	END IF;
    
    
    IF (vTimedSeconds> UNIX_TIMESTAMP(vPrevious)) THEN
		IF vPreviousDirection = 'in' THEN 
			RETURN 'out';
		ELSE
			SELECT UNIX_TIMESTAMP(MAX(timed)) INTO vLastTimeIn
				FROM vn.workerTimeControl 
				WHERE userFk = vUserFk 
					AND direction ='in'
					AND timed < vPrevious;
			IF vTimedSeconds - vLastTimeIn <= vDayStayMax THEN
				RETURN 'out';
            END IF;
		END IF;
	END IF;

	RETURN 'in';
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `validationCode` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `validationCode`(vString VARCHAR(255)) RETURNS int(11)
    DETERMINISTIC
BEGIN

	DECLARE vTail VARCHAR(3);
	DECLARE vCode INT;
    
    SET vTail = LEFT(LPAD(vString,3,'0'),3);

	SET vCode = (ASCII(MID(vTail,1,1)) * ASCII(MID(vTail,2,1)) * ASCII(MID(vTail,3,1))) mod 1000;

	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 `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 FUNCTION IF EXISTS `workerTimeControl_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`@`%` FUNCTION `workerTimeControl_add`( vUserFk INT,  vWarehouseFk INT,  vTimed DATETIME,  vIsManual BOOL) RETURNS int(11)
    DETERMINISTIC
BEGIN
	DECLARE vDirection VARCHAR(6);
	DECLARE vLastIn DATETIME;
	DECLARE vDayStayMax INT;
    DECLARE vHasDirectionOut INT;
    DECLARE vLastInsertedId INT;

    SELECT dayStayMax INTO vDayStayMax
		FROM workerTimeControlParams;
        
    SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection;

	IF vDirection = 'out' THEN
	
		SELECT MAX(timed) INTO vLastIn
			FROM workerTimeControl 
			WHERE userFk = vUserFk 
				AND direction = 'in'
				AND timed < vTimed;
	
		UPDATE  workerTimeControl wtc
			SET wtc.direction = 'middle'
			WHERE userFk = vUserFk
				AND direction = 'out'
				AND timed BETWEEN vLastIn AND vTimed;
	
	ELSE IF vDirection = 'in' THEN
			
            SELECT COUNT(*) INTO vHasDirectionOut 
				FROM workerTimeControl wtc
				WHERE userFk = vUserFk 
					AND direction = 'out'
					AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);          

			UPDATE  workerTimeControl wtc
				SET wtc.direction = IF (vHasDirectionOut,'middle','out')
				WHERE userFk = vUserFk
					AND direction = 'in'
					AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);  

		 END IF;
     END IF;
	
	INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual)
		VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual);
        
	SET vLastInsertedId = LAST_INSERT_ID();
    
    CALL workerTimeControlSOWP(vUserFk, vTimed);
    
	RETURN vLastInsertedId;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `xdiario_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`@`%` FUNCTION `xdiario_new`(
	vAsiento INT,
	vDated DATE,
	vSubaccount VARCHAR(12),
	vAccount VARCHAR(12),
	vConcept VARCHAR(25),
	vDebit DOUBLE,
	vCredit DOUBLE,
	vEuro DOUBLE,
	vSerie CHAR(1),
	vInvoice VARCHAR(8),
	vVat DOUBLE,
	vRe DOUBLE,
	vAux TINYINT,
	vCompany INT
) RETURNS int(11)
    NO SQL
BEGIN
	IF vAsiento IS NULL THEN
        CALL vn.ledger_next(vAsiento);
	END IF;

	INSERT INTO XDiario
	SET ASIEN = vAsiento,
		FECHA = vDated,
		SUBCTA = vSubaccount,
		CONTRA = vAccount,
		CONCEPTO = vConcept,
		EURODEBE = vDebit,
		EUROHABER = vCredit,
		BASEEURO = vEuro,
		SERIE = vSerie,
		FACTURA = vInvoice,
		IVA = vVat,
		RECEQUIV = vRe,
		AUXILIAR = IF(vAux = FALSE, NULL, '*'),
		MONEDAUSO = 2,
		empresa_id = vCompany;

	RETURN vAsiento;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `zoneGeo_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`@`%` FUNCTION `zoneGeo_new`(vType VARCHAR(255), vName VARCHAR(255), vParentFk INT) RETURNS int(11)
    NO SQL
BEGIN
/**
 * Creates a new node a node from the #zoneGeo table.
 * Also sets a mark to force the tree recalculation.
 *
 * @param vType The node type
 * @param vName The node name
 * @param vParentFk The parent node identifier
 * @return The new node identifier
 */
	DECLARE vSelf INT;

	INSERT INTO zoneGeo
		SET `type` = vType,
			`name` = vName,
			parentFk = vParentFk;
            
	SET vSelf = LAST_INSERT_ID();

	UPDATE zoneGeoRecalc SET isChanged = TRUE;

    RETURN 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 `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 `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 `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 `available_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 `available_calc`(
	vDate DATE,
    vAddress INT,
    vAgencyMode INT)
BEGIN
/**
 * Calculates the available for all available stores
 * according to the given parameters.
 *
 * @param vDate The delivery date
 * @param vAddress The delivery address id
 * @param vAgencyMode The shipping agency
 * @return tmp.availableCalc(calcFk) The available cache ids
 */
	DECLARE vCalcFk INT;
	DECLARE vShipment DATE;
	DECLARE vWarehouse INT;
	DECLARE vDone BOOL;

	DECLARE cWarehouses CURSOR FOR
		SELECT warehouseFk, shipped FROM tmp.zoneGetShipped;
			
	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	-- Establecemos los almacenes y las fechas que van a entrar al disponible

	CALL vn.zone_getShippedWarehouse(vDate, vAddress, vAgencyMode);

	DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc;
	CREATE TEMPORARY TABLE tmp.availableCalc(	
		calcFk INT UNSIGNED,
		PRIMARY KEY (calcFk)
	)
	ENGINE = MEMORY;

	OPEN cWarehouses;

	l: LOOP
		SET vDone = FALSE;
		FETCH cWarehouses INTO vWarehouse, vShipment;
		
		IF vDone THEN
			LEAVE l;
		END IF;

		CALL `cache`.available_refresh(vCalcFk, FALSE, vWarehouse, vShipment);

		INSERT IGNORE INTO tmp.availableCalc
			SET calcFk = vCalcFk;
	END LOOP;

	CLOSE cWarehouses;
	DROP TEMPORARY TABLE tmp.zoneGetShipped;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_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;
    DECLARE vLanded DATE;
    DECLARE vBuyerFk INT;
    DECLARE vItemName VARCHAR(50);
    
	SELECT entryFk, itemFk, stickers, packing
		INTO vEntryFk, vItemFk, vStickers, vPacking
		FROM buy
		WHERE id = vSelf;

	SELECT t.warehouseInFk, t.warehouseOutFk, t.landed
		INTO vWarehouse, vWarehouseOut, vLanded
		FROM entry e
			JOIN travel t ON t.id = e.travelFk
		WHERE e.id = vEntryFk;

	SELECT k.merchandise, it.workerFk, i.longName
		INTO vIsMerchandise, vBuyerFk, vItemName
		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 = buy_getUnitVolume(vSelf);
	END IF;

	SELECT isFeedStock INTO vIsFeedStock
		FROM warehouse WHERE id = vWarehouseOut AND id <> 13;

	IF vIsFeedStock THEN
		INSERT IGNORE INTO producer(`name`)
			SELECT es.company_name
				FROM buy b
					JOIN edi.ekt be ON be.id = b.ektFk
					JOIN edi.supplier es ON es.supplier_id = be.pro
				WHERE b.id = vSelf;
                
		IF vn2008.has_notify_passport(vItemFk, vSelf) THEN
			CALL vn.buy_notifyPassport(vSelf, vItemFk, vStickers, vPacking);
		END IF;
	END IF;
    
    -- Aviso al comprador de modificacion de entrada en Barajas
	IF (SELECT isBuyerToBeEmailed FROM warehouse WHERE id = vWarehouse)
		AND vLanded = CURDATE()
        AND vBuyerFk != account.myUserGetId() 
	THEN
        
        CALL vn.mail_insert(CONCAT(account.userGetNameFromId(vBuyerFk),'@verdnatura.es'),
							CONCAT(account.myUserGetName(),'@verdnatura.es'),
                            CONCAT('E ',vEntryFk,' Se ha modificado item ', vItemFk, ' ',vItemName),
                            'Este email se ha generado automáticamente');
           
	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_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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_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 = buy_getUnitVolume(vSelf);
	END IF;

	SELECT isFeedStock INTO vIsFeedStock
		FROM warehouse WHERE id = vWarehouseOut AND id <> 13;

	IF vIsFeedStock AND buy_hasNotifyPassport(vSelf, vItemFk) THEN
		CALL buy_notifyPassport(vSelf, vItemFk, vStickers, vPacking);
		INSERT IGNORE INTO producer(`name`)
			SELECT es.company_name
				FROM buy b
					JOIN edi.ekt be ON be.id = b.ektFk
					JOIN edi.supplier es ON es.supplier_id = be.pro
				WHERE b.id = 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 `buy_notifyPassport` */;
/*!50003 SET @saved_cs_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_notifyPassport`(
	IN vBuyFk INT,
	IN vItemFk INT,
    IN vStickers SMALLINT,
    IN vPacking SMALLINT
)
BEGIN
	INSERT INTO vn.mail(`subject`,`body`,`sender`) 
		SELECT 'Solicitar pasaporte',
				CONCAT(
					'Etiquetas: ', IFNULL(vStickers, 0),
                    ', Packing: ', IFNULL(vPacking, 0),
                    ', Nombre: ', IFNULL(i.`name`, 0),
                    ', buy_edi: ', IFNULL(e.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 item i
				LEFT JOIN itemBotanical ib ON ib.itemFk = i.id
				LEFT JOIN edi.genus g ON g.genus_id = ib.genusFk
				LEFT JOIN edi.specie s ON IFNULL(s.specie_id, ib.specieFk) = ib.specieFk
				LEFT JOIN producer p ON p.id = i.producerFk
				LEFT JOIN buy b ON b.id = vBuyFk
				LEFT JOIN edi.ekt e ON b.ektFk = e.id
				LEFT JOIN edi.supplier es ON es.supplier_id = e.pro
			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 `camaraFutureVolume` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `camaraFutureVolume`(vWarehouseFk INT, vDateStart DATE, vDateEnd DATE)
BEGIN

	DECLARE vDated DATE;
    DECLARE vSectorVolume INT;
    DECLARE vLastDayVolume INT;
    DECLARE vMinCamara INT;

	SET vDated = vDateStart;
    
    DROP TEMPORARY TABLE IF EXISTS tmp.camara;
    
	IF vDateStart = CURDATE() THEN
    
		CREATE TEMPORARY TABLE tmp.camara
		SELECT 	vDated as dated, 
				CONCAT('sector ', sectorFk) as place, 
				FLOOR(SUM(ish.visible * r.cm3)/1000000) as m3
		FROM vn.itemShelving ish
			JOIN bi.rotacion r ON r.Id_Article = ish.itemFk AND r.warehouse_id = vWarehouseFk
			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 = vWarehouseFk
			GROUP BY p.sectorFk;

		SELECT m3 
			INTO vSectorVolume 
			FROM tmp.camara 
			WHERE place LIKE 'sector%';
				
		CALL cache.visible_refresh(@calc_id, FALSE, 1);

		INSERT INTO tmp.camara(dated, place, m3)
			SELECT 	vDated, 'nicho', 
					FLOOR((SUM(v.visible * r.cm3) / 1000000) - vSectorVolume ) as m3
			FROM cache.visible v
				JOIN bi.rotacion r ON r.Id_Article = v.item_id AND r.warehouse_id = vWarehouseFk
				JOIN vn.item i ON i.id = v.item_id
				JOIN vn.itemType it ON it.id = i.typeFk
				JOIN vn.itemCategory ic ON ic.id = it.categoryFk
				WHERE calc_id = @calc_id
					AND ic.merchandise;

		INSERT INTO tmp.camara(dated, place, m3)
			SELECT vDated, 'entradas', FLOOR(SUM(iei.amount * r.cm3) / 1000000) as m3
				FROM vn2008.item_entry_in iei
					JOIN bi.rotacion r ON r.Id_Article = iei.item_id AND r.warehouse_id = vWarehouseFk
					JOIN vn.item i ON i.id = iei.item_id
					JOIN vn.itemType it ON it.id = i.typeFk
					JOIN vn.itemCategory ic ON ic.id = it.categoryFk
				WHERE ic.merchandise
					AND dat = vDated
					AND NOT received
					AND NOT isVirtualStock
					AND iei.warehouse_id = vWarehouseFk;
                    
		INSERT INTO tmp.camara(dated, place, m3)
			SELECT vDated, 'salidas', FLOOR(SUM(ieo.amount * r.cm3) / 1000000) as m3
				FROM vn2008.item_entry_out ieo
					JOIN bi.rotacion r ON r.Id_Article = ieo.item_id AND r.warehouse_id = vWarehouseFk
					JOIN vn.item i ON i.id = ieo.item_id
					JOIN vn.itemType it ON it.id = i.typeFk
					JOIN vn.itemCategory ic ON ic.id = it.categoryFk
				WHERE ic.merchandise
					AND dat = vDated
					AND NOT delivered
					AND NOT isVirtualStock
					AND ieo.warehouse_id = vWarehouseFk;
					
		INSERT INTO tmp.camara(dated, place, m3)
			SELECT vDated, 'ventas', FLOOR(SUM(io.amount * r.cm3) / 1000000) as m3
				FROM vn2008.item_out io
					JOIN bi.rotacion r ON r.Id_Article = io.item_id AND r.warehouse_id = vWarehouseFk
					JOIN vn.item i ON i.id = io.item_id
					JOIN vn.itemType it ON it.id = i.typeFk
					JOIN vn.itemCategory ic ON ic.id = it.categoryFk
					JOIN vn.ticketStateToday tst ON tst.ticket = io.ticketFk
                    JOIN vn.ticket t ON t.id = io.ticketFk
				WHERE ic.merchandise
					AND ic.id != 7
					AND t.clientFk NOT IN (200,400,50,450)
					AND dat BETWEEN vDated AND util.dayend(vDated)
					AND NOT tst.isPicked
					AND io.warehouse_id = vWarehouseFk;
                    
	ELSE
    
		CREATE TEMPORARY TABLE tmp.camara
			SELECT 	vDated as dated, 
				'entradas' as place, 
                FLOOR(SUM(iei.amount * r.cm3) / 1000000) as m3
				FROM vn2008.item_entry_in iei
					JOIN bi.rotacion r ON r.Id_Article = iei.item_id AND r.warehouse_id = vWarehouseFk
					JOIN vn.item i ON i.id = iei.item_id
					JOIN vn.itemType it ON it.id = i.typeFk
					JOIN vn.itemCategory ic ON ic.id = it.categoryFk
				WHERE ic.merchandise
					AND dat = vDated
					AND NOT isVirtualStock
					AND iei.warehouse_id = vWarehouseFk;
                    
        INSERT INTO tmp.camara(dated, place, m3)            
			SELECT vDated, 'salidas', FLOOR(SUM(ieo.amount * r.cm3) / 1000000) as m3
				FROM vn2008.item_entry_out ieo
					JOIN bi.rotacion r ON r.Id_Article = ieo.item_id AND r.warehouse_id = vWarehouseFk
					JOIN vn.item i ON i.id = ieo.item_id
					JOIN vn.itemType it ON it.id = i.typeFk
					JOIN vn.itemCategory ic ON ic.id = it.categoryFk
				WHERE ic.merchandise
					AND dat = vDated
					AND ieo.warehouse_id = vWarehouseFk;
                    
		INSERT INTO tmp.camara(dated, place, m3)
			SELECT vDated, 'ventas', FLOOR(SUM(io.amount * r.cm3) / 1000000) as m3
				FROM vn2008.item_out io
					JOIN bi.rotacion r ON r.Id_Article = io.item_id AND r.warehouse_id = vWarehouseFk
					JOIN vn.item i ON i.id = io.item_id
					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 = io.ticketFk
				WHERE ic.merchandise
					AND dat BETWEEN vDated AND util.dayend(vDated)
                    AND ic.id != 7
					AND t.clientFk NOT IN (200,400,50,450)
					AND io.warehouse_id = vWarehouseFk;   
            
	END IF;
    
    -- Resto de dias
    WHILE vDated < vDateEnd DO
    
		SELECT SUM(IFNULL(m3,0)) INTO vLastDayVolume
			FROM tmp.camara
			WHERE dated = vDated;
			
		SET vDated = TIMESTAMPADD(DAY, 1, vDated);
				
		INSERT INTO tmp.camara(dated, place, m3)
			VALUES( vDated, 'camara', vLastDayVolume);
			   
		INSERT INTO tmp.camara(dated, place, m3)
			SELECT vDated, 'entradas', FLOOR(SUM(iei.amount * r.cm3) / 1000000) as m3
				FROM vn2008.item_entry_in iei
					JOIN bi.rotacion r ON r.Id_Article = iei.item_id AND r.warehouse_id = vWarehouseFk
					JOIN vn.item i ON i.id = iei.item_id
					JOIN vn.itemType it ON it.id = i.typeFk
					JOIN vn.itemCategory ic ON ic.id = it.categoryFk
				WHERE ic.merchandise
					AND dat = vDated
					AND NOT isVirtualStock
					AND iei.warehouse_id = vWarehouseFk;
		
		INSERT INTO tmp.camara(dated, place, m3)            
			SELECT vDated, 'salidas', FLOOR(SUM(ieo.amount * r.cm3) / 1000000) as m3
				FROM vn2008.item_entry_out ieo
					JOIN bi.rotacion r ON r.Id_Article = ieo.item_id AND r.warehouse_id = vWarehouseFk
					JOIN vn.item i ON i.id = ieo.item_id
					JOIN vn.itemType it ON it.id = i.typeFk
					JOIN vn.itemCategory ic ON ic.id = it.categoryFk
				WHERE ic.merchandise
					AND dat = vDated
					AND ieo.warehouse_id = vWarehouseFk;
                    
		INSERT INTO tmp.camara(dated, place, m3)
			SELECT vDated, 'ventas', FLOOR(SUM(io.amount * r.cm3) / 1000000) as m3
				FROM vn2008.item_out io
					JOIN bi.rotacion r ON r.Id_Article = io.item_id AND r.warehouse_id = vWarehouseFk
					JOIN vn.item i ON i.id = io.item_id
					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 = io.ticketFk
				WHERE ic.merchandise
					AND dat BETWEEN vDated AND util.dayend(vDated)
                    AND ic.id != 7
					AND t.clientFk NOT IN (200,400,50,450)
					AND io.warehouse_id = vWarehouseFk;   
                    
	END WHILE;
    
    SELECT min(m3) INTO vMinCamara
		FROM
        (SELECT dated, sum(m3) m3
			FROM tmp.camara
			GROUP BY dated) sub;
	
	UPDATE tmp.camara
		SET m3 = m3 - vMinCamara
        WHERE place = 'camara';
        
	SELECT camara.* FROM tmp.camara;
    
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 `catalog_calcFromItem` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calcFromItem`(
	vLanded DATE,
    vAddressFk INT,
    vAgencyModeFk INT,
    vItemFk INT)
BEGIN
/**
 * Calculates available and price for a single item.
 *
 * @param vItemFk The item id
 * @return tmp.ticketCalculateItem
 * @return tmp.ticketComponentPrice
 * @return tmp.ticketComponent
 * @return tmp.ticketLot
 * @return tmp.zoneGetShipped
 */
	DROP TEMPORARY TABLE IF EXISTS tmp.item;
	CREATE TEMPORARY TABLE tmp.item
		ENGINE = MEMORY 
		SELECT vItemFk itemFk;

	CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk);
	DROP TEMPORARY TABLE 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 `catalog_calculate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calculate`(
    vLanded DATE,
    vAddressFk INT,
    vAgencyModeFk INT)
proc: BEGIN
/**
 * Calcula los articulos disponibles y sus precios
 * 
 * @table tmp.item(itemFk) Listado de artÃ­culos a calcular
 * @param vLanded Fecha de recepcion de mercancia
 * @param vAddressFk Id del consignatario
 * @param vAgencyModeFk Id de la agencia
 * @return tmp.ticketCalculateItem(itemFk, available, producer, 
 *			item, size, stems, category, inkFk, image, origin, price)
 * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk)
 * @return tmp.ticketComponent
 * @return tmp.ticketComponentPrice
 * @return tmp.zoneGetShipped

 **/
 
    DECLARE vAvailableCalc INT;
    DECLARE vShipped DATE;
    DECLARE vClient INT;
    DECLARE vWarehouseFk SMALLINT;
    DECLARE vZoneFk INT;
    DECLARE vDone BOOL;
    DECLARE cTravelTree CURSOR FOR
        SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
    
    -- Establece los almacenes y las fechas que van a entrar al disponible

    SELECT clientFk INTO vClient
        FROM address WHERE id = vAddressFk;

    CALL vn.zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk);

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
    CREATE TEMPORARY TABLE tmp.ticketLot(
      `warehouseFk` smallint(5) unsigned NOT NULL,
      `itemFk` int(11) NOT NULL,
      `available` double DEFAULT NULL,
      `buyFk` int(11) DEFAULT NULL,
      `fix` tinyint(3) unsigned DEFAULT '0',
      KEY `itemFk` (`itemFk`),
      KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH
    ) ENGINE=MEMORY DEFAULT CHARSET=utf8;

    OPEN cTravelTree;

    l: LOOP
        SET vDone = FALSE;
        FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped;

        IF vDone THEN
            LEAVE l;
        END IF;

        CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped);
        CALL buyUltimate (vWarehouseFk, vShipped);

        INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk)
			SELECT vWarehouseFk,
					i.item_id,
					IFNULL(i.available, 0),
					bu.buyFk
				FROM `cache`.available i
					JOIN tmp.item br ON br.itemFk = i.item_id
					LEFT JOIN item it ON it.id = i.item_id
					LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id
				WHERE i.calc_id = vAvailableCalc
					AND it.id != 100
					AND i.available > 0;
        
        DROP TEMPORARY TABLE tmp.buyUltimate;
    END LOOP;

    CLOSE cTravelTree;

    CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped);

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem;
    CREATE TEMPORARY TABLE tmp.ticketCalculateItem
    ENGINE = MEMORY
		SELECT 
				b.itemFk, 
				SUM(b.available) available,
				p.name producer, 
				i.name item, 
				i.size size,  
				i.stems,  
				i.category, 
				i.inkFk,  
				i.image,
				o.code origin, 
                bl.price,
                bl.priceKg
			FROM tmp.ticketLot b
				JOIN item i ON b.itemFk = i.id
				LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible
				JOIN origin o ON o.id = i.originFk
				JOIN (
					SELECT MIN(price) price, itemFk, priceKg
						FROM tmp.ticketComponentPrice
						GROUP BY itemFk
				) bl ON bl.itemFk = b.itemFk
			GROUP BY b.itemFk;
        
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `catalog_componentCalculate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `catalog_componentCalculate`(
    vZoneFk INT,
    vAddressFk INT,
    vShipped DATE)
proc: BEGIN
/**
 * Calcula los componentes de los articulos de tmp.ticketLot
 *
 * @param vZoneFk para calcular el transporte
 * @param vAgencyModeFk Id del modo de agencia
 * @param tmp.ticketLot (warehouseFk,available,itemFk,buyFk)
 *
 * @return tmp.ticketComponent(itemFk, warehouseFk, available, rate2, rate3, minPrice,
 *		packing, grouping, groupingMode, buyFk, typeFk)
 * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price)
 */
 
	DECLARE vClientFk INT;
    DECLARE vGeneralInflationCoefficient INT DEFAULT 1;
    DECLARE vMinimumDensityWeight INT DEFAULT 167;
	DECLARE vBoxFreightItem INT DEFAULT 71;
    DECLARE vBoxVolume BIGINT; -- DEFAULT 138000;
	DECLARE vSpecialPriceComponent INT DEFAULT 10;
	DECLARE vDeliveryComponent INT DEFAULT 15;
	DECLARE vRecoveryComponent INT DEFAULT 17;
	DECLARE vSellByPacketComponent INT DEFAULT 22;
	DECLARE vBuyValueComponent INT DEFAULT 28;
	DECLARE vMarginComponent INT DEFAULT 29;
	DECLARE vDiscountLastItemComponent INT DEFAULT 32;
	DECLARE vExtraBaggedComponent INT DEFAULT 38;
	DECLARE vManaAutoComponent INT DEFAULT 39;

    SELECT volume INTO vBoxVolume
		FROM vn.packaging
        WHERE id = '94';
        
    SELECT clientFk INTO vClientFK 
		FROM address 
        WHERE id = vAddressFk;

    SET @rate2 := 0;
    SET @rate3 := 0;

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate;
	CREATE TEMPORARY TABLE tmp.ticketComponentCalculate
	(PRIMARY KEY (itemFk, warehouseFk))
	ENGINE = MEMORY
		SELECT 
			tl.itemFk, tl.warehouseFk, tl.available,
			IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2,
			IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3,
            IFNULL(pf.rate3, 0) AS minPrice,
			IFNULL(pf.packing, b.packing) packing,
			IFNULL(pf.`grouping`, b.`grouping`) `grouping`,
			ABS(IFNULL(pf.box, b.groupingMode)) groupingMode,
            tl.buyFk, 
            i.typeFk,
            IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping
        FROM tmp.ticketLot tl
		JOIN buy b ON b.id = tl.buyFk
		JOIN item i ON i.id = tl.itemFk
        JOIN itemType it ON it.id = i.typeFk
        LEFT JOIN itemCategory ic ON ic.id = it.categoryFk
		LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk
		LEFT JOIN (
			SELECT * FROM (
				SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, zw.warehouseFk
					FROM priceFixed pf
					JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk AND (zw.warehouseFk = pf.warehouseFk OR pf.warehouseFk = 0)
						WHERE vShipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC
			) tpf
			GROUP BY tpf.itemFk, tpf.warehouseFk
		) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk
        WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.display <> 0;
        
    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, 
                c.id, 
                GREATEST(IFNULL(ROUND(tcb.base * c.tax, 4), 0), tcc.minPrice - tcc.rate3)
			FROM tmp.ticketComponentBase tcb
				JOIN `component` c
				JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk 
				LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk
			WHERE c.id = vDiscountLastItemComponent AND c.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL;
	
	INSERT INTO tmp.ticketComponent
		SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3 
			FROM tmp.ticketComponentCalculate tcc
				JOIN buy b ON b.id = tcc.buyFk
			LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk
		WHERE sp.value IS NULL;
             
	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((z.price - z.bonus)
					* 1/*amz.inflation*/ , 50)) / vBoxVolume, 4
				) cost
		FROM tmp.ticketComponentCalculate tcc
			JOIN item i ON i.id = tcc.itemFk
            JOIN zone z ON z.id = vZoneFk
			JOIN agencyMode am ON am.id = z.agencyModeFk
			LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk 
				AND r.Id_Article = tcc.itemFk
			HAVING cost <> 0; 
            
    IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN
		INSERT INTO tmp.ticketComponent
			SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost
				FROM tmp.ticketComponentCalculate tcc
					JOIN vn.addressForPackaging ap
				WHERE ap.addressFk = vAddressFk;
    END IF;
	
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy;
    CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY
		SELECT * FROM tmp.ticketComponent;
        
	INSERT INTO tmp.ticketComponent
		SELECT tcc.warehouseFk, 
				tcc.itemFk, 
				vSpecialPriceComponent, 
				sp.value - SUM(tcc.cost) sumCost
			FROM tmp.ticketComponentCopy tcc
				JOIN `component` c ON c.id = tcc.componentFk
				JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk
			WHERE c.classRate IS NULL
			GROUP BY tcc.itemFk, tcc.warehouseFk
			HAVING ABS(sumCost) > 0.001;
	
	DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum;
	CREATE TEMPORARY TABLE tmp.ticketComponentSum
		(INDEX (itemFk, warehouseFk))
		ENGINE = MEMORY
		SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, c.classRate
			FROM tmp.ticketComponent tc
				JOIN `component` c ON c.id = tc.componentFk
			GROUP BY tc.itemFk, tc.warehouseFk, c.classRate;

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate;
	CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY
		SELECT tcc.warehouseFk,  
				tcc.itemFk, 
				1 rate,
				IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, 
				CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price,
                CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg                
			FROM tmp.ticketComponentCalculate tcc
				JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk 
					AND tcs.warehouseFk = tcc.warehouseFk
			WHERE IFNULL(tcs.classRate, 1) = 1 
				AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0)
			GROUP BY tcs.warehouseFk, tcs.itemFk;

	INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg)
        SELECT 
				tcc.warehouseFk, 
				tcc.itemFk, 
				2 rate, 
				tcc.packing `grouping`, 
				SUM(tcs.sumCost) price,
                SUM(tcs.sumCost) / weightGrouping priceKg   
			FROM tmp.ticketComponentCalculate tcc
				JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk 
					AND tcs.warehouseFk = tcc.warehouseFk
			WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 
				AND tcc.packing > 0 AND tcc.available >= tcc.packing)
			GROUP BY tcs.warehouseFk, tcs.itemFk;

	INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg)
		 SELECT 				
		 		tcc.warehouseFk, 
				tcc.itemFk, 
				3 rate, 
				tcc.available `grouping`, 
				SUM(tcs.sumCost) price,
                SUM(tcs.sumCost) / weightGrouping priceKg   
			FROM tmp.ticketComponentCalculate tcc
				JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk 
					AND tcs.warehouseFk = tcc.warehouseFk
			WHERE IFNULL(tcs.classRate, 3) = 3 
			GROUP BY tcs.warehouseFk, tcs.itemFk;
        
	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 `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 vOneYearAgo DATE;
	DECLARE vFourYearsAgo DATE;
	DECLARE v18Month DATE;
    DECLARE v26Month DATE;
    DECLARE v3Month DATE;
    
	SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE());
	SET vOneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE());
	SET vFourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE());
    SET v18Month = TIMESTAMPADD(MONTH, -18,CURDATE());
	SET v26Month = TIMESTAMPADD(MONTH, -26,CURDATE());
    SET v3Month = TIMESTAMPADD(MONTH, -3, CURDATE());
    
    DELETE FROM workerTimeControlLog WHERE created < vDateShort;
	DELETE FROM `message` WHERE sendDate < vDateShort;
	DELETE FROM messageInbox WHERE sendDate < vDateShort;
	DELETE FROM messageInbox WHERE sendDate < vDateShort;
	DELETE FROM workerTimeControl WHERE timed < vFourYearsAgo;
	DELETE FROM itemShelving WHERE created < CURDATE() AND visible = 0;
	DELETE FROM ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE());
    DELETE FROM entryLog WHERE creationDate < vDateShort;
    DELETE FROM expedition WHERE created < v26Month;
    DELETE FROM sms WHERE created < v18Month;
    DELETE FROM saleTracking WHERE created < vDateShort;
    DELETE tobs FROM ticketObservation tobs 
		JOIN ticket t ON tobs.ticketFk = t.id WHERE t.shipped < vDateShort;
	DELETE FROM sharingCart where ended < vDateShort;
    DELETE FROM sharingClient where ended < vDateShort;
    DELETE tw.* FROM ticketWeekly tw 
		LEFT JOIN sale s ON s.ticketFk = tw.ticketFk WHERE s.itemFk IS NULL;
	DELETE FROM claim WHERE ticketCreated < v18Month;
	DELETE FROM message WHERE sendDate < vDateShort;
    DELETE FROM travelLog WHERE creationDate < v18Month;
    DELETE sc FROM saleChecked sc 
		JOIN sale s ON sc.saleFk = s.id WHERE s.created < vDateShort;
	DELETE bm
		FROM buyMark bm 
			JOIN buy b ON b.id = bm.id 
			JOIN entry e ON e.id = b.entryFk
			JOIN travel t ON t.id = e.travelFk
		WHERE t.landed <= vDateShort;
	DELETE FROM stowaway WHERE created < v3Month;
    
    	-- Equipos duplicados
	DELETE w.* 
		FROM workerTeam w
		JOIN (SELECT id, team, workerFk, COUNT(*) - 1 as duplicated
				FROM workerTeam
				GROUP BY team,workerFk
				HAVING duplicated
			 ) d ON d.team = w.team AND d.workerFk = w.workerFk AND d.id != w.id;
             
	    -- CAP 29/10/2018 Mantenimiento tabla Movimientos_componentes 
    DELETE sc 
		FROM  saleComponent sc
			JOIN sale s 
				ON s.id=  sc.saleFk
			JOIN ticket t 
				ON t.id= s.ticketFk
		WHERE t.shipped < v18Month;
	CALL shelving_clean;
			
	CALL 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 `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__`()
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;
	DELETE FROM vn.ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE());
	CALL shelving_clean;
			
	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  = 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 `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,
			TRIM(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

	UPDATE bi.defaulters d
			JOIN vn.client c ON c.id = d.client
            JOIN vn.config ON TRUE
		SET c.isFreezed = TRUE, frozened = CURDATE()
		WHERE d.amount > config.defaultersMaxAmount 
			AND d.`date` = CURDATE()
            AND frozened IS NULL;
        
	IF day(CURDATE()) IN (5,15,25) THEN
		
		UPDATE vn.client c
				JOIN bi.defaulters d ON d.client = c.id
				JOIN vn.config ON TRUE
				SET c.isFreezed = TRUE, frozened = CURDATE()
			WHERE d.amount > config.defaultersMaxAmount 
				AND c.typeFk = 'normal'
				AND d.date = 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 `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  = 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 `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, -35, 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 `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  = 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 `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 `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 sale s
						JOIN ticket t on t.id = s.ticketFk 
						JOIN packaging p ON p.itemFk = s.itemFk 
						LEFT JOIN packageEquivalentItem pe ON pe.itemFk = s.itemFk
						WHERE t.clientFk = vClientFk
						AND t.shipped > '2017-11-30' 
						AND p.isPackageReturnable
				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 ticketPackagingStartingStock tps
						LEFT JOIN 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 ticketPackaging tp 
					JOIN ticket t on t.id = tp.ticketFk 
					JOIN packaging p ON p.id = tp.packagingFk
					LEFT JOIN packageEquivalentItem pe ON pe.itemFk = p.itemFk
					WHERE t.clientFk = vClientFk
					AND t.shipped > '2017-11-21' ) x

					JOIN 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  = 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 `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()
				,1 -- Silla FV
				,442 -- Verdnatura
				,NULL -- address
				,2 -- Rec_Silla
				,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  = 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 `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;
        
        INSERT INTO vn.clientLog (originFk, userFk, `action`, description)
		VALUES (vClientFk, account.userGetId(), 'update', CONCAT('Se ha desasignado el cliente por que no ha comprado en 3 meses'));
        
		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_general_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 BOOLEAN DEFAULT FALSE;
	DECLARE vAuxEntryFk INT;
	DECLARE vRsEntry CURSOR FOR
		SELECT e.id
			FROM entry e
				JOIN travel t 
					ON t.id = e.travelFk
			WHERE e.travelFk = vTravelFk;
		
	 DECLARE vRsBuy CURSOR FOR
		SELECT b.*
			FROM buy b
				JOIN 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 = TRUE;
	
	DECLARE EXIT HANDLER FOR SQLEXCEPTION 
		BEGIN 
			ROLLBACK;
			RESIGNAL;
		END;
		  
	START TRANSACTION;
		  
	INSERT INTO travel (shipped,landed, warehouseInFk, warehouseOutFk, agencyFk, ref, isDelivered, isReceived, m3, kg)
		SELECT vDateStart, vDateEnd,warehouseInFk, warehouseOutFk, agencyFk, vRef, isDelivered, isReceived, m3, kg
			FROM travel
			WHERE id = vTravelFk;
		
	SET vTravelNew = LAST_INSERT_ID();
	SET vDone = FALSE;	 
	OPEN vRsEntry ;
	FETCH vRsEntry INTO vAuxEntryFk;
	
		WHILE NOT vDone DO
			INSERT INTO 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 entry
					WHERE id = vAuxEntryFk;
								
			SET vEntryNew  = LAST_INSERT_ID();
			
						
				 INSERT INTO buy (entryFk,
									itemFk,
									quantity,
									buyingValue,
									packageFk,
									stickers,
									freightValue,
									packageValue,
									comissionValue,
									packing,
									`grouping`,
									groupingMode,
									location,
									price1,
									price2,
									price3,
									minPrice,
									producer,
									printedStickers,
									isChecked,
									weight)
							SELECT vEntryNew,
									itemFk,
									quantity,
									buyingValue,
									packageFk,
									stickers,
									freightValue,
									packageValue,
									comissionValue,
									packing,
									`grouping`,
									groupingMode,
									location,
									price1,
									price2,
									price3,
									minPrice,
									producer,
									printedStickers,
									isChecked,
									weight
								FROM buy
								WHERE entryFk = 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 `collectionPlacement_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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `collectionPlacement_get`(vCollectionFk INT)
BEGIN
	DECLARE vCalcFk INT;
    DECLARE vWarehouseFk INT;
    DECLARE vWarehouseAliasFk INT;
    
    SELECT t.warehouseFk, w.aliasFk
		INTO vWarehouseFk, vWarehouseAliasFk
        FROM vn.ticket t
			JOIN vn.ticketCollection tc ON tc.ticketFk = t.id
            JOIN vn.warehouse w ON w.id = t.warehouseFk
        LIMIT 1;
        
	CALL cache.visible_refresh(vCalcFk,FALSE,vWarehouseFk);
    
    DROP TEMPORARY TABLE IF EXISTS tmp.parked;
    CREATE TEMPORARY TABLE tmp.parked
    ENGINE MEMORY
    SELECT 	s.itemFk, 0 as quantity
		FROM vn.ticketCollection tc
			JOIN vn.sale s ON s.ticketFk = tc.ticketFk
		WHERE tc.collectionFk = vCollectionFk;
    
	UPDATE tmp.parked pk
		JOIN ( SELECT itemFk, sum(visible) as visible
				FROM vn.itemShelvingStock iss 
					JOIN vn.warehouse w ON w.id = iss.warehouseFk
				WHERE  w.aliasFk = vWarehouseAliasFk
				GROUP BY iss.itemFk ) iss ON iss.itemFk = pk.itemFk
		SET pk.quantity = iss.visible;
        
	DROP TEMPORARY TABLE IF EXISTS tmp.`grouping`;
    CREATE TEMPORARY TABLE tmp.`grouping`
		ENGINE MEMORY
		SELECT itemFk, `grouping`
			FROM (
				SELECT itemFk,
					CASE groupingMode 
					   WHEN 0 THEN 1 
					   WHEN 2 THEN packing
					   ELSE `grouping`
					END	AS `grouping`
				FROM buy b
					JOIN entry e ON e.id = b.entryFk
					JOIN travel tr ON tr.id = e.travelFk
				WHERE tr.warehouseInFk = vWarehouseFk
					AND landed BETWEEN (SELECT FechaInventario FROM vn2008.tblContadores LIMIT 1) AND CURDATE()
					AND b.isIgnored = FALSE
				ORDER BY tr.landed DESC
			) sub
			GROUP BY sub.itemFk ;
                            
	DROP TEMPORARY TABLE IF EXISTS tmp.grouping2;
	CREATE TEMPORARY TABLE tmp.grouping2
		ENGINE MEMORY
		SELECT * FROM tmp.`grouping`;

	SELECT 	s.id as saleFk, s.itemFk,
			p.code COLLATE utf8_general_ci as placement ,
			sh.code COLLATE utf8_general_ci as shelving,
			ish.created,
			ish.visible,
			IFNULL(p.pickingOrder,0) as `order`,
            IF(sc.isPreviousPreparedByPacking, ish.packing, g.`grouping`) as `grouping`
		FROM vn.ticketCollection tc
			JOIN vn.sale s ON s.ticketFk = tc.ticketFk
            JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk
            JOIN vn.shelving sh ON sh.code = ish.shelvingFk
            JOIN vn.parking p ON p.id = sh.parkingFk
            JOIN vn.sector sc ON sc.id = p.sectorFk
            JOIN vn.warehouse w ON w.id = sc.warehouseFk
            JOIN tmp.`grouping` g ON g.itemFk = s.itemFk
		WHERE tc.collectionFk = vCollectionFk
			AND w.aliasFk = vWarehouseAliasFk
	UNION ALL
	SELECT	s.id as saleFk, s.itemFk,
			ip.code COLLATE utf8_general_ci as placement,
            '' COLLATE utf8_general_ci as shelving,
            modificationDate as created,
            v.visible - p.quantity as visible,
            IFNULL(cpd.id,0) as `order`,
            g.`grouping`
		FROM vn.ticketCollection tc
			JOIN vn.sale s ON s.ticketFk = tc.ticketFk
            JOIN vn.itemPlacement ip ON ip.itemFk = s.itemFk AND ip.warehouseFk = vWarehouseFk
            LEFT JOIN vn.coolerPathDetail cpd ON cpd.hallway = LEFT(ip.`code`,3)
            JOIN tmp.parked p ON p.itemFk = s.itemFk
            JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vCalcFk
            LEFT JOIN tmp.grouping2 g ON g.itemFk = s.itemFk
		WHERE tc.collectionFk = vCollectionFk
			-- HAVING visible > 0
            ;
        
	DROP TEMPORARY TABLE
		tmp.parked,
        tmp.`grouping`,
        tmp.grouping2;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `collectionSale_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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `collectionSale_get`(vCollectionFk INT)
BEGIN

	SELECT 	ticketFk,
			saleFk,
			itemFk,
            quantity,
            longName,
            size,
            reserved,
            max(isPreviousPrepared) as isPreviousPrepared,
            max(isPrepared) as isPrepared,
            max(isControlled) as isControlled
		FROM (
			SELECT 	s.ticketFk,
					s.id as saleFk,
					s.itemFk,
					s.quantity,
					i.longName,
                    i.size,
					s.reserved,
                    IF(st.semaphore <=> 1, TRUE, FALSE) as isPreviousPrepared,
                    IF(st.semaphore <=> 2, TRUE, FALSE) as isPrepared,
                    IF(st.semaphore <=> 3, TRUE, FALSE) as isControlled
				FROM vn.sale s
					JOIN vn.item i ON i.id = s.itemFk
                    LEFT JOIN vn.saleTracking str ON str.saleFk = s.id AND str.isChecked = 1
                    LEFT JOIN vn.state st ON st.id = str.stateFk
					JOIN vn.ticketCollection tc ON tc.ticketFk = s.ticketFk
				WHERE tc.collectionFk = vCollectionFk
                
			) sub
		GROUP BY saleFk
        HAVING quantity > 0
        
	UNION ALL
    
	SELECT 	stow.shipFk,
			stow.id as stowawayFk,
            0,
			1,
            CONCAT('POLIZON T',stow.id),
            0 AS size,
            0 AS reserved,
			IF(st.semaphore <=> 1,TRUE, FALSE) as isPreviousPrepared,
			IF(st.semaphore <=> 2,TRUE, FALSE) as isPrepared,
			IF(st.semaphore <=> 3,TRUE, FALSE) as isControlled
		FROM vn.ticketCollection tc
            JOIN vn.stowaway stow ON stow.shipFk = tc.ticketFk
            LEFT JOIN vn.ticketState ts ON ts.ticketFk = stow.id
            LEFT JOIN vn.state st ON st.id = ts.stateFk
            WHERE tc.collectionFk = vCollectionFk;
            
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `collectionStickers_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 `collectionStickers_print`(vCollectionFk INT)
BEGIN

    UPDATE vn.ticket t
		JOIN vn.ticketCollection tc ON tc.ticketFk = t.id
        SET t.notes = CONCAT('COL ',vCollectionFk,'-',tc.`level`)
        WHERE tc.collectionFk = vCollectionFk;
    
    INSERT INTO vn.printServerQueue(reportFk, param1, workerFk)
		SELECT 23, tc.ticketFk, getUser()
			FROM vn.ticketCollection tc
			WHERE tc.collectionFk = vCollectionFk;

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

	SELECT 	tc.ticketFk, 
			tc.level,
            am.name as agencyName
		FROM vn.ticketCollection tc
			 JOIN vn.ticket t ON t.id = tc.ticketFk
			LEFT JOIN vn.zone z ON z.id = t.zoneFk 
            LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
		WHERE tc.collectionFk = vCollectionFk;
        
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `collection_new` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `collection_new`(vSectorFk INT)
proc:BEGIN

	DECLARE vIsPreviousPrepared BOOLEAN;
    DECLARE vCollectionFk INT;
    DECLARE vWarehouseFk INT;
    DECLARE vTicketLiters INT;
    DECLARE vTicketLines INT;
    DECLARE vTicketFk INT;
    DECLARE vIsTicketCollected BOOLEAN;
    DECLARE vMaxTickets INT;
    DECLARE vStateFk INT;
	DECLARE vVolumetryLiters INT;
    DECLARE vVolumetryLines INT;
    DECLARE vVolumetryFk INT;
    DECLARE vVolumetryLevel INT;
    DECLARE vVolumetryLitersMax INT;
    DECLARE vVolumetryLinesMax INT;
    DECLARE vDone BOOLEAN DEFAULT FALSE;
    DECLARE vWorkerCode VARCHAR(3);
    
    DECLARE cVolumetry CURSOR FOR
		SELECT level, liters, `lines`
			FROM vn.collectionVolumetry
            ORDER BY `level`;
    
    DECLARE cTicket CURSOR FOR
		SELECT pb.Id_Ticket ticketFk,
			   pb.lines,
			   pb.m3 * 1000 liters
			FROM tmp.production_buffer pb
				JOIN vn.state s ON s.id = pb.state
                LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = pb.Id_Ticket
			WHERE pb.problems = 0
				AND tc.ticketFk IS NULL
				AND (s.isPreparable OR (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode))
			ORDER BY (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode) DESC, pb.Hora, pb.Minuto, m3 DESC, pb.lines DESC
			LIMIT vMaxTickets;
    
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
    
    SELECT isPreviousPrepared, warehouseFk
		INTO vIsPreviousPrepared, vWarehouseFk
		FROM vn.sector
        WHERE id = vSectorFk;
        
	SELECT w.code 
		INTO vWorkerCode
		FROM vn.worker w
        WHERE w.id = account.myUserGetId();
        
	IF vIsPreviousPrepared THEN
    
		SELECT id INTO vStateFk
			FROM vn.state
            WHERE `code` = 'PREVIOUS_PREPARATION';
    ELSE
    
		SELECT id INTO vStateFk
			FROM vn.state
            WHERE `code` = 'ON_PREPARATION';
            
    END IF;
        
	SELECT COUNT(*), sum(liters), sum(`lines`)
		INTO vMaxTickets, vVolumetryLitersMax, vVolumetryLinesMax
		FROM vn.collectionVolumetry;
	
    CALL vn2008.production_control_source(vWarehouseFk, 0);
    
    -- Empieza el bucle
    OPEN cVolumetry;
    OPEN cTicket;
    /*
    DROP TEMPORARY TABLE IF EXISTS tmp.kk;
    CREATE TEMPORARY TABLE tmp.kk
		SELECT pb.Id_Ticket ticketFk,pb.Hora, pb.Minuto,
			   pb.lines,
			   pb.m3 * 1000 liters
			FROM tmp.production_buffer pb
				JOIN vn.state s ON s.id = pb.state
                LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = pb.Id_Ticket
			WHERE pb.problems = 0
				AND tc.ticketFk IS NULL
				AND (s.isPreparable OR (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode))
			ORDER BY (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode) DESC, pb.Hora, pb.Minuto, m3 DESC, pb.lines DESC
			LIMIT vMaxTickets;
    */
	FETCH cTicket INTO vTicketFk, vTicketLines, vTicketLiters;
	FETCH cVolumetry INTO vVolumetryLevel, vVolumetryLiters, vVolumetryLines;
 
	IF NOT vDone THEN
    
		INSERT INTO vn.collection
			SET workerFk = account.myUserGetId();
		
		SELECT LAST_INSERT_ID() INTO vCollectionFk;
    
    END IF;
 
	bucle:WHILE NOT vDone DO
    
		IF (vVolumetryLitersMax < vTicketLiters OR vVolumetryLinesMax < vTicketLines) AND vVolumetryLevel > 1 THEN
			
            LEAVE bucle;
            
		END IF;
    
		SELECT COUNT(*) INTO vIsTicketCollected
			FROM vn.ticketCollection
			WHERE ticketFk = vTicketFk
				AND collectionFk = vCollectionFk;
		
		IF vIsTicketCollected THEN
        
			UPDATE vn.ticketCollection
				SET level = CONCAT(level, vVolumetryLevel)
                WHERE ticketFk = vTicketFk
				AND collectionFk = vCollectionFk;
        
        ELSE
        
			INSERT INTO vn.ticketCollection
					SET collectionFk = vCollectionFk,
						ticketFk = vTicketFk,
						level = vVolumetryLevel;
                        
			INSERT INTO vncontrol.inter
					SET state_id = vStateFk,
                    Id_Ticket = vTicketFk,
                    Id_Trabajador = account.myUserGetId();
		
        END IF;

        SET vVolumetryLitersMax = GREATEST(0,vVolumetryLitersMax - vVolumetryLiters);
        SET vVolumetryLinesMax = GREATEST(0,vVolumetryLinesMax - vVolumetryLines);
        SET vTicketLiters = GREATEST(0,vTicketLiters - vVolumetryLiters);
        SET vTicketLines = GREATEST(0,vTicketLines - vVolumetryLines);
        
		IF vVolumetryLitersMax = 0 OR vVolumetryLinesMax = 0 THEN
                
			LEAVE bucle;
            
        END IF;
        
        IF vTicketLiters > 0 OR vTicketLines > 0 THEN
        
			FETCH cVolumetry INTO vVolumetryLevel, vVolumetryLiters, vVolumetryLines;
            
        ELSE
        
			FETCH cTicket INTO vTicketFk, vTicketLines, vTicketLiters;
			FETCH cVolumetry INTO vVolumetryLevel, vVolumetryLiters, vVolumetryLines;
            
        END IF;
	
	END WHILE;
	
    
    UPDATE vn.collection c
		JOIN vn.state st ON st.code = 'ON_PREPARATION'
        SET c.stateFk = st.id
        WHERE c.id = vCollectionFk;
        
    SELECT vCollectionFk;    
    
    CLOSE cVolumetry;
    CLOSE cTicket;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 '2019-10-30 23:59';
DECLARE vWarehouse INT DEFAULT 1;
DECLARE vPalletVolume INT DEFAULT 2200000;

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) / vPalletVolume  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) / vPalletVolume  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 / vPalletVolume ,
			@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(ish.visible ) * r.cm3 / vPalletVolume  as pal
        FROM vn.itemShelving ish 
			JOIN bi.rotacion r ON r.Id_Article = ish.itemFk AND r.warehouse_id = 1
			LEFT JOIN vn.shelving sh ON sh.code = ish.shelvingFk
            LEFT JOIN vn.parking p ON p.id = sh.parkingFk
			WHERE (sh.code = 'FUE' OR p.code = 'FUE-PI')
        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 `crypt` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `crypt`(vText VARCHAR(255), vKey VARCHAR(255), OUT vResult VARCHAR(255) )
BEGIN

	DECLARE vEncryptedText VARCHAR(255) DEFAULT '';
    
	DECLARE vKeyLength INT;
    DECLARE vKeyPosition INT DEFAULT 1;
    DECLARE vKeyChar VARCHAR(1);
    
    DECLARE vTextLength INT;
    DECLARE vTextPosition INT DEFAULT 1;
    DECLARE vTextChar VARCHAR(1);
    
    DECLARE vEncryptedChar VARCHAR(1);
    DECLARE vEncryptedCharPosition INT;
    
    DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz';
    DECLARE vChainTextPosition INT;
    DECLARE vChainKeyPosition INT;
    DECLARE vChainLength INT;
    
    DECLARE vInvalidadChars VARCHAR(255) DEFAULT '';
    
    SET vTextLength = LENGTH(vText);	
    SET vKeyLength = LENGTH(vKey);
    SET vChainLength = LENGTH(vChain);
	
	WHILE vTextPosition <= vTextLength DO
    
		SET vTextChar = MID(vText,vTextPosition,1);
        SET vKeyChar =  MID(vKey,vKeyPosition,1);
        
        SET vChainTextPosition = LOCATE(vTextChar, vChain);
        SET vInvalidadChars = IF(vChainTextPosition, vInvalidadChars, CONCAT(vInvalidadChars,vTextChar));
        SET vChainKeyPosition = LOCATE(vKeyChar, vChain);
        SET vEncryptedCharPosition = vChainTextPosition + vChainKeyPosition;
        
        IF vEncryptedCharPosition > vChainLength THEN
        
			SET vEncryptedCharPosition = vEncryptedCharPosition - vChainLength;
            
		END IF;
        
        SET vEncryptedChar = MID(vChain, vEncryptedCharPosition,1);
        
        SET vEncryptedText = CONCAT(vEncryptedText, vEncryptedChar);
        
		SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1);
		SET vTextPosition = vTextPosition + 1;
    
    END WHILE;

	SET vResult = IF(LENGTH(vInvalidadChars), CONCAT('Caracteres no válidos: ',vInvalidadChars),vEncryptedText);

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cryptOff` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `cryptOff`(vText VARCHAR(255), vKey VARCHAR(255), OUT vResult VARCHAR(255))
BEGIN

	DECLARE vUncryptedText VARCHAR(255) DEFAULT '';
    
	DECLARE vKeyLength INT;
    DECLARE vKeyPosition INT DEFAULT 1;
    DECLARE vKeyChar VARCHAR(1);
    
    DECLARE vTextLength INT;
    DECLARE vTextPosition INT DEFAULT 1;
    DECLARE vTextChar VARCHAR(1);
    
    DECLARE vUncryptedChar VARCHAR(1);
    DECLARE vUncryptedCharPosition INT;
    
    DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz';
    DECLARE vChainTextPosition INT;
    DECLARE vChainKeyPosition INT;
    DECLARE vChainLength INT;
    
    SET vTextLength = LENGTH(vText);	
    SET vKeyLength = LENGTH(vKey);
    SET vChainLength = LENGTH(vChain);
	
	WHILE vTextPosition <= vTextLength DO
    
		SET vTextChar = MID(vText,vTextPosition,1);
        SET vKeyChar =  MID(vKey,vKeyPosition,1);
        
        SET vChainTextPosition = LOCATE(vTextChar, vChain);
        SET vChainKeyPosition = LOCATE(vKeyChar, vChain);
        SET vUncryptedCharPosition = vChainTextPosition - vChainKeyPosition;
        
        IF vUncryptedCharPosition < 1 THEN
        
			SET vUncryptedCharPosition = vUncryptedCharPosition + vChainLength;
            
		END IF;
        
        SET vUncryptedChar = MID(vChain, vUncryptedCharPosition,1);
        
        SET vUncryptedText = CONCAT(vUncryptedText, vUncryptedChar);
        
		SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1);
		SET vTextPosition = vTextPosition + 1;
    
    END WHILE;

	SET vResult = vUncryptedText;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 `department_calcTree` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `department_calcTree`()
BEGIN
/**
 * Calculates the #path, #lft, #rgt, #sons and #depth columns of
 * the #department table. To build the tree, it uses the #parentFk
 * column.
 */
	DECLARE vIndex INT DEFAULT 0;
	DECLARE vSons INT;

	DROP TEMPORARY TABLE IF EXISTS tNestedTree;
	CREATE TEMPORARY TABLE tNestedTree
		SELECT id, path, lft, rgt, depth, sons
			FROM department LIMIT 0;

	SET max_sp_recursion_depth = 5;
	CALL department_calcTreeRec(NULL, '/', 0, vIndex, vSons);
	SET max_sp_recursion_depth = 0;

	UPDATE department z
		JOIN tNestedTree t ON t.id = z.id
		SET z.path = t.path,
			z.lft = t.lft,
			z.rgt = t.rgt,
			z.depth = t.depth,
			z.sons = t.sons;

	DROP TEMPORARY TABLE tNestedTree;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `department_calcTreeRec` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `department_calcTreeRec`(
	vSelf INT,
    vPath VARCHAR(255),
    vDepth INT,
    INOUT vIndex INT,
    OUT vSons INT
)
BEGIN
/**
 * Calculates and sets the #path, #lft, #rgt, #sons and #depth
 * columns for all children of the passed node. Once calculated
 * the last node rgt index and the number of sons are returned.
 * To update it's children, this procedure calls itself recursively
 * for each one.
 *
 * @vSelf The node identifier
 * @vPath The initial path
 * @vDepth The initial depth
 * @vIndex The initial lft index
 * @vSons The number of direct sons
 */
    DECLARE vChildFk INT;
    DECLARE vLft INT;
    DECLARE vMySons INT;
	DECLARE vDone BOOL;
	DECLARE vChildren CURSOR FOR
		SELECT id FROM department
			WHERE (vSelf IS NULL AND parentFk IS NULL)
				OR (vSelf IS NOT NULL AND parentFk = vSelf);

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
    
    SET vSons = 0;

	OPEN vChildren;
	myLoop: LOOP
		SET vDone = FALSE;
		FETCH vChildren INTO vChildFk;

		IF vDone THEN
			LEAVE myLoop;
		END IF;
        
        SET vIndex = vIndex + 1;
        SET vLft = vIndex;
        SET vSons = vSons + 1;
    
		CALL department_calcTreeRec(
			vChildFk,
            CONCAT(vPath, vChildFk, '/'),
            vDepth + 1,
            vIndex,
            vMySons
		);

        SET vIndex = vIndex + 1;

		INSERT INTO tNestedTree
			SET id = vChildFk,
				path = vPath,
				lft = vLft,
				rgt = vIndex,
				depth = vDepth,
				sons = vMySons;
	END LOOP;
	CLOSE vChildren;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `department_doCalc` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `department_doCalc`()
proc: BEGIN
/**
 * Recalculates the department tree.
 */
    DECLARE vIsChanged BOOL;

	DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
    BEGIN
		DO RELEASE_LOCK('vn.department_doCalc');
        RESIGNAL;
	END;

	IF !GET_LOCK('vn.department_doCalc', 0) THEN
		LEAVE proc;
	END IF;

	SELECT isChanged INTO vIsChanged
		FROM department_recalc;
        
	IF vIsChanged THEN
		UPDATE department_recalc SET isChanged = FALSE;
        CALL vn.department_calcTree;
	END IF;

	DO RELEASE_LOCK('vn.department_doCalc');
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `department_getLeaves` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `department_getLeaves`(
    vParentFk INT,
    vSearch VARCHAR(255)
)
BEGIN
	DECLARE vIsNumber BOOL;
	DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != '';

	DROP TEMPORARY TABLE IF EXISTS tNodes;
	CREATE TEMPORARY TABLE tNodes
		(UNIQUE (id))
		ENGINE = MEMORY
		SELECT id FROM department LIMIT 0;

	IF vIsSearch THEN
		SET vIsNumber = vSearch REGEXP '^[0-9]+$';

		INSERT INTO tNodes
			SELECT id FROM department
				WHERE (vIsNumber AND `name` = vSearch)
					OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%'))
				LIMIT 1000;
	END IF;

	IF vParentFk IS NULL THEN
		DROP TEMPORARY TABLE IF EXISTS tChilds;
		CREATE TEMPORARY TABLE tChilds
			ENGINE = MEMORY
			SELECT id FROM tNodes;

		DROP TEMPORARY TABLE IF EXISTS tParents;
		CREATE TEMPORARY TABLE tParents
			ENGINE = MEMORY
			SELECT id FROM department LIMIT 0;

		myLoop: LOOP
			DELETE FROM tParents;
			INSERT INTO tParents
				SELECT parentFk id
					FROM department g
						JOIN tChilds c ON c.id = g.id
					WHERE g.parentFk IS NOT NULL;
			
			INSERT IGNORE INTO tNodes
				SELECT id FROM tParents;
			
			IF ROW_COUNT() = 0 THEN
				LEAVE myLoop;
			END IF;
			
			DELETE FROM tChilds;
			INSERT INTO tChilds
				SELECT id FROM tParents;
		END LOOP;
		
		DROP TEMPORARY TABLE
			tChilds,
			tParents;
	END IF;

	IF !vIsSearch THEN
		INSERT IGNORE INTO tNodes
			SELECT id FROM department
				WHERE parentFk <=> vParentFk;
	END IF;

	SELECT d.id,
			d.`name`,
			d.parentFk,
			d.sons
		FROM department d
			JOIN tNodes n ON n.id = d.id
		ORDER BY depth, `name`;

	DROP TEMPORARY TABLE tNodes;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 vn.ledgerConfig lc ON lc.lastBookEntry = x.ASIEN
                SET x.ASIEN = vASIEN;
        
        ELSE
        
			SELECT lastBookEntry INTO vASIEN FROM vn.ledgerConfig;
            
		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 `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 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 ASIEN, IFNULL(bookEntried, CURDATE()) INTO vBookNumber, vBookDated
		FROM dua 
		WHERE id = vDuaFk;
        
    IF vBookNumber IS NULL OR NOT vBookNumber THEN
		CALL ledger_next(vBookNumber);
    END IF;
    
	-- Apunte de la aduana

	INSERT INTO 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 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,
			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;

	SELECT SUM(EURODEBE) -SUM(EUROHABER), MAX(id) INTO vDiff, vApunte
		FROM XDiario
		WHERE ASIEN = vBookNumber;
     
	UPDATE XDiario
		SET BASEEURO = 100 * (EURODEBE - vDiff) / IVA,
			EURODEBE = EURODEBE - vDiff			
		WHERE id = vApunte;
    
    UPDATE 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 `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  = 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 `duaTaxBooking__`(vDuaFk INT)
BEGIN
    -- BERNAT: WORKING IN THIS FILE
	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,
			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;

	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 `energyMeter_record` */;
/*!50003 SET @saved_cs_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 `energyMeter_record`(vInput INT, vActiveTime INT)
BEGIN
	DECLARE vConsumption INT;
    
    SELECT consumption INTO vConsumption
		FROM energyInput
		WHERE input = vInput;

	INSERT INTO vn.energyMeter 
		SET 
		  `input` = vInput, 
		  `period` = DATE_FORMAT(NOW(), '%Y-%m-%d %H:00:00'), 
		  `activeTime` = vActiveTime,
          `consumption` = IFNULL((vConsumption / 3600) * vActiveTime, 0)
		ON DUPLICATE KEY UPDATE 
		  `activeTime` = `activeTime` + vActiveTime,
          `consumption` = `consumption` + VALUES(`consumption`);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 `entryDelivered` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `entryDelivered`(vDated DATE, vEntryFk INT)
BEGIN

	DECLARE vTravelFk INT;
    
    SELECT travelFk INTO vTravelFk
		FROM vn.entry 
		WHERE id = vEntryFk;
    
    IF (SELECT COUNT(*) FROM vn.entry WHERE travelFk = vTravelFk) = 1 THEN
    
		UPDATE vn.travel SET shipped = LEAST(shipped, vDated), landed = vDated
			WHERE id = vTravelFk;
    
    ELSE
    
		INSERT INTO vn.travel(shipped, landed, warehouseInFk, warehouseOutFk, agencyFk, ref, isDelivered, isReceived)
			SELECT LEAST(shipped, vDated), vDated, warehouseInFk, warehouseOutFk, agencyFk, CONCAT(account.userGetName(),' ', vEntryFk), TRUE, TRUE
				FROM vn.travel WHERE id = vTravelFk;
                
		SELECT LAST_INSERT_ID() INTO vTravelFk;
        
        UPDATE vn.entry 
			SET travelFk = vTravelFk 
			WHERE id = vEntryFk;
    
    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 `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 `entrySplit_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 `entrySplit_move`()
BEGIN

	/* 	CREATED PAK 08/09/2019
    *	PENDING REVIEW
    *
    *
    */
    
	DROP TEMPORARY TABLE IF EXISTS itemList;
    
    CREATE TEMPORARY TABLE itemList
		SELECT DISTINCT b.itemFk, es.delayedFk, es.receivedFk
			FROM vn.buy b
				JOIN vn.entrySplit es ON es.delayedFk = b.entryFk
				JOIN vn.itemPlacement ip ON ip.itemFk = b.itemFk
            WHERE ip.modificationDate > CURDATE();
            
	INSERT INTO itemList
		SELECT DISTINCT ish.itemFk, es.delayedFk, es.receivedFk
			FROM vn.buy b
				JOIN vn.entrySplit es ON es.delayedFk = b.entryFk
				JOIN vn.itemShelving ish ON ish.itemFk = b.itemFk
			WHERE ish.created > CURDATE();
            
            
	UPDATE vn.buy b
		JOIN vn.itemList il ON il.delayedFk = b.entryFk AND b.itemFk = il.itemFk
        SET b.entryFk = il.receivedFk;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_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 netCost DECIMAL(10,2), IN `vInOutDate` DATE)
BEGIN

    DECLARE vTravel INT;
    DECLARE vEntry INT;
    DECLARE vBucket VARCHAR(10);
    DECLARE vAgencyDirectFromProvider INT DEFAULT 15;
    DECLARE vSupplierFk INT DEFAULT 963;
    

	-- 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 AND e.supplierFk = vSupplierFk
	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 (vSupplierFk, vTravel); -- proveedor 'CONFECCION ARTIFICIAL'
		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`, stickers, buyingValue, price2, price3) 
		SELECT itemFk,
			quantity,
			vEntry,
			vBucket,
			1 packing,
			1 `grouping`,
            quantity,
			netCost,
			s.price,
			s.price
		FROM sale s
		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 `entry_getRate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `entry_getRate`(vEntry INT)
BEGIN
	DECLARE vLanded DATE;
	DECLARE vWarehouseFk  INT;

	-- Obtiene fecha de llegada y almacén entrante

	SELECT landed, warehouseInFk INTO vLanded, vWarehouseFk 
		FROM vn.travel t
			JOIN vn.entry e ON t.id = e.travelFk
		WHERE e.id = vEntry;

	-- Prepara una tabla con las tarifas aplicables en funcion de la fecha y el almacén

	DROP TEMPORARY TABLE IF EXISTS tmp.rate;
	CREATE TEMPORARY TABLE tmp.rate
		ENGINE = MEMORY
		SELECT * FROM
		(
			SELECT * FROM
				(    
					SELECT rate0, rate1, rate2, rate3
					FROM vn.rate
					WHERE dated <= vLanded
					AND warehouseFk = vWarehouseFk
					ORDER BY dated DESC
							
				) sub
			UNION ALL
			SELECT rate0, rate1, rate2, rate3
			FROM rateConfig
		) sub2
		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 `expeditionGetFromRoute` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `expeditionGetFromRoute`(
    vExpeditionFk INT)
BEGIN
/**
 * Get all expeditions from route
 */
 DECLARE  vRouteFk INT DEFAULT 0;
 
 SELECT t.routeFk INTO vRouteFk
	FROM vn.expedition exp 
    INNER JOIN ticket t on t.id = exp.ticketFk
    WHERE exp.id = vExpeditionFk;
 
SELECT exp.id, exp.ticketFk, exp.checked, t.routeFk,t.packages AS bultos , ts.alertLevel, a.street, a.city,a.postalCode,a.id AS addressFk,w.name AS warehouse
	FROM vn.expedition exp
	INNER JOIN ticket t ON t.id = exp.ticketFk
    INNER JOIN vn.ticketState ts ON ts.ticketFk = exp.ticketFk
    LEFT JOIN vn.address a ON t.addressFk = a.id
    LEFT JOIN vn.warehouse w ON t.warehouseFk = w.id
	WHERE t.routeFk = vRouteFk AND exp.isBox > 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 `expeditionUpdateChecked` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `expeditionUpdateChecked`(
    vExpeditionFk INT, vChecked INT)
BEGIN
/**
 * Get all expeditions from route
 */
 
   UPDATE vn.expedition exp
   SET exp.checked = vChecked
   WHERE exp.id = vExpeditionFk;
   
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = 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 `getItemUbication`(vItemFk INT)
BEGIN
	SELECT vn.barcodeToItem(vItemFk) INTO vItemFk;

	SELECT 	pk.code as Parking,
			sh.code as Matricula,
            ish.visible as visible,
            ish.available as Disponible,
            ish.level as level,
            ish.created as created,
            ish.itemFk as itemFk
		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  = 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 `getItemVisibleAvailable__`(
	vItem INT,
    vDate DATE,
    vWarehouse TINYINT,
    vRefresh BOOL)
BEGIN
	-- DEPRECADO - UTILIZAR vn.item_getVisibleAvailable() - JSB - 2019-11-20
	CALL item_getVisibleAvailable(vItem, vDate, vWarehouse, vRefresh);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 `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) * IF(i.density, i.density, it.density) / 1000000  as neto
			FROM vn.entry e 
				JOIN vn.travel tr ON tr.id = e.travelFk
				JOIN vn.buy b ON b.entryFk = e.id
				JOIN vn.item i ON i.id = b.itemFk
                join vn.itemType it ON it.id = i.typeFk
				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  = 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 `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 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 travel tr
            JOIN entry e ON e.travelFk = tr.id
            JOIN buy b ON b.entryFk = e.id
			WHERE warehouseOutFk = 13
				AND landed < vDate
                AND e.supplierFk = 4
				AND warehouseInFk = vWh
                AND NOT isRaid;
        
        -- Generamos travel, si no existe.
        SET vTravelFK = 0;
        
        SELECT id INTO vTravelFk
			FROM travel
            WHERE warehouseOutFk = 13
				AND warehouseInFk = vWh
                AND landed = vDate
                AND agencyFk = 53
                AND ref = 'inventario'
			LIMIT 1;
        
        IF NOT vTravelFK THEN
        
			INSERT INTO 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 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 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 buy b
                JOIN entry e ON e.id = b.entryFk
                JOIN travel tr ON tr.id = e.travelFk
                WHERE tr.warehouseInFk = vWh
					AND tr.landed BETWEEN vDateLastInventory 
                    AND vDateYesterday
                    AND NOT isRaid
				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 buy b
						JOIN entry e ON e.id = b.entryFk
						JOIN travel tr ON tr.id = e.travelFk
						WHERE tr.warehouseOutFk = vWh
							AND tr.shipped BETWEEN vDateLastInventory 
                            AND vDateYesterday
							AND NOT isRaid
						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 sale s
						JOIN 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 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 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 config SET inventoried = 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 `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  = 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 `inventoryMake__`(vDate DATE, vWh INT)
proc: BEGIN
/**
 * bernat WORKING IN THIS FILE
 * 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
                AND NOT isRaid;
        
        -- 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
                    AND NOT isRaid
				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
							AND NOT isRaid
						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 `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  = 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 `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;
              
	INSERT INTO invoiceOutExpence(invoiceOutFk, expenceFk, amount)
		SELECT vInvoice,
			   tst.expenceFk,
			   SUM(ROUND(ts.quantity * ts.price ,2)) amount
			FROM ticketToInvoice t
				JOIN ticketService ts ON ts.ticketFk = t.id
                JOIN ticketServiceType tst ON tst.id = ts.ticketServiceTypeFk
            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 `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  = 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 `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;
    
    CALL vn.ledger_next(vBookNumber);
   
	-- 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,
			ROUND(tc.rate/100 * SUM(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;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = 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 `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 `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), vTaxArea VARCHAR(25))
BEGIN

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

	DECLARE vInvoiceFk INT;
    DECLARE vCountry INT;
    DECLARE vTaxArea VARCHAR(15);
    DECLARE vSpainCountryCode INT DEFAULT 1;
    
	SELECT id INTO vInvoiceFk
		FROM invoiceOut 
        WHERE ref =  vInvoiceRef;
        
	UPDATE invoiceOut 
		SET hasPdf = 0
        WHERE id = vInvoiceFk;
        
	SELECT s.countryFk INTO vCountry
		FROM supplier s
			JOIN invoiceOut io ON io.companyFk = s.id
		WHERE io.id = vInvoiceFk;

	DROP TEMPORARY TABLE IF EXISTS ticketToInvoice;

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

	CALL invoiceExpenceMake(vInvoiceFk);
    
	CALL invoiceTaxMake(vInvoiceFk,vTaxArea);
    
    UPDATE invoiceOut io
		JOIN (
			SELECT SUM(amount) AS total
				FROM invoiceOutExpence 
                WHERE invoiceOutFk = vInvoiceFk
			) base
		JOIN (
			SELECT SUM(vat) AS total
				FROM invoiceOutTax 
                WHERE invoiceOutFk = vInvoiceFk
			) vat
	SET io.amount = base.total + vat.total
    WHERE io.id = vInvoiceFk;
   
	CALL vn.invoiceOutBooking(vInvoiceFk);
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = 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 `invoiceOutBooking`(IN vInvoice INT)
BEGIN
/* Asienta la factura emitida
*
* param vInvoice factura_id
*/
	DECLARE vBookNumber INT;
    DECLARE vExpenceConcept VARCHAR(50);
    DECLARE vIsUeeMember BOOL DEFAULT TRUE;
    DECLARE vSpainCountryFk INT;
    DECLARE vOldBookNumber INT;

	SELECT id INTO vSpainCountryFk FROM country WHERE code = 'ES';

    SELECT ASIEN
			INTO vOldBookNumber
		FROM XDiario x
			JOIN 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 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 = vSpainCountryFk, vSpainCountryFk, IF(ct.isUeeMember = vIsUeeMember,2,4)) AS TERIDNIF,
				CONCAT(IF(ct.isUeeMember = vIsUeeMember AND ct.politicalCountryFk <> vSpainCountryFk,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;

	CALL vn.ledger_next(vBookNumber);
    
	-- Linea del cliente
	INSERT INTO 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 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 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 `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  = 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 `invoiceOutBooking__`(IN vInvoice INT)
BEGIN
-- bernat: working in this file
/* 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 `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  = 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 `invoiceOutBooking___`(IN vInvoice INT)
BEGIN
/* Asienta la factura emitida
* ULTIMA VERSION
* param vInvoice factura_id
*/
	DECLARE vBookNumber INT;
    DECLARE vExpenceConcept VARCHAR(50);
    DECLARE vIsUeeMember BOOL DEFAULT TRUE;
    DECLARE vSpainCountryFk INT;
    DECLARE vOldBookNumber INT;

	SELECT id INTO vSpainCountryFk FROM country WHERE code = 'ES';

    SELECT ASIEN
			INTO vOldBookNumber
		FROM XDiario x
			JOIN 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 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 = vSpainCountryFk, vSpainCountryFk, IF(ct.isUeeMember = vIsUeeMember,2,4)) AS TERIDNIF,
				CONCAT(IF(ct.isUeeMember = vIsUeeMember,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;

	CALL vn.ledger_next(vBookNumber);
    
	-- Linea del cliente
	INSERT INTO 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 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 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 `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 `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 `invoiceOut_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 `invoiceOut_new`(
	vSerial VARCHAR(255),
	vInvoiceDate DATETIME,
    vTaxArea VARCHAR(25),
	OUT vNewInvoiceId INT)
BEGIN

/* Creación de facturas emitidas. 
* REQUIERE previamente tabla ticketToInvoice.
*
* @param vSerial, vInvoiceDate,vTaxArea
*
* @return vNewInvoiceId
*/
	
    DECLARE vSpainCountryCode INT DEFAULT 1;
	DECLARE vIsAnySaleToInvoice BOOL;
	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,vTaxArea);
		
		UPDATE invoiceOut io
				JOIN (
					SELECT SUM(amount) AS total
						FROM invoiceOutExpence 
						WHERE invoiceOutFk = vNewInvoiceId
					) base
				JOIN (
					SELECT SUM(vat) AS total
						FROM invoiceOutTax 
						WHERE invoiceOutFk = vNewInvoiceId
					) vat
			SET io.amount = base.total + vat.total
			WHERE io.id = vNewInvoiceId;
		
	END IF;
    
	DROP TEMPORARY TABLE `ticketToInvoice`;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceOut_newFromClient` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOut_newFromClient`(vClientFk INT, vSerial CHAR(1), vShipped DATE, vCompanyFk INT, vTaxArea VARCHAR(25), OUT vInvoiceId INT)
BEGIN
/**
 * Factura los tickets de un cliente
 * @param vTicketFk Id del ticket
 * @param vSerial Serie de factura
 * @return Id factura
 */
	CALL invoiceFromClient(vShipped, vClientFk, vCompanyFk);
    CALL invoiceOut_new(vSerial, CURDATE(), vTaxArea, 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 `invoiceOut_newFromTicket` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOut_newFromTicket`(vTicketFk INT, vSerial CHAR(1), vTaxArea VARCHAR(25), OUT vInvoiceId INT)
BEGIN
/**
 * Factura un ticket
 * @param vTicketFk Id del ticket
 * @param vSerial Serie de factura
 * @param vTaxArea Area de la factura en caso de querer forzarlo, 
 *     en la mayoria de los casos poner NULL
 * @return vInvoiceId
 */
	DECLARE EXIT HANDLER FOR SQLEXCEPTION 
		BEGIN 
			ROLLBACK;
			RESIGNAL;
		END;
              
	START TRANSACTION;
	CALL invoiceFromTicket(vTicketFk);
    CALL invoiceOut_new(vSerial, CURDATE(), vTaxArea, 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;
    
    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 `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  = 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 `invoiceTaxMake`(vInvoice INT, vTaxArea VARCHAR(25))
BEGIN
/**
 * Factura un conjunto de tickets.
 *
 * @param vInvoice, vTaxAreaFk
 * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
 * @return tmp.ticketAmount
 * @return tmp.ticketTax Impuesto desglosado para cada ticket.
 */
    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 ticket_getTax(vTaxArea);

    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
		ORDER BY priority;
	   
	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 `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  = 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 `invoiceTaxMake__`(vInvoice INT, vTaxArea VARCHAR(25))
BEGIN
/**
 * Factura un conjunto de tickets.
 *
 * @param vInvoice, vTaxAreaFk
 * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
 * @return tmp.ticketAmount
 * @return tmp.ticketTax Impuesto desglosado para cada ticket.
 */
    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 ticket_getTax(vTaxArea);

    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  = 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 `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 AND warehouseFk = vWarehouseFk;
        
	CALL vn2008.item_last_buy_(vWarehouseFk,vItemFk);

	SELECT  i.id,
			i.longName,
            i.tag5,
			i.value5,
            i.tag6,
            i.value6,
            i.tag7,
            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 vn2008.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  = 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 `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  inventoried INTO vDateInventory FROM config;
    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 buy b
                    JOIN entry e ON e.id = b.entryFk
                    JOIN travel tr ON tr.id = e.travelFk
                    JOIN supplier s ON s.id = e.supplierFk
                    JOIN alertLevel al ON al.alertLevel = 
						CASE
							WHEN tr.isReceived != FALSE THEN 3
							WHEN tr.isDelivered THEN 1
                            ELSE 0
						END
                    JOIN state st ON st.code = al.code
                WHERE tr.landed >= vDateInventory
                    AND vWarehouse = tr.warehouseInFk 
                    AND b.itemFk = vItemId
                    AND e.isInventory = 0
					AND e.isRaid = 0
            UNION ALL

            SELECT tr.shipped 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 buy b
                    JOIN entry e ON e.id = b.entryFk
                    JOIN travel tr ON tr.id = e.travelFk
                    JOIN warehouse w ON w.id = tr.warehouseOutFk
                    JOIN supplier s ON s.id = e.supplierFk
                    JOIN alertLevel al ON al.alertLevel = 
						CASE
							WHEN tr.isReceived != FALSE THEN 3
							WHEN tr.isDelivered THEN 1
                            ELSE 0
						END
                    JOIN state st ON st.code = al.code
                WHERE tr.shipped >= vDateInventory
                    AND vWarehouse =tr.warehouseOutFk
                    AND s.id <> 4
                    AND b.itemFk = vItemId
                    AND e.isInventory = 0
                    AND w.isFeedStock = 0
					AND e.isRaid = 0
            UNION ALL

            SELECT 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 sale s
                    JOIN ticket t ON t.id = s.ticketFk
                    LEFT JOIN ticketState ts ON ts.ticket = t.id
                    LEFT JOIN state st ON st.code = ts.code
                    JOIN client c ON c.id = t.clientFk
                    JOIN alertLevel al ON al.alertLevel = 
						CASE
							WHEN t.shipped < vCurdate THEN 3
							WHEN t.shipped > vDayEnd THEN 0
                            ELSE IFNULL(ts.alertLevel, 0)
						END
                    LEFT JOIN 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 `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  = 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 `itemDiary__`(IN vItemId INT, IN vWarehouse INT)
BEGIN
	-- BERNAT WORKING IN THIS FILE
    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
					AND e.isRaid = 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
					AND e.isRaid = 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 vn.item i 
		JOIN (
				SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS reserva
					FROM vn.itemShelving ish
						LEFT JOIN vn.shelving sh ON sh.code = ish.shelvingFk
                        LEFT JOIN vn.parking p ON p.id = sh.parkingFk
					WHERE (ish.shelvingFk = 'FUE' 
						OR p.code = 'FUE-PI')
					GROUP BY ish.itemFk	
			 ) alt ON alt.itemFk = i.id
		LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = 1
		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 isVirtualStock = 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
			 
		;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = 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 `itemGetVisibleAvailable__`(
	vItem INT,
    vDate DATE,
    vWarehouse TINYINT,
    vRefresh BOOL)
BEGIN
	-- DEPRECADO - UTILIZAR vn.item_getVisibleAvailable() - JSB - 2019-11-20
	CALL item_getVisibleAvailable(vItem, vDate, vWarehouse, vRefresh);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = 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 `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, modificationDate = NOW();
	ELSE
		INSERT INTO itemPlacement(itemFk, warehouseFk, code)
			VALUES(vItemFk, vWarehouseFk, vPlacement)
			ON DUPLICATE KEY UPDATE code = vPlacement, modificationDate = 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 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(FLOOR(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`(vSector INT )
BEGIN

	DECLARE vId INT;
    DECLARE vLastParkingFk INT;
    DECLARE vNextParkingFk INT;
        
	SELECT sh.parkingFk INTO vLastParkingFk
		FROM vn.itemShelvingPlacementSupply isps
			JOIN vn.itemShelving ish ON ish.id = isps.itemShelvingFk
            JOIN vn.shelving sh ON sh.code = ish.shelvingFk
        WHERE isps.userFk = getUser()
        ORDER BY isps.created DESC
        LIMIT 1;
    
    SET vNextParkingFk = vn.itemShelvingPlacementSupply_ClosestGet(vLastParkingFk);
    
	SELECT ipsl.id INTO vId
		FROM vn.itemPlacementSupplyList ipsl
			JOIN vn.itemShelvingPlacementSupplyStock ispss ON ispss.itemFk = ipsl.itemFk
		WHERE ipsl.saldo > 0
			AND (ipsl.repoUserFk is NULL OR ipsl.repoUserFk = getUser())
            AND ipsl.sectorFk = vSector
         ORDER BY  ipsl.repoUserFk DESC, ipsl.priority DESC, (ispss.parkingFk = vNextParkingFk) DESC, ispss.parking DESC, ipsl.created
        LIMIT 1;
        
    UPDATE vn.itemPlacementSupply
		SET repoUserFk = getUser()
        WHERE id = vId;
        
    SELECT * FROM vn.itemPlacementSupplyList 
		WHERE id = vId 
		AND sectorFk = vSector;

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

	DECLARE vId INT;
    
    SELECT id INTO vId
		FROM vn.itemPlacementSupplyList ipsl
		WHERE Saldo > 0
			AND (repoUserFk is NULL OR repoUserFk = getUser())
            AND ipsl.sectorFk = vSector
        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 
		AND sectorFk = vSector;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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,vSectorFk INT)
BEGIN

	SELECT shelving, parking, sum(stock) as stockTotal,created
        FROM
			(
                SELECT  `ispss`.`itemShelvingFk` AS `itemShelvingFk`,
								`ispss`.`itemFk` AS `itemFk`,
								`ispss`.`quantity` AS `quantity`,
								`ispss`.`packing` AS `packing`,
								`ispss`.`stock` AS `stock`,
								`ispss`.`longName` AS `longName`,
								`ispss`.`size` AS `size`,
								`ispss`.`subName` AS `subName`,
								`ispss`.`shelving` AS `shelving`,
								`ispss`.`parking` AS `parking`,
								`ispss`.`created` AS `created`,
								 `ispss`.`priority` AS `priority`,
								`ispss`.`parkingFk` AS `parkingFk`,
								`ispss`.`sectorFk` AS `sectorFk`
					FROM vn.itemShelvingPlacementSupplyStock ispss
					LEFT JOIN vn.parking p ON p.code = parking
					WHERE itemFk = vItemFk 
                    -- AND p.sectorFk = vSectorFk 
                    AND stock > 0
					ORDER BY priority DESC
			) sub
		GROUP BY shelving
        ORDER BY parking 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 `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_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemSearchShelving`(`vShelvingFk` VARCHAR(3))
BEGIN
	SELECT p.`column` AS col , p.`row`
		FROM vn.shelving s 
			JOIN parking p ON s.parkingFk = p.id 
		WHERE s.`code` = vShelvingFk 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 `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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_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`,
           p.`code` as `code`,
           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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_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;
    
	
    
    IF (SELECT COUNT(*) FROM vn.itemShelving 
			WHERE shelvingFk COLLATE utf8_unicode_ci  = vShelvingFk 
				AND itemFk  = vItemFk 
				AND packing  = vPacking) = 1 THEN

		UPDATE vn.itemShelving SET quantity = quantity+vQuantity,visible = visible+vQuantity,available = available+vQuantity
        WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; 
        
    ELSE
		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 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 `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;
    
	IF (SELECT COUNT(*) FROM vn.itemShelving 
			WHERE shelvingFk COLLATE utf8_unicode_ci  = vShelvingFk 
				AND itemFk  = vItemFk 
				AND packing  = vPacking) = 1 THEN

		UPDATE vn.itemShelving SET quantity = quantity+vQuantity,visible = visible+vQuantity,available = available+vQuantity, created = vCreated
        WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; 
        
    ELSE
		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 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 `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, vAllTravel BOOLEAN, vFromTimed DATETIME, vToTimed DATETIME)
BEGIN

	DECLARE vTravelFk INT;
    
    SELECT travelFk INTO vTravelFk 
		FROM entry 
        WHERE id = vEntryFk;

	SELECT i.id, i.longName, i.size, i.subName, b.stickers, ish.etiquetas, b.printed
		FROM item i
		JOIN (
					SELECT itemFk, sum(stickers) AS stickers, sum(printedStickers) as printed
						FROM buy b
							JOIN entry e ON e.id = b.entryFk
						WHERE IF(vAllTravel , travelFk = vTravelFk, b.entryFk = vEntryFk)
						GROUP BY itemFk
				  ) b ON b.itemFk = i.id
		LEFT JOIN (
					SELECT itemFk, sum(cast(visible / 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 ish.created BETWEEN vFromTimed AND vToTimed
						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`(vSectorFk INT)
BEGIN

	DECLARE vVisibleCache INT;
    DECLARE vWarehouseFk INT;
    
    SELECT warehouseFk INTO vWarehouseFk
		FROM vn.sector
        WHERE id = vSectorFk;

	CALL cache.visible_refresh (vVisibleCache, FALSE, vWarehouseFk);
		
	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,
        IFNULL(sub3.transit,0)  transit,
        v.visible, s.isPicked, s.reserved, t.shipped, tst.productionOrder, mm.Id_Movimiento
		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 
					AND sectorFk = vSectorFk
                GROUP BY itemFk) sub3 ON sub3.itemFk = i.id
		WHERE v.visible + IFNULL(sub3.transit,0) - GREATEST(0,iss.visible)  < s.quantity 
			AND IFNULL(sub3.transit,0) < s.quantity
			AND s.isPicked = FALSE 
			AND s.reserved = FALSE
			AND t.shipped BETWEEN CURDATE() AND MIDNIGHT(CURDATE()) 
			AND tst.isPreviousPreparable = TRUE
			AND t.warehouseFk = vWarehouseFk
            AND iss.sectorFk = vSectorFk
			AND mm.Id_Movimiento IS NULL
		ORDER 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 `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`(vSectorFk INT)
BEGIN
	DECLARE vWarehouseFk INT;
    DECLARE vCalcVisibleFk INT;
    DECLARE vCalcAvailableFk INT;
    
    SELECT warehouseFk INTO vWarehouseFk
		FROM vn.sector
        WHERE id = vSectorFk;
        
	CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk);
    CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, CURDATE());
    
	DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar;
    CREATE TEMPORARY TABLE tmp.itemShelvingRadar
		(PRIMARY KEY (itemFk))
		ENGINE = MEMORY 
		SELECT iss.itemFk,
				0 `hour`,
				0 `minute`,
				ip.`code` itemPlacementCode,
				i.longName,
				i.size,
				i.subName producer,
                i.upToDown,
				a.available,
				IFNULL(v.visible,0) - IFNULL(iss.visible,0) dayEndVisible,
				IFNULL(v.visible,0) - IFNULL(iss.visible,0) firstNegative,
				IFNULL(v.visible,0) - IFNULL(iss.visible,0) itemPlacementVisible, 
				i.minimum * b.packing itemPlacementSize,
				ips.onTheWay,
				iss.visible itemShelvingStock,
                IFNULL(v.visible,0) visible,
                b.isPickedOff,
                iss.sectorFk
		FROM vn.itemShelvingStock iss
			JOIN vn.item i on i.id = iss.itemFk
			LEFT JOIN vn.itemPlacement ip ON ip.itemFk = iss.itemFk AND ip.warehouseFk = vWarehouseFk
            LEFT JOIN cache.last_buy lb ON lb.item_id = iss.itemFk AND lb.warehouse_id = vWarehouseFk
				LEFT JOIN vn.buy b ON b.id = lb.buy_id
			LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk
            LEFT JOIN cache.visible v  ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk
			LEFT JOIN (SELECT itemFk, sum(saldo) as  onTheWay
							FROM vn.itemPlacementSupplyList 
							WHERE saldo > 0 
							GROUP BY itemFk
						) ips ON ips.itemFk = i.id
			WHERE IFNULL(iss.sectorFk,0) IN (0, vSectorFk) 
				AND iss.sectorFk = vSectorFk;            
     
	DROP TEMPORARY TABLE IF EXISTS tmp.itemOutTime;
    CREATE TEMPORARY TABLE tmp.itemOutTime
		 SELECT *,SUM(amount) quantity
			FROM 
				 (SELECT 	item_id itemFk,
							amount, 
                            IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours, 
                            IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) as minutes
						FROM vn2008.item_out io
							JOIN tmp.itemShelvingRadar isr ON isr.itemFk = io.item_id
							JOIN vn.ticket t on t.id= io.ticketFk
                            JOIN vn.ticketState ts on ts.ticketFk = io.ticketFk
							JOIN vn.state s ON s.id = ts.stateFk
                            LEFT JOIN vn.zone z ON z.id = t.zoneFk
                            LEFT JOIN (SELECT DISTINCT saleFk 
										FROM vn.saleTracking st 
										WHERE st.created > CURDATE() 
											AND st.isChecked
									)  stPrevious  ON `stPrevious`.`saleFk` = io.saleFk
						WHERE t.warehouseFk = vWarehouseFk
							AND s.isPicked = 0 
							AND NOT io.Reservado 
							AND stPrevious.saleFk IS NULL
							AND io.dat >= CURDATE() 
							AND io.dat < CURDATE()+1
				 ) sub
			GROUP BY itemFk, hours, minutes;
   
	INSERT INTO tmp.itemShelvingRadar (itemFk)
		SELECT itemFk FROM tmp.itemOutTime
		ON DUPLICATE KEY UPDATE dayEndVisible = dayEndVisible + quantity, 
								firstNegative = if (firstNegative < 0, firstNegative, firstNegative + quantity),
                                `hour` = ifnull(if (firstNegative > 0 , `hour`, hours),0),
                                `minute` = ifnull(if (firstNegative > 0, `minute`, minutes),0);

	SELECT * FROM tmp.itemShelvingRadar;

	DROP TEMPORARY TABLE tmp.itemShelvingRadar;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingRadar_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

IF saleFk  <> 0 THEN
	INSERT INTO vn.itemShelvingSale(	itemShelvingFk, 
												saleFk, 
                                                quantity, 
                                                userFk)
		VALUES (	vItemShelvingFk,
					saleFk,
                    vQuantity,
                    getUser());

	
END IF;
	UPDATE vn.itemShelving SET quantity = (quantity - vQuantity), available = (available - vQuantity), visible = (visible - 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 `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 `itemStock` */;
/*!50003 SET @saved_cs_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 `itemStock`(vWarehouseFk SMALLINT, vDated DATETIME, vItemFk INT)
BEGIN
/**
 * Calcula el stock del vWarehouseFk desde FechaInventario hasta vDated
 * @param vWarehouse warehouse id
 * @param vDated max date to filter
 * @param vItemFk item id
 **/
	SET vDated = TIMESTAMP(DATE(vDated), '00:00:00');
    
	DROP TEMPORARY TABLE IF EXISTS tmp.itemList;
	CREATE TEMPORARY TABLE tmp.itemList
		(UNIQUE INDEX i USING HASH (itemFk))
		ENGINE = MEMORY
			SELECT itemFk, SUM(quantity) stock, SUM(quantity) visible, SUM(quantity) available FROM (
				SELECT itemFk, quantity 
                FROM itemTicketOut
					WHERE shipped >= CURDATE() AND shipped < vDated
						AND warehouseFk = vWarehouseFk
                        AND (vItemFk IS NULL OR itemFk = vItemFk)
				UNION ALL
				SELECT itemFk, quantity 
                FROM itemEntryIn
					WHERE landed >= CURDATE() AND landed < vDated
						AND warehouseInFk = vWarehouseFk
                        AND (vItemFk IS NULL OR itemFk = vItemFk)
				UNION ALL
				SELECT itemFk, quantity 
                FROM itemEntryOut
					WHERE shipped >= CURDATE() AND shipped < vDated
						AND warehouseOutFk = vWarehouseFk
                        AND (vItemFk IS NULL OR itemFk = vItemFk)
			) t
			GROUP BY itemFk HAVING stock != 0;

    CALL `cache`.stock_refresh (FALSE);

	INSERT INTO tmp.itemList (itemFk,stock,visible,available)
	SELECT item_id,amount,amount,amount 
		FROM `cache`.stock
		WHERE warehouse_id = vWarehouseFk AND (vItemFk IS NULL OR vItemFk = 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 `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 vAgencyModeOthersFk INT DEFAULT 2;
    DECLARE vVisible INT DEFAULT 0;
    DECLARE vCalc INT;
    DECLARE vCurrentTime VARCHAR(5);
    
    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.ticketCreateWithoutZone(vClientFk, CURDATE(), vWarehouseFk, vCompanyVnlFk, NULL, vAgencyModeOthersFk, NULL, CURDATE(), account.userGetId(),vTicketFk);
        
    END IF;
    
    INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount)
		SELECT vTicketFk, vItemFk,  CONCAT(longName," ",vn.getWorkerCode(), " ",LEFT(CAST(NOW() AS TIME),5)), 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 `itemStockVisible_verify` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `itemStockVisible_verify`(vItemFk INT, vQuantity INT)
BEGIN

	INSERT INTO vn.itemShelving(itemFk, 
								shelvingFk, 
                                quantity, 
                                visible, 
                                available, 
                                packing) 
		VALUES(	vItemFk, 
				'FAL', 
                -vQuantity, 
                -vQuantity, 
                -vQuantity, 
                -vQuantity);
        
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 `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_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `item_GetVisible`(vWarehouse SMALLINT, vItem INT)
BEGIN
	DECLARE vTomorrow DATETIME DEFAULT TIMESTAMPADD(DAY, 1, CURDATE());
    
	INSERT INTO vn2008.tmp_item (item_id, visible)
		SELECT item_id, SUM(amount) amount
			FROM (
				SELECT i.itemFk AS item_id, quantity AS amount 
					FROM itemTicketOut i
						LEFT JOIN ticketState ts ON ts.ticketFk = i.ticketFk 
							JOIN state s ON s.id = ts.stateFk
						LEFT JOIN (SELECT DISTINCT saleFk 
										FROM saleTracking st 
											JOIN state s ON s.id = st.stateFk
										WHERE st.created > CURDATE() 
											AND (s.isPicked OR st.isChecked)
									)  stPrevious  ON `stPrevious`.`saleFk` = i.saleFk
					WHERE i.warehouseFk = vWarehouse
						AND (vItem IS NULL OR i.itemFk = vItem)
						AND (s.isPicked OR i.reserved OR stPrevious.saleFk )
						AND i.shipped >= CURDATE() AND i.shipped < vTomorrow
				UNION ALL
				SELECT iei.itemFk, quantity 
					FROM itemEntryIn iei
						LEFT JOIN itemPlacement ip ON ip.itemFk = iei.itemFk AND ip.warehouseFk = vWarehouse
					WHERE (iei.isReceived != FALSE /*OR ip.modificationDate > CURDATE()*/)
						AND iei.landed >= CURDATE() AND iei.landed < vTomorrow
						AND iei.warehouseInFk = vWarehouse
						AND (vItem IS NULL OR iei.itemFk = vItem)
						AND iei.isVirtualStock is FALSE
				UNION ALL
				SELECT itemFk, quantity 
					FROM itemEntryOut
					WHERE isDelivered != FALSE
						AND shipped >= CURDATE() AND shipped < vTomorrow
						AND warehouseOutFk = vWarehouse
						AND (vItem IS NULL OR itemFk = vItem)
					) 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_getVisibleAvailable` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_getVisibleAvailable`(
	vItem INT,
    vDate DATE,
    vWarehouse TINYINT,
    vRefresh BOOL)
BEGIN
	DECLARE vVisibleCalc INT;
    DECLARE vAvailableCalc INT;
    DECLARE vVisibleAltillo INT;
    
    CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/ , vWarehouse, vDate);
    CALL cache.visible_refresh(vVisibleCalc, FALSE,vWarehouse);
   
   SELECT visible INTO vVisibleAltillo
		FROM vn.itemShelvingStock 
        WHERE itemFk = vItem
			AND warehouseFk = vWarehouse;
   
    IF vRefresh THEN
    
		DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item;
		CREATE TEMPORARY TABLE vn2008.tmp_item
			(PRIMARY KEY (item_id))
			ENGINE = MEMORY
			SELECT vItem item_id, 0 stock, 0 visible;

		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,
					vi.visible - IFNULL(vVisibleAltillo,0) AS visible,
					av.available
			FROM vn.item i 
				LEFT JOIN vn.itemPlacement ip
					ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse
				LEFT JOIN vn2008.tmp_item v
					ON v.item_id = i.id 
				LEFT JOIN cache.available av
					 ON av.calc_id = vAvailableCalc AND av.item_id = i.id
				LEFT JOIN cache.visible vi
					 ON vi.calc_id = vVisibleCalc AND vi.item_id = i.id
				LEFT JOIN cache.stock st 
					ON st.warehouse_id = vWarehouse AND st.item_id = i.id
			WHERE (vItem IS NULL OR i.id = vItem);
		
    ELSE
    
		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 - IFNULL(vVisibleAltillo,0) AS 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 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 `item_ValuateInventory` */;
/*!50003 SET @saved_cs_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_ValuateInventory`(IN vDated DATE, IN vIsDetailed BOOLEAN)
BEGIN

    DECLARE vInventoried DATE;
    DECLARE vHasNotInventory BOOLEAN DEFAULT 0;
    DECLARE vInventoried2 DATE;
    DECLARE vDateDayEnd DATETIME;
    
    SET vDateDayEnd = util.dayEnd(vDated);
    SELECT landed INTO vInventoried
    FROM travel tr
        JOIN entry E ON E.travelFk = tr.id
    WHERE landed <= vDateDayEnd
        AND E.supplierFk = 4
    ORDER BY landed DESC
    LIMIT 1;

    SET vHasNotInventory = IF (vInventoried is null, TRUE, FALSE);
    
    IF vHasNotInventory THEN

        SELECT landed INTO vInventoried2
        FROM travel tr
            JOIN entry E ON E.travelFk = tr.id
        WHERE landed >= vDated
            AND E.supplierFk = 4
        ORDER BY landed ASC
        LIMIT 1;

        SET vInventoried = TIMESTAMPADD(DAY,1,vDated);
        SET vDateDayEnd = vInventoried2;

    END IF;

    DROP TEMPORARY TABLE IF EXISTS inv;

    CREATE TEMPORARY TABLE inv
        (warehouseFk SMALLINT,
         Id_Article BIGINT,
         cantidad INT,    
         coste DOUBLE DEFAULT 0,
         total DOUBLE DEFAULT 0,
         Almacen VARCHAR(20),
         PRIMARY KEY (Almacen, Id_Article) USING HASH)
     ENGINE = MEMORY;
     
    IF vHasNotInventory = TRUE THEN

        INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen)
            SELECT tr.warehouseInFk, b.itemFk, SUM(b.quantity), w.`name`
            FROM buy b
                JOIN item i ON i.id = b.itemFk
                JOIN entry e ON e.id = b.entryFk
                JOIN travel tr ON tr.id = e.travelFk
                JOIN itemType t ON t.id = i.typeFk
                JOIN warehouse w ON w.id = warehouseInFk
            WHERE landed = vDateDayEnd
                AND e.supplierFk = 4
                AND w.valuatedInventory
                AND t.isInventory
            GROUP BY tr.warehouseInFk, b.itemFk;

    END IF;

    INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen)
        SELECT tr.warehouseInFk, b.itemFk, b.quantity * IF(vHasNotInventory,-1,1), w.`name`
        FROM buy b
        JOIN item i ON i.id = b.itemFk
        JOIN entry e ON e.id = b.entryFk
        JOIN travel tr ON tr.id = e.travelFk
        JOIN itemType t ON t.id = i.typeFk
        JOIN warehouse w ON w.id = tr.warehouseInFk
        WHERE tr.landed BETWEEN vInventoried AND vDateDayEnd
        AND IF(tr.landed = CURDATE(), tr.isReceived, trUE)
        AND NOT e.isRaid
        AND w.valuatedInventory
        AND t.isInventory
        ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + (b.quantity * IF(vHasNotInventory,-1,1));

    INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen)
        SELECT tr.warehouseOutFk, b.itemFk, b.quantity * IF(vHasNotInventory,1,-1), w.`name`
        FROM buy b
        JOIN item i ON i.id = b.itemFk
        JOIN entry e ON e.id = b.entryFk
        JOIN travel tr ON tr.id = e.travelFk
        JOIN itemType t ON t.id = i.typeFk
        JOIN warehouse w ON w.id = tr.warehouseOutFk
        WHERE tr.shipped BETWEEN vInventoried AND vDateDayEnd
        AND NOT e.isRaid
        AND w.valuatedInventory
        AND t.isInventory
        ON DUPLICATE KEY UPDATE  inv.cantidad = inv.cantidad + (b.quantity * IF(vHasNotInventory,1,-1));

    INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen)
        SELECT w.id, s.itemFk, s.quantity  * IF(vHasNotInventory,1,-1), w.`name`
        FROM sale s
        JOIN ticket t ON t.id = s.ticketFk
        JOIN `client` c ON c.id = t.clientFk
        JOIN item i ON i.id = s.itemFk
        JOIN itemType it ON  it.id = i.typeFk
        JOIN warehouse w ON w.id = t.warehouseFk
        WHERE t.shipped BETWEEN vInventoried AND vDateDayEnd
        AND w.valuatedInventory
        AND it.isInventory
        ON DUPLICATE KEY UPDATE  inv.cantidad = inv.cantidad + s.quantity * IF(vHasNotInventory,1,-1);

    IF vDated = CURDATE() THEN -- volver a poner lo que esta aun en las estanterias

        INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen)
            SELECT w.id, s.itemFk, s.quantity  * IF(vHasNotInventory,0,1), w.`name`
            FROM sale s
            JOIN ticket t ON t.id = s.ticketFk
            JOIN `client` c ON c.id = t.clientFk
            JOIN item i ON i.id = s.itemFk
            JOIN itemType it ON  it.id = i.typeFk
            JOIN warehouse w ON w.id = t.warehouseFk
            WHERE t.shipped BETWEEN  vDated AND vDateDayEnd
            AND (s.isPicked <> 0 or t.isLabeled <> 0 )
            AND w.valuatedInventory
            AND it.isInventory
            ON DUPLICATE KEY UPDATE  inv.cantidad = inv.cantidad + s.quantity * IF(vHasNotInventory,0,1);

    END IF;  

    -- Mercancia en transito
    INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen)
        SELECT tr.warehouseInFk, b.itemFk, b.quantity, CONCAT(wOut.`name`,' - ', wIn.`name`)
        FROM buy b
            JOIN item i ON i.id = b.itemFk
            JOIN entry e ON e.id = b.entryFk
			JOIN travel tr ON tr.id = e.travelFk
			JOIN itemType t ON t.id = i.typeFk
            JOIN warehouse wIn ON wIn.id = tr.warehouseInFk
            JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk
        WHERE vDated >= tr.shipped AND vDated < tr.landed
            AND NOT isRaid
            AND wIn.valuatedInventory
            AND t.isInventory
            AND e.isConfirmed
        ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + (b.quantity);
 
    CALL vn.buyUltimate(NULL,vDateDayEnd);

    UPDATE inv i
    JOIN tmp.buyUltimate bu ON i.warehouseFk = bu.warehouseFk AND i.Id_Article = bu.itemFk
    JOIN buy b ON b.id = bu.buyFk
    SET total = i.cantidad * (ifnull(b.buyingValue,0) + IFNULL(b.packageValue,0) + IFNULL(b.freightValue,0) + IFNULL(b.comissionValue,0)),
        coste = ifnull(b.buyingValue,0) + IFNULL(b.packageValue,0) + IFNULL(b.freightValue,0) + IFNULL(b.comissionValue,0)
    WHERE i.cantidad <> 0;

    DELETE FROM inv WHERE Cantidad IS NULL or Cantidad = 0;

    IF vIsDetailed THEN

        SELECT inv.warehouseFk, i.id, i.name, i.size, inv.Cantidad, tp.code,
                tp.categoryFk, inv.coste, cast(inv.total as decimal(10,2)) total,Almacen
            FROM inv
                JOIN warehouse w on w.id = warehouseFk
                JOIN item i ON i.id = inv.Id_Article
                JOIN itemType tp ON tp.id = i.typeFk
            WHERE w.valuatedInventory
            and inv.total > 0
            order by inv.total desc;

    ELSE

		 SELECT i.Almacen, ic.name as Reino, cast(i.total as decimal(10,2)) as Euros, w.code as Comprador,it.id
            FROM inv i
				JOIN warehouse wh on wh.id = warehouseFk
                JOIN item it ON it.id = i.Id_Article
                JOIN itemType itp ON itp.id = it.typeFk
                LEFT JOIN worker w ON w.id = itp.workerFk
                JOIN itemCategory ic ON ic.id = itp.categoryFk
			WHERE wh.valuatedInventory
                AND i.total > 0;

    END IF;
    DROP TEMPORARY TABLE tmp.buyUltimate;
    DROP TEMPORARY TABLE 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 */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ledger_next` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ledger_next`(OUT vNewBookEntry INT)
BEGIN
   
   UPDATE vn.ledgerConfig  SET lastBookEntry = LAST_INSERT_ID(lastBookEntry + 1);
   SET vNewBookEntry = 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 `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 `mail_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 `mail_insert`(
    vSender VARCHAR(50),
    vReplyTo VARCHAR(50),
    vSubject VARCHAR(50),
    vBody VARCHAR(255))
BEGIN
   
   DECLARE vIsRepeated BOOLEAN;
   
   SELECT COUNT(*) INTO vIsRepeated
		FROM vn.mail
		WHERE creationDate >= CURDATE()
			AND sender = vSender
			AND `replyTo` = vReplyTo
			AND `subject` = vSubject;
        
	IF NOT vIsRepeated THEN
   
	   INSERT INTO vn.mail SET
				`sender` = vSender,
				`replyTo` = vReplyTo,
				`subject` = vSubject,
				`body` = vBody;
                
	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 `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`(vWorkerFk 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 = vWorkerFk;
    
	IF NOT vWorkerIsExcluded THEN

		SELECT max(dated) INTO vFromDated 
			FROM clientManaCache;
            
        REPLACE bs.workerMana (workerFk, amount)
			SELECT vWorkerFk, 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 =  vWorkerFk 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 = vWorkerFk 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 = vWorkerFk 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 = vWorkerFk 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();

		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), Id_Ruta = NULL;
        
		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);
		
        DROP TEMPORARY TABLE vn2008.Tickets_to_fusion;
	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 `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), Id_Ruta = NULL;
        
		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);
		
        DROP TEMPORARY TABLE vn2008.Tickets_to_fusion;
	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              = '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(
		'TRUNCATE TABLE ', vDestinationSchema, '.', vDestinationTable));
    CALL util.exec(CONCAT(
		'INSERT INTO ', vDestinationSchema, '.', vDestinationTable,
		'(id, name, lft, rgt, depth, sons)',
			'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;
    DECLARE vZoneFk INT;

	SET vGraceDays = IF(vIsAllInvoiceable,0,30);
	SET vGraceDate = TIMESTAMPADD(DAY, - vGraceDays, vDate);
    
    /* Clientes especiales: 
								3240 MADEFLOR
                                 992 JAVIER FELIU
                                   4 TONI VENDRELL
	*/
                                 
    IF vClient IN (992, 3240, 4) 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;

    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;

	SELECT id INTO vZoneFk FROM vn.zone WHERE agencyModeFk = vAgenciaEmbalajes LIMIT 1;

    IF vIsInvoiceable THEN

        CALL vn.ticketCreateWithoutZone(vClient, vDate, vWarehouse, vCompany, NULL, vAgenciaEmbalajes, NULL, vDate, account.userGetId(), 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;
             
		UPDATE ticket SET zoneFk = vZoneFk WHERE id = 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  = 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 `packingListSwitch`(saleFk INT)
BEGIN

	DECLARE valueFk INT;
    DECLARE encajando INT DEFAULT 9;
    
    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, stateFk) 
		VALUES(saleFk,valueFk,getWorker(),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 `parking_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 `parking_add`(vFromColumn INT, vToColumn INT, vFromRow INT, vToRow INT, vSectorFk INT, vIsLetterMode BOOLEAN)
BEGIN

	DECLARE vColumn INT;
    DECLARE vRow INT;
    DECLARE vLetters VARCHAR(26) DEFAULT 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    DECLARE vMaxId INT;
    DECLARE vCode VARCHAR(8);
    
    SET vColumn = vFromColumn;
    SET vRow = vFromRow;
    SET vCode = CONCAT(LPAD(vColumn,3,'0'),IF(vIsLetterMode, MID(vLetters, vRow, 1), CONCAT('-',LPAD(vRow, 2,'0'))));
     
	SELECT MAX(id) INTO vMaxId
		FROM vn.parking;

	WHILE vColumn <= vToColumn DO
    
		WHILE vRow <= vToRow DO
    
			INSERT IGNORE INTO vn.parking(`column`, `row`, sectorFk, `code`, pickingOrder)
				VALUES (vColumn, vRow, vSectorFk, vCode, vColumn )
                ON DUPLICATE KEY UPDATE `code` = vCode;
			
			SET vRow = vRow + 1;
            SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0')));
            
		END WHILE;
        
        SET vRow = vFromRow;
        SET vColumn = vColumn + 1;
        
		SET vCode = CONCAT(LPAD(vColumn,3,'0'),IF(vIsLetterMode, MID(vLetters, vRow, 1), CONCAT('-',LPAD(vRow, 2,'0'))));
     
    END WHILE;
    
    SELECT * FROM vn.parking WHERE `column` BETWEEN vFromColumn AND vToColumn;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = 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 `payRoll`(IN vFromDated DATE, IN vToDated DATE, IN vFromPaid DATE, IN vToPaid DATE, IN vPartTime BOOL)
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 postgresql.calendar_labour_type cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id
		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
		AND IF(vPartTime,cl.hours_week <= 40,cl.hours_week = 40)
	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`(vSectorFk INT)
BEGIN

	SELECT 0,999999,0 INTO @sameTicket, @ticket, @litrosTicket;
    

	SELECT  @litrosTicket := IF(sub.ticketFk = @ticket, @litrosTicket + Litros, Litros) as LitrosTicket,
			@sameTicket := IF(sub.ticketFk = @ticket, @sameTicket, IF(@sameTicket, 0 , 1)) as sameTicket, 
			sub.*, 
            @ticket := ticketFk
		FROM
			(
				SELECT * FROM
				(
					SELECT isa.*, 
							cast(max(isa.quantity mod isa.packing) as DECIMAL(10,0)) as picos,
							sum(isa.available) as totalAvailable, 
							IF (HOUR(isa.shipped),HOUR(isa.shipped), HOUR(isa.`hour`)) Hora, 
							IF (MINUTE(isa.shipped),MINUTE(isa.shipped), MINUTE(isa.`hour`)) Minuto, 
							i.subName,
							CAST(isa.physicalVolume * 1000 AS DECIMAL(10,0)) as Litros
						FROM vn.itemShelvingAvailable isa
						JOIN vn.item i ON i.id = isa.itemFk
						JOIN vn.sector s ON s.id = isa.sectorFk
						WHERE IF(s.isPreviousPreparedByPacking, (MOD(TRUNCATE(isa.quantity,0), isa.packing)= 0 ), TRUE)
							AND isa.isPreviousPreparable = TRUE
							AND isa.sectorFk = vSectorFk
							AND isa.quantity > 0
                            AND isa.sectorFk = vSectorFk
						GROUP BY saleFk
						HAVING isa.quantity <= totalAvailable
				) sub2
					ORDER BY Hora, Minuto, ticketFk
			) 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 `rangeDateInfo` */;
/*!50003 SET @saved_cs_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 `rangeDateInfo`(vStarted DATE, vEnded DATE)
BEGIN
/**
 * Crea una tabla temporal con las fechas
 * desde una fecha inicial a una final
 * @param vStarted fecha inicial
 * @param vEnded fecha final
 */
    DECLARE vDated DATE DEFAULT vStarted;

    DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate;
    CREATE TEMPORARY TABLE tmp.rangeDate(
		`dated` DATE,
        `period` INT,
        `month` INT,
        `year` INT,
        `day` INT,
        `week` INT,
        `yearMonth` INT
        )
        ENGINE = MEMORY;
        
	WHILE vDated <= vEnded DO
		INSERT INTO tmp.rangeDate
			SET `dated` = vDated,
            `period` = YEAR(vDated) * 100 + WEEK(vDated, 1),
            `month` = MONTH(vDated),
            `year` = YEAR(vDated),
            `day` = DAY(vDated),
            `week` = WEEK(vDated, 1),
            `yearMonth` = YEAR(vDated) * 100 + MONTH(vDated);
            
		SET vDated = DATE_ADD(vDated, 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 `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 vWarehouse TINYINT;
	DECLARE vCompany MEDIUMINT;
	DECLARE vAddress MEDIUMINT;
    DECLARE vRefundAgencyMode INT;
    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 vZoneFk 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 id INTO vRefundAgencyMode
		FROM agencyMode WHERE `name` = 'ABONO';

	SELECT clientFk, warehouseFk, companyFk, addressFk 
			INTO vCustomer, vWarehouse, vCompany, vAddress
		FROM ticket 
        WHERE id = vOriginTicket;
    
    SELECT id INTO vZoneFk 
		FROM zone WHERE agencyModeFk = vRefundAgencyMode
        LIMIT 1;
        
	INSERT INTO vn2008.Tickets (
			Id_Cliente,
			Fecha,
			Id_Consigna,
			Id_Agencia,
			Alias,
			warehouse_id,
			empresa_id,
			landing,
            zoneFk
		)
		SELECT
					vCustomer,
					CURDATE(),
					vAddress,
					vRefundAgencyMode,
					a.nickname,
					vWarehouse,
					vCompany,
					CURDATE(),
                    vZoneFk
			FROM address a
			WHERE a.id = vAddress;

	SET vNewTicket = LAST_INSERT_ID();

	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 `routeSetOk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `routeSetOk`(
    vRouteFk INT)
BEGIN
 
   UPDATE vn.route r
   SET r.isOk = 1
   WHERE r.id = vRouteFk;
   
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 routeFk, SUM(volume) AS m3
				FROM saleVolume
				WHERE routeFk = vRoute
			 ) v ON v.routeFk = 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  = 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 `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 VOLUMETRICAS, 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(r.created),
				MONTH(r.created),
				GREATEST(1,a.warehouseFk),
				r.id,
				r.agencyModeFk,
				r.kmEnd - r.kmStart,
				DAYNAME(r.created),
				r.created,
				SUM(sv.volume / ebv.m3),
				v.numberPlate,
				IF(ISNULL(`r`.`cost`), 'P', 'A'),
                r.cost
			FROM vn.route r
				JOIN vn.ticket t ON t.routeFk = r.id
                LEFT JOIN vn.zone z ON z.id = t.zoneFk
				LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk
                LEFT JOIN vn.agency a ON a.id = am.agencyFk
                LEFT JOIN vn.vehicle v ON v.id = r.vehicleFk
                JOIN vn.saleVolume sv ON sv.ticketFk = t.id
                JOIN vn.expeditionBoxVol ebv ON ebv.boxFk = 71
			WHERE YEAR(r.created) = vYear AND MONTH(r.created) = vMonth
				AND z.isVolumetric
			GROUP BY r.id;

   -- Rellenamos la tabla con los datos de las rutas NO VOLUMETRICAS, 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(r.created),
				MONTH(r.created),
				GREATEST(1,a.warehouseFk),
				r.id,
				r.agencyModeFk,
				r.kmEnd - r.kmStart,
				DAYNAME(r.created),
				r.created,
				SUM(t.packages),
				v.numberPlate,
				IF(ISNULL(`r`.`cost`), 'P', 'A'),
                r.cost
			FROM vn.route r
				JOIN vn.ticket t ON t.routeFk = r.id
                LEFT JOIN vn.zone z ON z.id = t.zoneFk
				LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk
                LEFT JOIN vn.agency a ON a.id = am.agencyFk
                LEFT JOIN vn.vehicle v ON v.id = r.vehicleFk
			WHERE YEAR(r.created) = vYear AND MONTH(r.created) = vMonth
				AND z.isVolumetric = FALSE
			GROUP BY r.id
		ON DUPLICATE KEY UPDATE Bultos = Bultos + VALUES(Bultos);
            
   -- 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.`component` c ON c.id = sc.componentFk
						JOIN vn.componentType ct ON ct.id = c.typeFk
					WHERE ct.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(z.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.zone z ON z.id = t.zoneFk
				WHERE tm.year = vYear 
					AND tm.month = vMonth
                    AND z.isVolumetric = FALSE
				GROUP BY t.routeFk) sub ON r.Id_Ruta = sub.routeFk
		SET r.teorico = sub.BultoTeoricoMedio;

 	-- Coste VOLUMETRICO TEORICO de una caja "virtual" para cada ruta
	UPDATE bi.rutasBoard r
		JOIN (
			SELECT  t.routeFk, 
					SUM(freight) 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.saleFreight sf ON sf.ticketFk = t.id
					JOIN vn.client c ON c.id = sf.clientFk
					JOIN vn.zone z ON z.id = t.zoneFk
				WHERE tm.year = vYear 
					AND tm.month = vMonth
                    AND z.isVolumetric != FALSE
				GROUP BY t.routeFk) sub ON r.Id_Ruta = sub.routeFk
		SET r.teorico = sub.BultoTeoricoMedio / r.Bultos;

   -- 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 vShipped DATE;
	DECLARE vWarehouseFk INT;
	DECLARE vAddressFk INT;
	DECLARE vAgencyModeFk INT;
	DECLARE vNewTicket BIGINT;
	DECLARE vNewSale BIGINT;
	DECLARE vLanded DATE;
	DECLARE vShippedDayEnd DATETIME;
	DECLARE vTicketOriginalFk INT;
	DECLARE hasAlreadyItem BOOLEAN;
	DECLARE vItemFk INT;
    DECLARE vClientTypeFk VARCHAR(20);

	SELECT t.shipped, t.warehouseFk, t.addressFk, agencyModeFk, landed, t.id, s.itemfk, c.typeFk
			INTO vShipped, vWarehouseFk, vAddressFk, vAgencyModeFk, vLanded, vTicketOriginalFk, vItemFk, vClientTypeFk
		FROM ticket t
			JOIN sale s ON s.ticketFk = t.id
			JOIN `client` c ON t.clientFk = c.id
		WHERE s.id = vSaleFk;

	SET vShippedDayEnd = util.dayEnd(vShipped);

	IF vClientTypeFk <> 'handMaking' THEN
		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 vShipped AND vShippedDayEnd 
				AND t.refFk IS NULL
				AND t.id <> vTicketOriginalFk
				AND IFNULL(ts.alertLevel,0) = 0
			LIMIT 1; 
	END IF;
    
	IF vNewTicket IS NULL THEN
		CALL vn.ticket_Clone(vTicketOriginalFk, vNewTicket);
	END IF;

	INSERT INTO ticketTracking(ticketFk, workerFk, stateFk)
		SELECT vNewTicket, getWorker(), s.id
			FROM state s
			WHERE s.code = 'FIXING';
  
	SELECT COUNT(id) INTO hasAlreadyItem
			FROM sale s
			WHERE s.ticketFk = vNewTicket AND s.itemFk = vItemFk;
 
	IF hasAlreadyItem = FALSE 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

		UPDATE sale  
			SET quantity = quantity + vQuantity
			WHERE ticketFk = vNewTicket AND itemFk = vItemFk;

	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 `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  = 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 `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 ticketFk 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 stPrevious ON stPrevious.saleFk = s.id AND stPrevious.stateFk = 26
		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.itemBarcode ib ON ib.itemFk = i.id
        
    WHERE t.id = ticketFk 
    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 `saleTracking_del` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `saleTracking_del`(vSaleFk INT, vState VARCHAR(50))
BEGIN

	DELETE FROM itemShelvingSale
		WHERE saleFk = vSaleFk;

	DELETE st.*
		FROM vn.saleTracking st
			JOIN vn.state s ON s.id = st.stateFk
		WHERE st.saleFk = vSaleFk 
			AND s.code = vState 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 `saleTracking_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 `saleTracking_new`(	vSaleFK INT, 
										vIsChecked BOOLEAN, 
                                        vOriginalQuantity INT, 
                                        vWorkerFk INT, 
                                        vAction VARCHAR(50), 
                                        vState VARCHAR(50))
BEGIN

	REPLACE vn.saleTracking(saleFk, 
								isChecked, 
                                originalQuantity, 
                                workerFk, 
                                actionFk, 
                                stateFk) 
		SELECT 	vSaleFk,
				vIsChecked,
                vOriginalQuantity,
                vWorkerFk,
                a.accion_id,
                s.id
			FROM vncontrol.accion a
				JOIN vn.state s
			WHERE s.code = vState COLLATE utf8_unicode_ci
				AND a.accion = vAction 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 `sale_calculateComponent` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `sale_calculateComponent`(vSale INT, vOption INT)
proc: BEGIN
/**
 * Actualiza los componentes
 *
 * @param vSale Delivery date
 * @param vOption indica en que componente pone el descuadre, NULL en casos habituales
 * @return tmp.ticketLot(warehouseFk, available, itemFk, buyFk)
 * @return tmp.sale(saleFk, warehouseFk)
 */  
	DECLARE vShipped DATE; 
	DECLARE vWarehouseFk SMALLINT;
    DECLARE vAgencyModeFk INT;
    DECLARE vAddressFk INT;
    DECLARE vTicket BIGINT;
    DECLARE vItem BIGINT;
    DECLARE vLanded DATE; 
    DECLARE vTicketFree BOOLEAN DEFAULT TRUE;
    DECLARE vZoneFk INTEGER;
    
	SELECT  NOT (t.refFk IS NOT NULL OR ts.alertLevel > 0) OR s.price = 0, s.ticketFk, s.itemFk , t.zoneFk
			INTO vTicketFree, vTicket, vItem, vZoneFk
		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
		LIMIT 1;
    	
	SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.agencyModeFk, t.landed
			INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded
		FROM agencyMode a 
			JOIN ticket t ON t.agencyModeFk = a.id
		WHERE t.id = vTicket;

    IF IFNULL(vZoneFk,0) = 0 THEN
		CALL util.throw('ticket dont have zone');
    END IF;
    
    CALL buyUltimate (vWarehouseFk, vShipped);  
    
	DELETE FROM tmp.buyUltimate WHERE itemFk != vItem;
    
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
    CREATE TEMPORARY TABLE tmp.ticketLot 
		SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk
				FROM tmp.buyUltimate
				WHERE itemFk = vItem;
                
	CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped);

    DROP TEMPORARY TABLE IF EXISTS tmp.sale;
	CREATE TEMPORARY TABLE tmp.sale
					(PRIMARY KEY (saleFk)) ENGINE = MEMORY
		SELECT vSale saleFk,vWarehouseFk warehouseFk;
    
    IF vOption IS NULL THEN
		SET vOption = IF(vTicketFree,1,6);
    END IF;
    
	CALL ticketComponentUpdateSale(vOption); 

	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 `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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `scanTreeCreate`()
BEGIN
	CALL nestTree(
		'vn2008', 
		'scan', 
		'vn2008', 
		'scanTree'
	);		

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

	DECLARE vDone BOOL DEFAULT FALSE;
    DECLARE vItemFk INT;
	DECLARE vItemShelvingRest INT;
    DECLARE vItemShelvingFk INT;
    DECLARE vItemShelvingCreated DATE;
	DECLARE vSaleRest INT;
    DECLARE vSaleDated DATE;
    DECLARE vWarehouseFk INT;
    
    DECLARE rsItem CURSOR FOR
		SELECT DISTINCT itemFk
			FROM vn.itemShelvingStock
            WHERE sectorFk = vSectorFk
				AND visible > 0;

	DECLARE rsItemShelving CURSOR FOR
		SELECT 	ish.id, 
                ish.visible,
                date(ish.created)
        FROM vn.itemShelving ish
			JOIN vn.shelving sh ON sh.code = ish.shelvingFk
            JOIN vn.parking p ON p.id = sh.parkingFk
        WHERE ish.itemFk = vItemFk
			AND ish.visible > 0
            AND p.sectorFk = vSectorFk
        ORDER BY date(ish.created), ish.visible; 

	DECLARE rsSale CURSOR FOR
		SELECT 	- floor(sum(io.amount)) as sold,
				date(io.dat) as dated
			FROM vn2008.item_out io
				LEFT JOIN tmp.ticketFree tf ON tf.ticketFk = io.ticketFk
				WHERE (dat BETWEEN util.tomorrow() AND '2019-10-31'
						OR 
						(dat BETWEEN CURDATE() AND util.dayEnd(CURDATE()) AND tf.ticketFk IS NOT NULL))
				AND item_id = vItemFk
                AND io.warehouse_id = vWarehouseFk
				GROUP BY dated;
        
	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	SELECT warehouseFk INTO vWarehouseFk
		FROM vn.sector
        WHERE id = vSectorFk;

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketFree;
	CREATE TEMPORARY TABLE tmp.ticketFree
		SELECT ticket as ticketFk
			FROM vn.ticketStateToday tst
				JOIN vn.state s ON s.id = tst.state
			WHERE s.isPicked = FALSE;
            
	DROP TEMPORARY TABLE IF EXISTS tmp.result;
		CREATE TEMPORARY TABLE tmp.result
			SELECT 	ish.id as itemShelvingFk, 
					date(ish.created) as created, 
					ish.visible,
					0 as reserve,
					CAST('2019-10-31' AS DATE) as picked,
                    ish.shelvingFk,
                    0 as Litros,
                    p.code as parkingCode
				FROM vn.itemShelving ish
					JOIN vn.shelving sh ON sh.code = ish.shelvingFk
					JOIN vn.parking p ON p.id = sh.parkingFk
				WHERE ish.visible > 0
					AND p.sectorFk = vSectorFk
				ORDER BY date(ish.created), ish.visible;
                    
	UPDATE tmp.result r 
		JOIN (SELECT ish.id, floor(sum(ish.visible * r.cm3) / 1000) as Litros
				FROM vn.itemShelving ish
					JOIN bi.rotacion r ON r.Id_Article = ish.itemFk AND r.warehouse_id = vWarehouseFk
				GROUP BY ish.id) sub ON r.itemShelvingFk = sub.id
		SET r.Litros = sub.Litros;
	
    ALTER TABLE tmp.result
		ADD PRIMARY KEY (itemShelvingFk);
		
    OPEN rsItem;
    
    FETCH rsItem INTO vItemFk;
    
    -- TRUNCATE tmp.log;
    
    WHILE NOT vDone DO 

		OPEN rsItemShelving;
		OPEN rsSale;
	
		FETCH rsSale INTO vSaleRest, vSaleDated;
		FETCH rsItemShelving INTO vItemShelvingFk, vItemShelvingRest, vItemShelvingCreated;
        /*
        INSERT INTO tmp.log(vItemFk, vItemShelvingRest, vSaleRest, vSalePicked,ifSide) 
					VALUES (vItemFk, vItemShelvingRest, vSaleRest, vSaleDated, '0');
		*/
		bucle: LOOP

			IF vDone THEN
			
				LEAVE bucle;
				
			END IF;
		
			IF vSaleRest >= vItemShelvingRest THEN
		/*
				INSERT INTO tmp.log(vItemFk, vItemShelvingRest, vSaleRest, vSalePicked,ifSide) 
					VALUES (vItemFk, vItemShelvingRest, vSaleRest, vSaleDated, '1');
		*/		
				SET vSaleRest = vSaleRest - vItemShelvingRest;
				
				UPDATE tmp.result
					SET reserve = reserve + vItemShelvingRest,
						picked = LEAST(picked, vSaleDated)
					WHERE itemShelvingFk = vItemShelvingFk;
					
				FETCH rsItemShelving INTO vItemShelvingFk, vItemShelvingRest, vItemShelvingCreated;
				
				IF vSaleRest = 0 THEN
				
					FETCH rsSale INTO vSaleRest, vSaleDated;
					
				END IF;
			
			ELSE
		/*	
				INSERT INTO tmp.log(vItemFk, vItemShelvingRest, vSaleRest, vSalePicked,ifSide) 
					VALUES (vItemFk, vItemShelvingRest, vSaleRest, vSaleDated, '2');
		*/		
				SET vItemShelvingRest = vItemShelvingRest - vSaleRest;
				
				UPDATE tmp.result
					SET reserve = reserve + vSaleRest,
						picked = LEAST(picked, vSaleDated)
					WHERE itemShelvingFk = vItemShelvingFk;

				FETCH rsSale INTO vSaleRest, vSaleDated;
				
			END IF;

		END LOOP;
		
		CLOSE rsItemShelving;
		CLOSE rsSale;
         /*
        INSERT INTO tmp.log(vItemFk, vItemShelvingRest, vSaleRest, vSalePicked,ifSide) 
					VALUES (vItemFk, vItemShelvingRest, vSaleRest, vSaleDated, '4');
         */           
		SET vDone = FALSE;
        
        FETCH rsItem INTO vItemFk;    
        
	END WHILE;
    
    CLOSE rsItem;

	SELECT * FROM tmp.result
		ORDER BY created, 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 `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,1);
		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.ticketParking(ticketFk,parkingFk)
			VALUES (vShelvingFk, vParkingFk);
        -- deprecated: eliminar despues de campaña PAK 2019-10-08  
		REPLACE vn.shelving(code, parkingFk, isPrinted, parked)
			VALUES(vShelvingFk, vParkingFk, TRUE, NOW());
        -- fin deprecated    
		CALL vn.ticketStatePrevious(vShelvingFk);
      
    ELSE
    
    
		UPDATE vn.shelving
			SET parkingFk = vParkingFk, parked = NOW()
			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 `shelvingPark_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 `shelvingPark_Beta__`(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.ticketParking(ticketFk,parkingFk)
			VALUES (vShelvingFk, vParkingFk);
          
		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 `shelving_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 `shelving_clean`()
BEGIN

	DELETE FROM vn.shelving
		WHERE length(code) > 3
			AND parked < TIMESTAMPADD(WEEK,-1,CURDATE());

	UPDATE vn.shelving sh
		LEFT JOIN vn.itemShelving its ON its.shelvingFk = sh.`code`
		SET isPrinted = 0
        WHERE isPrinted = 1
			AND its.id IS NULL
            AND (	sh.parked IS NULL 
					OR 
                    sh.parked < TIMESTAMPADD(MONTH,-1,CURDATE())
				);

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sinComponentes` */;
/*!50003 SET @saved_cs_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 `sinComponentes`()
BEGIN
  DECLARE v_done BOOL DEFAULT FALSE;
  DECLARE vSaleFk INTEGER;
  DECLARE vCur CURSOR FOR
SELECT s.id
	FROM vn.ticket t
    JOIN vn.client clt ON clt.id = t.clientFk
    JOIN vn.sale s ON s.ticketFk = t.id
    JOIN vn.item i ON i.id = s.itemFk
    JOIN vn.itemType tp ON tp.id = i.typeFk
    JOIN vn.itemCategory ic ON ic.id = tp.categoryFk
    LEFT JOIN tmp.coste c ON c.id = s.id
	WHERE t.shipped  >= '2019-10-01' AND  t.shipped  <= '2019-10-30'
    AND c.id IS NULL
    AND clt.isActive != 0
    AND ic.merchandise != 0
    GROUP BY s.id;
   
  DECLARE CONTINUE HANDLER FOR NOT FOUND
    SET v_done = TRUE; 

DROP TEMPORARY TABLE IF EXISTS tmp.coste;

DROP TEMPORARY TABLE IF EXISTS tmp.coste;
CREATE TEMPORARY TABLE tmp.coste
     (primary key (id)) ENGINE = MEMORY
    SELECT s.id
	FROM vn.ticket t
		JOIN vn.client clt ON clt.id = t.clientFk
		JOIN vn.sale s ON s.ticketFk = t.id
		JOIN vn.item i ON i.id = s.itemFk
		JOIN vn.itemType tp ON tp.id = i.typeFk
		JOIN vn.itemCategory ic ON ic.id = tp.categoryFk
		JOIN vn.saleComponent sc ON sc.saleFk = s.id
		JOIN vn.component c ON c.id = sc.componentFk
		JOIN vn.componentType ct ON ct.id = c.typeFk AND ct.id = 1
	WHERE t.shipped  >= '2019-10-01'
		AND ic.merchandise != 0;
	
        
  OPEN vCur;

  l: LOOP
   SET v_done = FALSE;
   FETCH vCur INTO vSaleFk;

   IF v_done THEN
    LEAVE l;
   END IF;

   CALL vn.ticketCalculateSaleForcePrice2(vSaleFk);
  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 `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` */;
/*!50003 SET @saved_cs_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 `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 ) * vn.buy_getVolume(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 */ ;
/*!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  = 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 `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 ) * vn.buy_getVolume(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  = 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 `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 ) * vn.buy_getVolume(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);

    INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador)
		SELECT id, vShipFk, getWorker()
			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 `stowaway_unboarding` */;
/*!50003 SET @saved_cs_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 `stowaway_unboarding`(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 worker w ON w.userFk = u.id
		WHERE w.id = client_getSalesPersonByTicket(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

	-- deprecated usar vn.worker_GetHierarch
	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 `supplierExpenses` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `supplierExpenses`(vEnded DATE)
BEGIN

	DROP TEMPORARY TABLE IF EXISTS openingBalance;

	CREATE TEMPORARY TABLE openingBalance(
		dueDated DATE
		, supplierFk INT NOT NULL
		, companyFk INT NOT NULL
		, eurAmount DOUBLE NOT NULL
		, foreignAmount DOUBLE NOT NULL
		, PRIMARY KEY(supplierFk, companyFk))
	ENGINE =  MEMORY;

	-- Calcula el balance inicial y final de cada proveedor
	INSERT INTO openingBalance
		SELECT MAX(dueDated),
				supplierFk, 
                companyFk, 
				sum(amount) eurAmount,
				sum(divisa) foreignAmount
		FROM (
			SELECT p.dueDated,
				p.supplierFk, 
				p.companyFk,
				p.amount,
                p.divisa
			FROM payment p
				JOIN currency c ON c.id = p.currencyFk
                JOIN company co ON co.id = p.companyFk
			WHERE p.dueDated > '2014-12-31'
				AND p.dueDated <= vEnded
				AND co.`code` = 'VNL'
				AND c.`code` <> 'EUR'
		UNION ALL

			SELECT iidd.dueDated,
					ii.supplierFk,
					ii.companyFk,
					- iidd.amount, 
                    - iidd.foreignValue
			FROM invoiceIn ii
				JOIN invoiceInDueDay iidd ON ii.id = iidd.invoiceInFk
				JOIN currency c ON c.id = ii.currencyFk
                JOIN company co ON co.id = ii.companyFk
			WHERE  iidd.dueDated > '2014-12-31'
				AND iidd.dueDated <= vEnded
				AND ii.isBooked AND co.`code` = 'VNL' 
                AND c.`code` <> 'EUR'
		UNION ALL

			SELECT se.dueDated,
					se.supplierFk,
					se.companyFk,
					- se.amount, 
                    0
			FROM supplierExpense se
				JOIN currency c ON c.id = se.currencyFk
                JOIN company co ON co.id = se.companyFk
			WHERE se.dueDated > '2014-12-31'
				AND se.dueDated <= vEnded
				AND co.`code` = 'VNL' AND c.`code` <> 'EUR'
		) sub
		GROUP BY companyFk, supplierFk;
  
    SELECT ob.dueDated
			, ob.supplierFk
			, ob.companyFk
			, ob.eurAmount
            , s.`name`
		FROM openingBalance ob
			LEFT JOIN supplier s ON s.id = ob.supplierFk
		WHERE ob.eurAmount <> 0 AND ob.foreignAmount = 0;

    DROP TEMPORARY TABLE openingBalance;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 `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`(
    vLanded DATE,
    vAddressFk INT,
    vAgencyModeFk INT)
proc: BEGIN
-- OBSOLETO utilizar catalog_calculate
    CALL vn.catalog_calculate(vLanded, vAddressFk, 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 `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;
    DECLARE vZoneFk 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, t.zoneFk
		INTO vClient, vWarehouse, vShipped, vAddress, vAgencyMode, vLanded, vAgency, vZoneFk
    FROM vn.agencyMode a
		JOIN vn.ticket t ON t.agencyModeFk = a.id
    WHERE t.id = vTicketNew;

	IF vLanded IS NULL THEN
		CALL zone_getLanded(vShipped, vAddress, vAgency, vWarehouse);
        UPDATE ticket t
				JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk 
			SET t.landed = zgl.landed,
				t.zone = zgl.zoneFk
			WHERE t.id = vTicketNew;
		
        SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1;
		DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded;
    END IF;
    
    -- rellena la tabla tmp.buyUltimate con la ultima compra
    CALL buyUltimate(vWarehouse, vShipped);  
    
    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 catalog_componentCalculate(vZoneFk, 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);
	
	-- 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.zoneGetLanded;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketCalculateFromType` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateFromType`( vLanded DATE,
    vAddressFk INT,
    vAgencyModeFk INT,
    vTypeFk INT)
BEGIN
	DROP TEMPORARY TABLE IF EXISTS tmp.item;
	CREATE TEMPORARY TABLE tmp.item 
		(INDEX (itemFk)) 
		ENGINE = MEMORY 
		SELECT id itemFk FROM vn.item
			WHERE typeFk = vTypeFk;
            
	CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk);
	DROP TEMPORARY TABLE tmp.item;
	DROP TEMPORARY TABLE 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 `ticketCalculatePurge` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculatePurge`()
BEGIN
	DROP TEMPORARY TABLE 
		tmp.ticketCalculateItem,
		tmp.ticketComponentPrice,
		tmp.ticketComponent,
        tmp.ticketLot,
		tmp.zoneGetShipped;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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
-- OBSOLETO USAR: sale_calculateComponent(vSale, NULL)
	DECLARE vShipped DATE; 
	DECLARE vWarehouseFk SMALLINT;
    DECLARE vAgencyModeFk INT;
    DECLARE vAddressFk INT;
    DECLARE vTicket BIGINT;
    DECLARE vItem BIGINT;
    DECLARE vLanded DATE; 
    DECLARE vTicketFree BOOLEAN DEFAULT TRUE;
    DECLARE vZoneFk INTEGER;
    
	SELECT  NOT (t.refFk IS NOT NULL OR ts.alertLevel > 0) OR s.price = 0, s.ticketFk, s.itemFk , t.zoneFk
			INTO vTicketFree, vTicket, vItem, vZoneFk
		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
		LIMIT 1;
    	
	SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.agencyModeFk, t.landed
			INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded
		FROM agencyMode a 
			JOIN ticket t ON t.agencyModeFk = a.id
		WHERE t.id = vTicket;

    IF IFNULL(vZoneFk,0) = 0 THEN
		CALL util.throw('ticket dont have zone');
    END IF;
    
    CALL buyUltimate (vWarehouseFk, vShipped);  
    
	DELETE FROM tmp.buyUltimate WHERE itemFk != vItem;
    
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
    CREATE TEMPORARY TABLE tmp.ticketLot 
		SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk
				FROM tmp.buyUltimate
				WHERE itemFk = vItem;
                
	CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped);

    DROP TEMPORARY TABLE IF EXISTS tmp.sale;
	CREATE TEMPORARY TABLE tmp.sale
					(PRIMARY KEY (saleFk)) ENGINE = MEMORY
		SELECT vSale saleFk,vWarehouseFk 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 `ticketCalculateSaleForcePrice` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSaleForcePrice`(IN vSale BIGINT)
proc: BEGIN

	DECLARE vShipped DATE; 
	DECLARE vWarehouseFk SMALLINT;
    DECLARE vAddressFk INT;
    DECLARE vTicket BIGINT;
    DECLARE vItem BIGINT;
    DECLARE vZoneFk INT;    
    
    SELECT ticketFk, itemFk 
			INTO vTicket, vItem 
		FROM sale 
        WHERE id = vSale;
    	
	SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.zoneFk
			INTO vWarehouseFk, vShipped, vAddressFk, vZoneFk
		FROM agencyMode a 
			JOIN ticket t ON t.agencyModeFk = a.id
		WHERE t.id = vTicket;
  
    IF vZoneFk IS NULL THEN
		CALL util.throw('ticket without zone');
    END IF;
    
    CALL buyUltimate (vWarehouseFk, vShipped);  
    
	DELETE FROM tmp.buyUltimate WHERE itemFk != vItem;
    
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
    CREATE TEMPORARY TABLE tmp.ticketLot 
		SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk
				FROM tmp.buyUltimate
				WHERE itemFk = vItem;
                
	CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped);
    
    DROP TEMPORARY TABLE IF EXISTS tmp.sale;
	CREATE TEMPORARY TABLE tmp.sale
					(PRIMARY KEY (saleFk)) ENGINE = MEMORY
		SELECT vSale saleFk,vWarehouseFk warehouseFk;
                
	CALL ticketComponentUpdateSale(1); 

	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 `ticketCalculateSaleForcePrice2` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSaleForcePrice2`(IN vSale BIGINT)
proc: BEGIN

	DECLARE vShipped DATE; 
	DECLARE vWarehouseFk SMALLINT;
    DECLARE vAddressFk INT;
    DECLARE vTicket BIGINT;
    DECLARE vItem BIGINT;
    DECLARE vZoneFk INT;
        
    SELECT ticketFk, itemFk 
			INTO vTicket, vItem 
		FROM sale 
        WHERE id = vSale;
    	
	SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.zoneFk
			INTO vWarehouseFk, vShipped, vAddressFk, vZoneFk
		FROM agencyMode a 
			JOIN ticket t ON t.agencyModeFk = a.id
		WHERE t.id = vTicket;
  
    IF vZoneFk IS NULL THEN
		CALL util.throw('ticket without zone');
    END IF;
    
    CALL buyUltimate (vWarehouseFk, vShipped);  
    
	DELETE FROM tmp.buyUltimate WHERE itemFk != vItem;
    
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
    CREATE TEMPORARY TABLE tmp.ticketLot 
		SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk
				FROM tmp.buyUltimate
				WHERE itemFk = vItem;
                
	CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped);
    
    DROP TEMPORARY TABLE IF EXISTS tmp.sale;
	CREATE TEMPORARY TABLE tmp.sale
					(PRIMARY KEY (saleFk)) ENGINE = MEMORY
		SELECT vSale saleFk,vWarehouseFk warehouseFk;
                
	CALL ticketComponentUpdateSale(1); 

	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 `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 vWarehouseFk SMALLINT;
    DECLARE vAgencyModeFk INT;
    DECLARE vAddressFk INT;
    DECLARE vTicket BIGINT;
    DECLARE vItem BIGINT;
    DECLARE vLanded DATE; 
    DECLARE vTicketFree BOOLEAN DEFAULT TRUE;
    DECLARE vZoneFk INTEGER;
    
	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 vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded
		FROM agencyMode a 
			JOIN ticket t ON t.agencyModeFk = a.id
		WHERE t.id = vTicket;
  
	CALL zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk);
  
	SELECT id INTO vZoneFk 
		FROM tmp.zoneGetShipped
		WHERE warehouseFk = vWarehouseFk
			AND shipped = vShipped;

    IF IFNULL(vZoneFk,0) = 0 THEN
		CALL util.throw('not zone with this parameters');
    END IF;
    
    CALL buyUltimate (vWarehouseFk, vShipped);  
    
	DELETE FROM tmp.buyUltimate WHERE itemFk != vItem;
    
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
    CREATE TEMPORARY TABLE tmp.ticketLot 
		SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk
				FROM tmp.buyUltimate
				WHERE itemFk = vItem;
                
	CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped);

    DROP TEMPORARY TABLE IF EXISTS tmp.sale;
	CREATE TEMPORARY TABLE tmp.sale
					(PRIMARY KEY (saleFk)) ENGINE = MEMORY
		SELECT vSale saleFk,vWarehouseFk 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_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosure`()
BEGIN
/**
 * Realiza el cierre de todos los 
 * tickets de la table ticketClosure.
 */
	DECLARE vDone BOOL;
	DECLARE vClientFk INT;
	DECLARE vTicketFk INT;
	DECLARE vIsTaxDataChecked BOOL;
	DECLARE vCompanyFk INT;
	DECLARE vShipped DATE;
	DECLARE vPriority INT DEFAULT 1;
	DECLARE vReportDeliveryNote INT DEFAULT 1;
	DECLARE vNewInvoiceId INT;
	DECLARE vHasDailyInvoice 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.hasDailyInvoice,
				w.isManaged
			INTO vClientFk,
				vIsTaxDataChecked,
				vCompanyFk, 
				vShipped,
				vHasDailyInvoice,
				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;

		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(vHasDailyInvoice) THEN

			-- Facturacion rapida
			CALL ticketTrackingAdd(vTicketFk, 'DELIVERED', NULL);
			-- Facturar si está contabilizado
			IF vIsTaxDataChecked THEN
				CALL invoiceOut_newFromClient(
					vClientFk, 
					(SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), 
					vShipped, 
					vCompanyFk, 
					NULL,
					vNewInvoiceId);
			END IF;
		ELSE
			-- Albaran_print
			CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), NULL);
            -- Comentar al pasar a nuevo cierre
            INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(vPriority, vReportDeliveryNote, vTicketFk);
            -- INSERT INTO 
		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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentCalculate__`(
    vAddressFk INT,
    vAgencyModeFk INT)
proc: BEGIN
-- OBSOLETO usar catalog_componentCalculate
/**
 * Calcula los componentes de un ticket
 *
 * @param vAddressFk Id del consignatario
 * @param vAgencyModeFk Id del modo de agencia
 * @return tmp.ticketComponent(itemFk, warehouseFk, available, rate2, rate3, minPrice,
 *		packing, grouping, groupingMode, buyFk, typeFk)
 * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price)
 */
 
	DECLARE vClientFk INT;
    DECLARE vGeneralInflationCoefficient INT DEFAULT 1;
    DECLARE vMinimumDensityWeight INT DEFAULT 167;
	DECLARE vBoxFreightItem INT DEFAULT 71;
    DECLARE vBoxVolume BIGINT; -- DEFAULT 138000;
	DECLARE vSpecialPriceComponent INT DEFAULT 10;
	DECLARE vDeliveryComponent INT DEFAULT 15;
	DECLARE vRecoveryComponent INT DEFAULT 17;
	DECLARE vSellByPacketComponent INT DEFAULT 22;
	DECLARE vBuyValueComponent INT DEFAULT 28;
	DECLARE vMarginComponent INT DEFAULT 29;
	DECLARE vDiscountLastItemComponent INT DEFAULT 32;
	DECLARE vExtraBaggedComponent INT DEFAULT 38;
	DECLARE vManaAutoComponent INT DEFAULT 39;
    
    
    
    SELECT volume INTO vBoxVolume
		FROM vn.packaging
        WHERE id = '94';
        
    SELECT clientFk INTO vClientFK 
		FROM address 
        WHERE id = vAddressFk;

    SET @rate2 := 0;
    SET @rate3 := 0;

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate;
	CREATE TEMPORARY TABLE tmp.ticketComponentCalculate
	(PRIMARY KEY (itemFk, warehouseFk))
	ENGINE = MEMORY
		SELECT 
			tl.itemFk, tl.warehouseFk, tl.available,
			IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2,
			IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3,
            IFNULL(pf.rate3, 0) AS minPrice,
			IFNULL(pf.packing, b.packing) packing,
			IFNULL(pf.`grouping`, b.`grouping`) `grouping`,
			ABS(IFNULL(pf.box, b.groupingMode)) groupingMode,
            tl.buyFk, 
            i.typeFk,
            IF(i.hasKgPrice,b.weight / b.packing, NULL) weightGrouping           
        FROM tmp.ticketLot tl
		JOIN buy b ON b.id = tl.buyFk
		JOIN item i ON i.id = tl.itemFk
        JOIN itemType it ON it.id = i.typeFk
        LEFT JOIN itemCategory ic ON ic.id = it.categoryFk
		LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk
		LEFT JOIN (
			SELECT * FROM (
				SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, aho.warehouseFk
					FROM priceFixed pf
					JOIN tmp.zoneGetShipped 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((z.price - z.bonus)
					* 1/*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 tmp.zoneGetShipped zgs ON zgs.warehouseFk = tcc.warehouseFk 
            JOIN zone z ON z.id = zgs.id
			LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk 
				AND r.Id_Article = tcc.itemFk
			HAVING cost <> 0; 
            
    IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN
		INSERT INTO tmp.ticketComponent
			SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost
				FROM tmp.ticketComponentCalculate tcc
					JOIN vn.addressForPackaging ap
				WHERE ap.addressFk = vAddressFk;
    END IF;
	
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy;
    CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY
		SELECT * FROM tmp.ticketComponent;
        
	INSERT INTO tmp.ticketComponent
		SELECT tcc.warehouseFk, 
				tcc.itemFk, 
				vSpecialPriceComponent, 
				sp.value - SUM(tcc.cost) sumCost
			FROM tmp.ticketComponentCopy tcc
				JOIN 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`, 
				CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price,
                CAST(SUM(tcs.sumCost)  / weightGrouping AS DECIMAL(10,2)) priceKg      
			FROM tmp.ticketComponentCalculate tcc
				JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk 
					AND tcs.warehouseFk = tcc.warehouseFk
			WHERE IFNULL(tcs.classRate, 1) = 1 
				AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0)
			GROUP BY tcs.warehouseFk, tcs.itemFk;

	INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg)
        SELECT 
				tcc.warehouseFk, 
				tcc.itemFk, 
				2 rate, 
				tcc.packing `grouping`, 
				SUM(tcs.sumCost) price,
                SUM(tcs.sumCost) / weightGrouping priceKg
			FROM tmp.ticketComponentCalculate tcc
				JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk 
					AND tcs.warehouseFk = tcc.warehouseFk
			WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 
				AND tcc.packing > 0 AND tcc.available >= tcc.packing)
			GROUP BY tcs.warehouseFk, tcs.itemFk;

	INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg)
		 SELECT 				
		 		tcc.warehouseFk, 
				tcc.itemFk, 
				3 rate, 
				tcc.available `grouping`, 
				SUM(tcs.sumCost) price,
                SUM(tcs.sumCost) / weightGrouping priceKg
			FROM tmp.ticketComponentCalculate tcc
				JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk 
					AND tcs.warehouseFk = tcc.warehouseFk
			WHERE IFNULL(tcs.classRate, 3) = 3 
			GROUP BY tcs.warehouseFk, tcs.itemFk;
        
	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 `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
-- OBSOLETO usar ticket_componentPreview
	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;

	CALL zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk);

	SELECT shipped INTO vShipped 
		FROM tmp.zoneGetShipped
		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.zoneGetShipped,
        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 `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;
    
   IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN
			
		UPDATE ticket t 
				JOIN address a ON a.id = vAddressFk
			SET t.nickname = a.nickname
			WHERE t.id = vTicketFk;
            
    END IF;
    
	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  = 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 `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 `component` c ON c.id = sc.componentFk
        WHERE c.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 `component` c ON c.id = tc.componentFk 
                WHERE IF(sc.componentFk IS NULL AND NOT c.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 `component` c ON c.id = sc.componentFk
					JOIN componentType ct on ct.id = c.typeFk AND ct.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 `ticketCreateWithoutZone` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithoutZone`(
     vClientId INT
    ,vShipped DATE
    ,vWarehouseFk INT
    ,vCompanyFk INT
    ,vAddressFk INT
    ,vAgencyModeFk INT
    ,vRouteFk INT
    ,vlanded DATE
    ,vUserId INT
    ,OUT vNewTicket INT)
BEGIN

	DECLARE vZoneFk INT;
    
	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;
    
    IF NOT vAgencyModeFk OR vAgencyModeFk IS NULL THEN
        SELECT agencyModeFk INTO vAgencyModeFk 
            FROM address
            WHERE clientFk = vClientId AND isDefaultAddress;
    END IF;

	CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk);
    
	SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped
		WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1;
	
	INSERT INTO vn2008.Tickets (
			Id_Cliente,
			Fecha,
			Id_Consigna,
			Id_Agencia,
			Alias,
			warehouse_id,
			Id_Ruta,
			empresa_id,
			landing,
            zoneFk
		)
		SELECT
					vClientId,
					vShipped,
					a.id,
					IF(vAgencyModeFk, vAgencyModeFk, a.agencyModeFk),
					a.nickname,
					vWarehouseFk,
					IF(vRouteFk,vRouteFk,NULL),
					vCompanyFk,
					vlanded,
                    vZoneFk
			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 `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
    ,vWarehouseFk INT
    ,vCompanyFk INT
    ,vAddressFk INT
    ,vAgencyModeFk INT
    ,vRouteFk INT
    ,vlanded DATE
    ,vUserId INT
    ,OUT vNewTicket INT)
BEGIN

	DECLARE vZoneFk INT;
    
	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;
    
	IF vAgencyModeFk IS NOT NULL THEN
		
		CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk);
    
		SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped
			WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1;
		
		IF vZoneFk IS NULL OR vZoneFk = 0 THEN
			CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS'); 
		END IF;
	END IF;
	INSERT INTO ticket (
			clientFk,
			shipped,
			addressFk,
			agencyModeFk,
			nickname,
			warehouseFk,
			routeFk,
			companyFk,
			landed,
            zoneFk
		)
		SELECT
					vClientId,
					vShipped,
					a.id,
					vAgencyModeFk,
					a.nickname,
					vWarehouseFk,
					IF(vRouteFk,vRouteFk,NULL),
					vCompanyFk,
					vlanded,
                    vZoneFk
			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;

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

	UPDATE vn.ticketDown td
		JOIN
			(SELECT DISTINCT t.id
				FROM vn.ticket t
					JOIN vn.sale s ON s.ticketFk = t.id
                    JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id
                    JOIN vn.itemShelving ish ON ish.id = iss.itemShelvingFk
                    JOIN vn.shelving sh ON sh.code = ish.shelvingFk
                    JOIN vn.parking p ON p.id = sh.parkingFk
					WHERE p.sectorFk = vSectorFk
			) sub ON sub.id = td.ticketFk
		JOIN vn.ticketDown_SelectionType tdst ON tdst.description = 'FREE'
        JOIN vn.ticketDown_SelectionType tdst2 ON tdst2.description = 'SELECTED'
		SET td.selected = tdst2.id
        WHERE td.selected = tdst.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 `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;
            
     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.available av ON av.item_id = i.id
                    AND av.calc_id = vAvailableCache
                WHERE date(t.shipped) = vDate
                    AND categoryFk != 6
                    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;

    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 `ticketMissed_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 `ticketMissed_List`(vTicketFk INT)
BEGIN

    DECLARE vParkingFk INT;
    DECLARE vParked DATETIME;
    DECLARE vLevel INT;
    DECLARE vCollectionFk INT;
    
    SELECT IFNULL(`level`,0), IFNULL(collectionFk,0) 
		INTO vLevel, vCollectionFk
		FROM vn.ticketCollection
        WHERE ticketFk = vTicketFk;
        
	SELECT created, parkingFk 
		INTO vParked, vParkingFk
		FROM vn.ticketParking
        WHERE ticketFk = vTicketFk;
        
    SELECT tp.ticketFk, CONCAT(vCollectionFk, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia
		FROM vn.ticketParking tp
        JOIN vn.parking p ON p.id = tp.parkingFk
        JOIN vn.sector sc ON sc.id = p.sectorFk
        LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk
        JOIN vn.ticketStateToday tst ON tst.ticket = tp.ticketFk
        JOIN vn.ticket t ON t.id = tp.ticketFk
        JOIN vn.zone z ON z.id = t.zoneFk
        JOIN vn.agencyMode am ON am.id = z.agencyModeFk
        JOIN vn.state s ON s.id = tst.state
        WHERE s.alertLevel < 2
			AND tp.parkingFk = vParkingFk
            AND sc.isPackagingArea
            AND (
					(
						( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked )
					OR
						( tc.collectionFk = vCollectionFk AND LEFT(tc.level,1) < LEFT(vLevel,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 `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 vCompanyFk INT;
	DECLARE vAgenciaEmbalajesFk INT DEFAULT 628;

	DECLARE rs CURSOR FOR
			SELECT DISTINCT tp.ticketFk, a.clientFk, t.warehouseFk, t.shipped, 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 t.shipped > '2001-01-01';

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	OPEN rs;

	FETCH rs INTO vTicketFk, vClientFk, vWarehouseFk, vShipped, vCompanyFk;

	WHILE NOT done DO

		CALL vn.ticketCreate(vClientFk,vShipped,vWarehouseFk,vCompanyFk, NULL, NULL, 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, 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 `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;
         */
        INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador, Id_Supervisor)
			SELECT s.nextStateFk, i.Id_Ticket, vLastWorkerFk, vn.getWorker()
				FROM vncontrol.inter i
					JOIN vn.state s ON i.state_id = s.id
                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, IN vSectorFk INT)
BEGIN

/* Tickets con estado 26 para preaprar en altillo 
*/
IF viewAll IS true THEN
	SELECT   stpp.*,ispss.created,ispss.sectorFk
		FROM vn.salesToPrePrepare stpp
        LEFT JOIN vn.itemShelvingPlacementSupplyStock ispss 
			ON ispss.itemShelvingFk = (SELECT itemShelvingFk FROM vn.itemShelvingPlacementSupplyStock WHERE itemFk = stpp.Id_Article AND sectorFk = vSectorFk   ORDER BY parking ASC LIMIT 1)
        LEFT JOIN vn.parking p ON p.id = ispss.parkingFk
        WHERE stpp.Id_Ticket =  vIdTicket
        ORDER BY  p.column ASC;
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  = 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 `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 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 `ticketVolumeByDate_ventas` */;
/*!50003 SET @saved_cs_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 `ticketVolumeByDate_ventas`(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 bs.ventas v ON v.Id_Movimiento = s.id
					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 t.shipped BETWEEN vDateStart AND vDateEnd
                    AND it.name NOT IN ('Accesorios Funerarios','Composiciones planta','Composición bajo pedido','Coronas y centros')
                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 `ticketVolumeByDate_ventas_Artificial` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_ventas_Artificial`(vDate DATE)
BEGIN

	DECLARE vDateStart DATETIME DEFAULT DATE(vDate);
    DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate);

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketVolumeByDate_Artificial;
        
    CREATE TEMPORARY TABLE tmp.ticketVolumeByDate_Artificial
	ENGINE = MEMORY
	SELECT s.ticketFk,
			CAST(SUM(r.cm3 * s.quantity) / 1000000 AS DECIMAL(10,2)) as m3
                FROM sale s
					JOIN bs.ventas v ON v.Id_Movimiento = s.id
					JOIN vn.item i ON i.id = s.itemFk
                    JOIN vn.sector sc ON sc.id = i.sectorFk
                    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 sc.description = 'Artificial'
                    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 `ticket_Clone` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticket_Clone`(vOriginalTicket INT, OUT vNewTicket INT)
BEGIN
	INSERT INTO ticket (
				clientFk,
				shipped,
				addressFk,
				agencyModeFk,
				nickname,
				warehouseFk,
				companyFk,
				landed,
				zoneFk
		)
		SELECT
					clientFk,
					shipped,
					addressFk,
					agencyModeFk,
					nickname,
					warehouseFk,
					companyFk,
					landed,
                    zoneFk
			FROM ticket
			WHERE id = vOriginalTicket;

	SET vNewTicket = LAST_INSERT_ID();
    
	INSERT INTO ticketObservation(ticketFk, observationTypeFk, description)
		SELECT vNewTicket, ao.observationTypeFk, ao.description
			FROM addressObservation ao
				JOIN ticket t ON t.addressFk = ao.addressFk
			WHERE t.id = vNewTicket;

    INSERT INTO ticketLog
		SET originFk = vNewTicket, userFk = account.myUserGetId(), `action` = 'insert', 
			description = CONCAT('Ha creado el ticket:', ' ', vNewTicket, ' clonando el ', vOriginalTicket);

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_componentMakeUpdate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_componentMakeUpdate`(	
	vTicketFk INT,
    vClientFk INT,
	vAgencyModeFk INT,
	vAddressFk INT,
    vZoneFk INT,
	vWarehouseFk TINYINT,
    vCompanyFk SMALLINT,
	vShipped DATETIME,
	vLanded DATE,
    vIsDeleted BOOLEAN,
    vHasToBeUnrouted BOOLEAN,
	vOption INT)
BEGIN

	CALL vn.ticket_componentPreview (vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk);
    CALL vn.ticket_componentUpdate (
		vTicketFk, 
        vClientFk,
        vAgencyModeFk, 
        vAddressFk, 
        vZoneFk,
		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 `ticket_componentPreview` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticket_componentPreview`(
	vTicketFk INT,
    vLanded DATE, 
    vAddressFk INT,
    vZoneFk INT,
    vWarehouseFk SMALLINT)
BEGIN
/**
 * Calcula los componentes de los articulos de un ticket
 *
 * @param vTicketFk id del ticket
 * @param vLanded nueva fecha de entrega
 * @param vAddressFk nuevo consignatario
 * @param vZoneFk nueva zona
 * @param vWarehouseFk nuevo warehouse
 *
 * @return tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost)
 */
	DECLARE vShipped DATE;
	DECLARE vBuyOrderItem INT DEFAULT 100;

    DECLARE vHasDataChanged BOOL DEFAULT FALSE;    
    DECLARE vHasAddressChanged BOOL;
    DECLARE vHasZoneChanged 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, 
			zoneFk <> vZoneFk,
            warehouseFk <> vWarehouseFk
		INTO
			vHasDataChanged,
            vHasAddressChanged,
            vHasZoneChanged,
            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 vHasZoneChanged THEN
		SET vAgencyModeTypeRateFk = 6;
    END IF;

	SELECT TIMESTAMPADD(DAY, -travelingDays, vLanded) INTO vShipped 
		FROM zone
		WHERE id = vZoneFk;
        
	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 catalog_componentCalculate(vZoneFk, vAddressFk, vShipped);

	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 `component` c ON c.id = sc.componentFk
			WHERE s.ticketFk = vTicketFk 
				AND (c.isRenewable = FALSE 
					OR 
					(NOT vHasChangeAll
						AND (NOT (c.typeFk <=> vAddressTypeRateFk
                        OR c.typeFk <=> vAgencyModeTypeRateFk))));

    SET @shipped = vShipped;

	DROP TEMPORARY TABLE
        tmp.buyUltimate,
		tmp.ticketLot;

	IF vShipped IS NULL THEN
		CALL util.throw('NO_ZONE_AVAILABLE');
    END IF;
    
	IF vShipped < CURDATE() THEN
		CALL util.throw('ERROR_PAST_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 `ticket_componentUpdate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_componentUpdate`(
	 vTicketFk INT,
     vClientFk INT,
     vAgencyModeFk INT,
     vAddressFk INT,
     vZoneFk 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;
    
   IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN
			
		UPDATE ticket t 
				JOIN address a ON a.id = vAddressFk
			SET t.nickname = a.nickname
			WHERE t.id = vTicketFk;
            
    END IF;
    
	UPDATE ticket t
		SET 
			t.clientFk = vClientFk,
			t.agencyModeFk = vAgencyModeFk,
			t.addressFk = vAddressFk,
            t.zoneFk = vZoneFk,
			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 `ticket_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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_getTax`(vTaxArea VARCHAR(25))
    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 ();
    
    IF vTaxArea > '' THEN
		UPDATE tmp.addressTaxArea
			SET areaFk = vTaxArea;
	END IF;
 /** 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 * FROM (  
		SELECT tmpTicket.ticketFk,
                bp.pgcFk,
                SUM(s.quantity * s.price * (100 - s.discount)/100 ) AS taxableBase,
                pgc.rate,
                tc.code,
                bp.priority
            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) t
		ORDER BY priority;

   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 `ticket_insertZone` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_insertZone`()
BEGIN
	DECLARE vDone INT DEFAULT 0;
    DECLARE vFechedTicket INT;
    DECLARE vLanded DATE;
    DECLARE vAddressFk INT;
    DECLARE vAgencyModeFk INT;
    DECLARE vWarehouseFk INT;
	DECLARE vCursor CURSOR FOR 
		SELECT id, landed, addressFk, agencyModeFk, warehouseFk
        FROM vn.ticket WHERE shipped >= '2019-07-01';
	DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET vDone = 1;
    
    OPEN vCursor;
    REPEAT
		FETCH vCursor INTO vFechedTicket, vLanded, vAddressFk, vAgencyModeFk, vWarehouseFk;
        CALL zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk);
        UPDATE vn.ticket t
			JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = vWarehouseFk
			SET zoneFk = zgs.id
		WHERE t.id = vFechedTicket;
        
     UNTIL vDone END REPEAT;
	DROP TEMPORARY TABLE tmp.zoneGetShipped;
    CLOSE vCursor;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_priceDifference` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticket_priceDifference`(
	vTicketFk INT,
    vLanded DATE, 
    vAddressFk INT,
    vZoneFk 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 vZoneFk Id de la zona
 * @param vWarehouseFk Id del almacén
 */
	CALL vn.ticket_componentPreview(vTicketFk, vLanded, vAddressFk, vZoneFk, 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 `component` c ON c.id = tc.componentFk 
		WHERE 
			t.id = vTicketFk 
			AND IF(sc.componentFk IS NULL 
				AND c.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 `ticket_recalcComponents` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_recalcComponents`(IN vTicketFk BIGINT )
proc: BEGIN

/**
 * Este procedimiento trata de "rebionizar" un ticket, 
 * eliminando los componentes existentes e insertandolos de nuevo
 *
 * @param vTicketFk Id del ticket
 * @return tmp.buyUltimate
 */
	DECLARE vShipped DATE;
	DECLARE vWarehouseFk SMALLINT;
    DECLARE vAgencyModeFk INT;
    DECLARE vAddressFk INT;
    DECLARE vLanded DATE;
    DECLARE vIsTicketEditable BOOLEAN;
    DECLARE vZoneFk INTEGER;
        
	SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk
		INTO vIsTicketEditable, vZoneFk
		FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket
		WHERE id = vTicketFk;
	
	SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed
			INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded
		FROM ticket
		WHERE id = vTicketFk;
		
    CALL zoneGetShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk);
	
    CALL vn.buyUltimate (vWarehouseFk, vShipped);  -- rellena la tabla buyUltimate con la ultima compra
	
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
    CREATE TEMPORARY TABLE tmp.ticketLot 
	SELECT vWarehouseFk warehouseFk, NULL available,
		s.itemFk, bu.buyFk
			FROM sale s
				LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
			WHERE s.ticketFk = vTicketFk 
			GROUP BY s.itemFk;
	
	CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped);
   
	DROP TEMPORARY TABLE IF EXISTS tmp.sale;
	CREATE TEMPORARY TABLE tmp.sale
				(PRIMARY KEY (saleFk)) ENGINE = MEMORY
			  SELECT id saleFk, vWarehouseFk warehouseFk
                  FROM sale s
                  WHERE s.ticketFk = vTicketFk;  
                                    
	CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios
    
	IF vLanded IS NULL THEN

		CALL zoneGetLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk);
        
        UPDATE vn2008.Tickets t
			SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) 
			WHERE Id_Ticket = vTicketFk;
            
		DROP TEMPORARY TABLE tmp.zoneGetLanded;

    END IF;
    
	DROP TEMPORARY TABLE tmp.buyUltimate;
    DROP TEMPORARY TABLE tmp.ticketComponentPrice;
    DROP TEMPORARY TABLE tmp.ticketComponent;
    DROP TEMPORARY TABLE tmp.sale;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_recalcComponentsForcePrice` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_recalcComponentsForcePrice`(IN vTicketFk BIGINT, vIsTicketEditable BOOLEAN )
proc: BEGIN

/**
 * Este procedimiento trata de "rebionizar" un ticket, 
 * eliminando los componentes existentes e insertandolos de nuevo
 *
 * @param vTicketFk Id del ticket
 * @return tmp.buyUltimate
 */
	DECLARE vShipped DATE;
	DECLARE vWarehouseFk SMALLINT;
    DECLARE vAgencyModeFk INT;
    DECLARE vAddressFk INT;
    DECLARE vLanded DATE;
    DECLARE vZoneFk INTEGER;
    
    IF vIsTicketEditable IS NULL THEN
		SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk
			INTO vIsTicketEditable, vZoneFk
			FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket
			WHERE id = vTicketFk;
	END IF;
	SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed
			INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded
		FROM ticket
		WHERE id = vTicketFk;
		
    CALL zoneGetShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk);
	
    CALL vn.buyUltimate (vWarehouseFk, vShipped);  -- rellena la tabla buyUltimate con la ultima compra
	
    DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot;
    CREATE TEMPORARY TABLE tmp.ticketLot 
	SELECT vWarehouseFk warehouseFk, NULL available,
		s.itemFk, bu.buyFk
			FROM sale s
				LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
			WHERE s.ticketFk = vTicketFk 
			GROUP BY s.itemFk;
	
	CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped);
   
	DROP TEMPORARY TABLE IF EXISTS tmp.sale;
	CREATE TEMPORARY TABLE tmp.sale
				(PRIMARY KEY (saleFk)) ENGINE = MEMORY
			  SELECT id saleFk, vWarehouseFk warehouseFk
                  FROM sale s
                  WHERE s.ticketFk = vTicketFk;  
                                    
	CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios
    
	IF vLanded IS NULL THEN

		CALL zoneGetLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk);
        
        UPDATE vn2008.Tickets t
			SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) 
			WHERE Id_Ticket = vTicketFk;
            
		DROP TEMPORARY TABLE tmp.zoneGetLanded;

    END IF;
    
	DROP TEMPORARY TABLE tmp.buyUltimate;
    DROP TEMPORARY TABLE tmp.ticketComponentPrice;
    DROP TEMPORARY TABLE tmp.ticketComponent;
    DROP TEMPORARY TABLE tmp.sale;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `timeBusiness_calculate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `timeBusiness_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME)
BEGIN

/**
 * Horas que debe trabajar un empleado según contrato y día. 
 * @param vDatedFrom workerTimeControl
 * @param vDatedTo workerTimeControl
 * @table tmp.user(userFk)
 * @return tmp.timeBusinessCalculate
 */
  	DECLARE vHoursFullTime  INT DEFAULT 40;
    
	DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate;
	DROP TEMPORARY TABLE IF EXISTS tmp.businessFullTime;
	
    CALL rangeDateInfo(vDatedFrom, vDatedTo);
    
	CREATE TEMPORARY TABLE tmp.timeBusinessCalculate
	SELECT dated, 
		    businessFk,
			userFk, 
			departmentFk, 
			hourStart,
			hourEnd,
            timeWorkSeconds,
            SEC_TO_TIME(timeWorkSeconds) timeWorkSexagesimal,
            timeWorkSeconds / 3600 timeWorkDecimal,
            timeWorkSeconds timeBusinessSeconds,
            SEC_TO_TIME(timeWorkSeconds) timeBusinessSexagesimal,
            timeWorkSeconds / 3600 timeBusinessDecimal,
			type,
            permissionrate,
			hoursWeek
		FROM(SELECT rd.dated,
					b.business_id businessFk,
                    w.userFk,
					bl.department_id departmentFk,  
					IF(cl.hours_week = vHoursFullTime, NULL, GROUP_CONCAT(DISTINCT LEFT(j.start,2) ORDER BY j.start ASC SEPARATOR '-')) hourStart , 
					IF(cl.hours_week = vHoursFullTime, NULL, GROUP_CONCAT(DISTINCT LEFT(j.end,2) ORDER BY j.end ASC SEPARATOR '-')) hourEnd,
					IF(cl.hours_week = vHoursFullTime, 0, IFNULL(SUM(TIME_TO_SEC(j.end)) - SUM(TIME_TO_SEC(j.start)),0)) timeWorkSeconds,
                    cs.type,
					cs.permissionRate,
					cl.hours_week hoursWeek
				FROM tmp.rangeDate rd
					LEFT JOIN postgresql.business b ON rd.dated BETWEEN b.date_start AND  ifnull(b.date_end, vDatedTo )
					LEFT JOIN postgresql.profile AS pr ON b.client_id = pr.profile_id
					LEFT JOIN postgresql.person AS p ON pr.person_id = p.person_id
					LEFT JOIN vn.worker AS w ON p.id_trabajador = w.id
                    JOIN tmp.`user` u ON u.userFK = w.userFK
					JOIN postgresql.business_labour AS bl ON b.business_id = bl.business_id
					LEFT JOIN postgresql.business_labour_payroll AS bp ON bl.business_id = bp.business_id
					LEFT JOIN postgresql.professional_category AS pc ON bl.professional_category_id = pc.professional_category_id
					LEFT JOIN postgresql.workcenter AS wc ON bl.workcenter_id = wc.workcenter_id
					LEFT JOIN postgresql.calendar_labour_type AS cl ON bl.calendar_labour_type_id = cl.calendar_labour_type_id
					LEFT JOIN postgresql.journey AS j ON j.business_id = b.business_id and j.day_id=WEEKDAY(rd.dated)+1
					LEFT JOIN postgresql.calendar_employee ce ON ce.business_id=b.business_id and  ce.date = rd.dated 
					LEFT JOIN postgresql.calendar_state cs ON cs.calendar_state_id = ce.calendar_state_id
				WHERE rd.dated BETWEEN vDatedFrom AND vDatedTo
				GROUP BY w.userFk,dated 
			)sub;
  
            
	UPDATE tmp.timeBusinessCalculate t
		SET t.timeWorkSeconds = vHoursFullTime / 5 * 3600,
			t.timeWorkSexagesimal = SEC_TO_TIME( vHoursFullTime / 5 * 3600), 
			t.timeWorkDecimal =  vHoursFullTime / 5, 
			t.timeBusinessSeconds = vHoursFullTime / 5 * 3600,
			t.timeBusinessSexagesimal = SEC_TO_TIME( vHoursFullTime / 5 * 3600), 
			t.timeBusinessDecimal = vHoursFullTime / 5
		WHERE DAYOFWEEK(t.dated) IN(2,3,4,5,6) AND hoursWeek = vHoursFullTime ;
  
    UPDATE tmp.timeBusinessCalculate t     
		SET t.timeWorkSeconds = t.timeWorkSeconds - (t.timeWorkSeconds * permissionrate)  ,
			t.timeWorkSexagesimal = SEC_TO_TIME(t.timeWorkSeconds - (t.timeWorkSeconds * permissionrate)), 
			t.timeWorkDecimal = t.timeWorkDecimal - (t.timeWorkDecimal * permissionrate)
		WHERE permissionrate <> 0;      
       
	UPDATE tmp.timeBusinessCalculate t     
		JOIN postgresql.calendar_labour cl ON cl.day = t.dated
		JOIN postgresql.business_labour bl ON bl.business_id = t.businessFk AND bl.workcenter_id = cl.workcenter_id 
		SET t.timeWorkSeconds = 0,
			t.timeWorkSexagesimal = 0, 
			t.timeWorkDecimal = 0,
            t.permissionrate = 1,
            t.type = 'Festivo'
		WHERE t.type IS NULL;

DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `timeBusiness_calculateAll` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `timeBusiness_calculateAll`(vDatedFrom DATETIME, vDatedTo DATETIME)
BEGIN

/**
 * @param vDatedFrom workerTimeControl
 * @param vDatedTo workerTimeControl
 */

	DROP TEMPORARY TABLE IF EXISTS tmp.`user`;

	CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` 
		SELECT userFk
			FROM vn.worker w
				JOIN vn.`user` u ON u.id = w.userFk
			WHERE userFk IS NOT NULL AND u.active = TRUE;
        
	CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo);

	DROP TEMPORARY TABLE tmp.`user`;
 
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `timeBusiness_calculateByDepartment` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `timeBusiness_calculateByDepartment`(vDepartmentFk INT, vDatedFrom DATETIME, vDatedTo DATETIME)
BEGIN

/**
 * @param vDepartmentFk 
 * @param vDatedFrom workerTimeControl
 * @param vDatedTo workerTimeControl
 */
  
  DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
  
  CREATE TEMPORARY TABLE tmp.`user`
	SELECT DISTINCT w.userFk
		FROM postgresql.business AS b 
			LEFT JOIN postgresql.profile AS pr ON pr.profile_id = b.client_id
			LEFT JOIN postgresql.person AS p ON p.person_id = pr.person_id
			LEFT JOIN postgresql.business_labour AS bl ON b.business_id = bl.business_id
			LEFT JOIN vn.worker AS w ON p.id_trabajador = w.id
			LEFT JOIN vn.department AS d ON bl.department_id = d.id
		WHERE ((b.date_start BETWEEN vDatedFrom  AND vDatedTo OR b.date_end  BETWEEN vDatedFrom AND vDatedTo) OR 
			   (b.date_end IS NULL AND b.date_start <= vDatedTo) OR 
			   (b.date_start <= vDatedFrom AND b.date_end >= vDatedTo)
              ) AND bl.department_id = vDepartmentFk
		ORDER BY b.date_end DESC;
        
  CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo);
  
  DROP TEMPORARY TABLE tmp.`user`;

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

/**
 * @param vUserFk 
 * @param vDatedFrom workerTimeControl
 * @param vDatedTo workerTimeControl
 */
  
  DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
  
  CREATE TEMPORARY TABLE tmp.`user`
	SELECT id userFk
		FROM user 
        WHERE id = vUserFk; 
  CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo);
  
  DROP TEMPORARY TABLE tmp.`user`;

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

/**
 * @param vWorkerFk
 * @param vDatedFrom workerTimeControl
 * @param vDatedTo workerTimeControl
 */
  
  DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
  
  CREATE TEMPORARY TABLE tmp.`user`
	SELECT u.id userFk
		FROM vn.user u
			JOIN vn.worker w ON w.userFk = u.id
        WHERE w.id = vWorkerFk;
        
  CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo);
  
  DROP TEMPORARY TABLE tmp.`user`;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `timeControl_calculate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `timeControl_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME)
BEGIN
	SET @vIsOdd := TRUE;
	SET @vUser := NULL;
	SET @vDated := NULL;	
 
	DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate;
	
	CREATE TEMPORARY TABLE tmp.timeControlCalculate
	  SELECT  userFk,
			  dated,
			  IF( timeWork >= 18000, @timeWork:=timeWork + 1200, @timeWork:=timeWork) timeWorkSeconds,
			  SEC_TO_TIME(@timeWork ) timeWorkSexagesimal,    
			  @timeWork / 3600 timeWorkDecimal 
			FROM (SELECT SUM(timeWork) timeWork, 
						 userFk, 
                         dated 
					FROM (SELECT IF(@vUser = wtc.userFk, @vUser :=@vUser, @vUser := wtc.userFk ),
								 IF(@vIsOdd, @vIsOdd := FALSE, @vIsOdd := TRUE ),
								 IF(direction='in', @vIsOdd := TRUE, @vIsOdd := @vIsOdd ),
								 IF(@vIsOdd, @vLastTimed:=UNIX_TIMESTAMP(timed),@vLastTimed:=@vLastTimed), 
								 IF(@vIsOdd, 0, UNIX_TIMESTAMP(timed)-@vLastTimed) timeWork,
								 IF(direction='in', @vDated := DATE(wtc.timed), @vDated :=@vDated) dated,
								 wtc.userFk,
								 wtc.timed timed,
								 direction
							FROM workerTimeControl wtc
								JOIN tmp.`user` w ON w.userFk = wtc.userFk
							WHERE wtc.timed BETWEEN vDatedFrom AND vDatedTo 
							ORDER BY userFk, timed
						 ) sub
					GROUP BY userFk, dated
					ORDER BY userFk, dated
				 )sub2;

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

/**
 * @param vDatedFrom workerTimeControl
 * @param vDatedTo workerTimeControl
 */

	DROP TEMPORARY TABLE IF EXISTS tmp.`user`;

	CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` 
		SELECT userFk
			FROM vn.worker w
				JOIN vn.`user` u ON u.id = w.userFk
			WHERE userFk IS NOT NULL;
        
	CALL vn.timeControl_calculate(vDatedFrom, vDatedTo);

	DROP TEMPORARY TABLE tmp.`user`;
 
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `timeControl_calculateByDepartment` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `timeControl_calculateByDepartment`(vDepartmentFk INT, vDatedFrom DATETIME, vDatedTo DATETIME)
BEGIN

/**
 * @param vDepartmentFk 
 * @param vDatedFrom workerTimeControl
 * @param vDatedTo workerTimeControl
 */
  
  DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
  
  CREATE TEMPORARY TABLE tmp.`user`
	SELECT DISTINCT w.userFk
		FROM postgresql.business AS b 
			LEFT JOIN postgresql.profile AS pr ON pr.profile_id = b.client_id
			LEFT JOIN postgresql.person AS p ON p.person_id = pr.person_id
			LEFT JOIN postgresql.business_labour AS bl ON b.business_id = bl.business_id
			LEFT JOIN vn.worker AS w ON p.id_trabajador = w.id
			LEFT JOIN vn.department AS d ON bl.department_id = d.id
		WHERE ((b.date_start BETWEEN vDatedFrom  AND vDatedTo OR b.date_end  BETWEEN vDatedFrom AND vDatedTo) OR 
			   (b.date_end IS NULL AND b.date_start <= vDatedTo) OR 
			   (b.date_start <= vDatedFrom AND b.date_end >= vDatedTo)
              ) AND bl.department_id = vDepartmentFk
		ORDER BY b.date_end DESC;
        
  CALL vn.timeControl_calculate(vDatedFrom, vDatedTo);
  
  DROP TEMPORARY TABLE tmp.`user`;

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

/**
 * @param vUserFk 
 * @param vDatedFrom workerTimeControl
 * @param vDatedTo workerTimeControl
 */
  
  DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
  
  CREATE TEMPORARY TABLE tmp.`user`
	SELECT id userFk
		FROM user 
        WHERE id = vUserFk; 
  CALL vn.timeControl_calculate(vDatedFrom, vDatedTo);
  
  DROP TEMPORARY TABLE tmp.`user`;

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

/**
 * @param vWorkerFk 
 * @param vDatedFrom workerTimeControl
 * @param vDatedTo workerTimeControl
 */
  
  DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
  
  CREATE TEMPORARY TABLE tmp.`user`
	SELECT u.id userFk
		FROM vn.user u
			JOIN vn.worker w ON w.userFk = u.id
        WHERE w.id = vWorkerFk;
        
  CALL vn.timeControl_calculate(vDatedFrom, vDatedTo);
  
  DROP TEMPORARY TABLE tmp.`user`;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `timeWorkerControl_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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `timeWorkerControl_check`(vUserFk INT, vDated DATE,vTabletFk VARCHAR(100))
proc: BEGIN
/**
 * deprecated call workerTimeControl_check
 */
CALL vn.workerTimeControl_check(vUserFk,vDated,vTabletFk);
	
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_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 `travel_weeklyClone` */;
/*!50003 SET @saved_cs_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_weeklyClone`(vSinceWeek INT, vToWeek INT)
BEGIN
	DECLARE vCounter INT;

	SET vCounter = vSinceWeek;
	vWeekLoop :LOOP
		INSERT IGNORE INTO travel (shipped, landed, warehouseOutFk, warehouseInFk, agencyFk, ref, cargoSupplierFk, kg) 
			SELECT @a := TIMESTAMPADD(DAY,vCounter * 7 - WEEKDAY(CURDATE()) - 1 + weekDay,CURDATE()),
					@a := TIMESTAMPADD(DAY,duration,@a), 
					warehouseOutFk, 
					warehouseInFk, 
					agencyModeFk, 
					ref, 
					cargoSupplierFk,
                    kg
				FROM travel_cloneWeekly;
		IF vCounter = vToWeek THEN
			LEAVE vWeekLoop;
		END IF;
        SET vCounter = vCounter + 1;
	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 `travel_weeklyClone__` */;
/*!50003 SET @saved_cs_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_weeklyClone__`(vSinceWeek INT, vToWeek INT)
BEGIN
	DECLARE vCounter INT;

	SET vCounter = vSinceWeek;
	vWeekLoop :LOOP
		INSERT IGNORE INTO travel (shipped, landed, warehouseOutFk, warehouseInFk, agencyFk, ref, cargoSupplierFk) 
			SELECT @a := TIMESTAMPADD(DAY,vCounter * 7 - WEEKDAY(CURDATE()) - 1 + weekDay,CURDATE()),
					@a := TIMESTAMPADD(DAY,duration,@a), 
					warehouseOutFk, 
					warehouseInFk, 
					agencyModeFk, 
					ref, 
					cargoSupplierFk  
				FROM travel_cloneWeekly;
		IF vCounter = vToWeek THEN
			LEAVE vWeekLoop;
		END IF;
        SET vCounter = vCounter + 1;
	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 `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, FALSE, vWhOrigin);
    CALL cache.visible_refresh(vCacheVisibleDestinyFk, FALSE, 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 worker(code, firstName, lastName, fi, userFk, bossFk) 
		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  = 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 `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, 
            d.department_id as departmentFk,
            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)
mainLabel:BEGIN

	IF vUserId = 14255 THEN
		LEAVE mainLabel;
    END IF;
	DELETE FROM account.account
		WHERE id = vUserId;

   	UPDATE account.user 
		SET role = 2
		WHERE id = vUserId;	
        
	DELETE FROM pbx.sip 
		WHERE user_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); */

	
	IF vUserFk = 0 THEN
		CALL vn.timeControl_calculateAll( vFromDate , CONCAT(REPLACE(vToDate, '00:00:00', ''), ' 23:59:59'));
	ELSE
		CALL vn.timeControl_calculateByUser( vUserFk, vFromDate , CONCAT(REPLACE(vToDate, '00:00:00', ''), ' 23:59:59'));
	END IF; 

	UPDATE workerJourney wj
		JOIN tmp.timeControlCalculate t ON wj.dated = t.dated AND wj.userFk = t.userFk
			SET wj.total = CAST(IF(t.timeWorkDecimal >= 5.33,t.timeWorkDecimal-0.33,t.timeWorkDecimal) AS DECIMAL (10,2)),
			wj.lunch = IF(t.timeWorkDecimal >= 5.33,0.33,0)
		WHERE wj.dated BETWEEN vFromDate AND vToDate
			AND wj.isPaid = FALSE
			AND wj.isUpdated = FALSE
			AND vUserFk IN (0,wj.userFk); 
            
	DROP TEMPORARY TABLE tmp.timeControlCalculate; 
			
 
        
	/********** 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;
     
    -- Elimina el precio de las horas extras para los contratos parciales.
    UPDATE vn.workerJourney wj
		JOIN postgresql.business_labour bl ON bl.business_id = wj.businessFk
        JOIN postgresql.calendar_labour_type clt ON clt.calendar_labour_type_id = bl.calendar_labour_type_id
        SET wj.priceExtraHour = 0
        WHERE clt.isPartial
			AND 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;*/
            
	 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
		JOIN postgresql.calendar_state cs ON cs.calendar_state_id = pce.calendar_state_id
			SET wj.permission = cs.permissionRate * wj.contractJourney, 
				wj.contractJourney = IF(cs.permissionRate = 1, 0, cs.permissionRate) * wj.contractJourney,
				wj.hollyday = wj.total - IF(cs.permissionRate = 1, 0, cs.permissionRate) * wj.contractJourney
		WHERE cs.permissionRate > 0 
			AND 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 `workerJourney_Replace` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `workerJourney_Replace`(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.8
    */
	
	DELETE FROM workerJourney
		WHERE dated BETWEEN vFromDate AND vToDate 
			AND IFNULL(vUserFk, userFk) = userFk;
                               
	IF vUserFk IS NULL THEN
		CALL vn.timeControl_calculateAll( vFromDate , CONCAT(REPLACE(vToDate, '00:00:00', ''), ' 23:59:59'));
		CALL vn.timeBusiness_calculateAll( vFromDate , CONCAT(REPLACE(vToDate, '00:00:00', ''), ' 23:59:59'));	
	ELSE
		CALL vn.timeControl_calculateByUser( vUserFk, vFromDate , CONCAT(REPLACE(vToDate, '00:00:00', ''), ' 23:59:59'));
        CALL vn.timeBusiness_calculateByUser( vUserFk, vFromDate , CONCAT(REPLACE(vToDate, '00:00:00', ''), ' 23:59:59'));
	END IF; 

	-- 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 tbc.userFk, tbc.dated, tbc.businessFk
			FROM tmp.timeBusinessCalculate  tbc;

	-- Se actualiza la cantidad total de horas prácticas, así como el tiempo de almuerzo remunerado, si corresponde
	UPDATE workerJourney wj
		JOIN tmp.timeControlCalculate t ON wj.dated = t.dated AND wj.userFk = t.userFk
			SET wj.total = CAST(IF(t.timeWorkDecimal >= 5.33,t.timeWorkDecimal-0.33,t.timeWorkDecimal) AS DECIMAL (10,2)),
				wj.lunch = IF(t.timeWorkDecimal >= 5.33,0.33,0)
		WHERE wj.dated BETWEEN vFromDate AND vToDate
			AND wj.isPaid = FALSE
			AND wj.isUpdated = FALSE
			AND IFNULL(vUserFk, wj.userFk) = wj.userFk; 
            
	DROP TEMPORARY TABLE tmp.timeControlCalculate; 
  
	/********** 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  IFNULL(vUserFk, userFk) = 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  IFNULL(vUserFk, userFk) = 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  IFNULL(vUserFk, userFk) = 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;


	-- Precios de hora ordinaria, Extras, Vacaciones y Nocturnas 
	-- Falta importe pactado en el procedimiento ¿?
	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
		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.priceOrdinaryHour = @priceOrdinaryHour := FORMAT((12 * blp.importepactado) / (52 * pclt.hours_week),2),
			 wj.priceHollydayHour = @priceOrdinaryHour * conv.hollidayInc,
			 wj.priceNocturnHour = @priceOrdinaryHour * conv.nightInc,
             wj.priceExtraHour = @priceOrdinaryHour * conv.extraInc
		WHERE wj.dated BETWEEN vFromDate AND vToDate
            AND IFNULL(vUserFk, userFk) = userFk
            AND wj.isPaid = FALSE  
            AND isUpdated = FALSE;

	--  Horas téoricas  bajas, vacaciones y festivos personales
	UPDATE vn.workerJourney wj
		JOIN tmp.timeBusinessCalculate b  ON b.dated = wj.dated AND b.userFk = wj.userFk 
			SET wj.permission = b.timeBusinessDecimal * b.permissionRate, 
				wj.contractJourney = b.timeWorkDecimal
		WHERE wj.dated BETWEEN vFromDate AND vToDate
			AND IFNULL(vUserFk, wj.userFk) = wj.userFk
			AND wj.isPaid = FALSE 
			AND wj.isUpdated = FALSE;	

	 UPDATE vn.workerJourney wj
		JOIN tmp.timeBusinessCalculate b  ON b.dated = wj.dated AND b.userFk = wj.userFk 
			SET wj.hollyday = wj.total - b.timeWorkDecimal
		WHERE wj.dated BETWEEN vFromDate AND vToDate
			AND IFNULL(vUserFk, wj.userFk) = wj.userFk
			AND wj.isPaid = FALSE 
			AND wj.isUpdated = FALSE
            AND b.permissionRate > 0 ;	
            
	-- Horas extras
    UPDATE workerJourney 
		SET extra =  lunch + total - contractJourney  
        WHERE dated BETWEEN vFromDate AND vToDate
			AND IFNULL(vUserFk, userFk) = 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 `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, FALSE, vWarehouseFk);
        
	CALL vn.workerTimeControlSOWP(vUserFk , vDated);*/
    
    CALL vn.workerTimeControl_add(vUserFk,vWarehouseFk,NOW(),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 `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 `workerTimeControlPinGenerate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControlPinGenerate`(
	vWorkerFk INT)
BEGIN
/**
 * Create new pin for workerFk or new pin for all workers if vWorkerFk 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 `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 `workerTimeControlSetOrder_by_User_and_dateRange` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_by_User_and_dateRange`(vUserFk INT, vStarted DATE, vFinished DATE)
BEGIN

	SET @order := 0;
    SET @day := '2000-01-01';

	UPDATE vn.workerTimeControl w
		SET w.`order` = @order := IF(@day = @day := date(timed), @order, 0) + 1
        WHERE w.userFk = vUserFk
        AND w.timed BETWEEN vStarted AND util.dayend(vFinished)
        ORDER BY w.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 `workerTimeControl_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 `workerTimeControl_add`(IN vUserFk INT, IN vWarehouseFk INT, IN vTimed DATETIME, IN vIsManual BOOL)
BEGIN
	
	
	SELECT workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_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 `workerTimeControl_add__`(IN vUserFk INT, IN vWarehouseFk INT, IN vTimed DATETIME, IN vIsManual BOOL)
BEGIN

	DECLARE vDirection VARCHAR(6);
	DECLARE vLastIn DATETIME;
	DECLARE vDayStayMax INT;
    DECLARE vHasDirectionOut INT;

    SELECT dayStayMax INTO vDayStayMax
		FROM vn.workerTimeControlParams;
        
    SELECT vn.timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection;

	IF vDirection = 'out' THEN
	
		SELECT MAX(timed) INTO vLastIn
			FROM vn.workerTimeControl 
			WHERE userFk = vUserFk 
				AND direction = 'in'
				AND timed < vTimed;
	
		UPDATE  vn.workerTimeControl wtc
			SET wtc.direction = 'middle'
			WHERE userFk = vUserFk
				AND direction = 'out'
				AND timed BETWEEN vLastIn AND vTimed;
	
	ELSE IF vDirection = 'in' THEN
			
            SELECT COUNT(*) INTO vHasDirectionOut 
				FROM vn.workerTimeControl wtc
				WHERE userFk = vUserFk 
					AND direction = 'out'
					AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);          

			UPDATE  vn.workerTimeControl wtc
				SET wtc.direction = IF (vHasDirectionOut,'middle','out')
				WHERE userFk = vUserFk
					AND direction = 'in'
					AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);  
           
		 END IF;
     END IF;
	
	INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual)
		VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual);

    CALL vn.workerTimeControlSOWP(vUserFk, vTimed);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_check` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_check`(vUserFk INT, vDated DATE,vTabletFk VARCHAR(100))
proc: BEGIN
/**
 * Verifica si el empleado puede fichar en el momento actual, si puede fichar llama a vn.workerTimeControlAdd
 *
 * @param vUserFk Identificador del trabajador
 * @return Retorna si encuentra un problema 'odd','maxTimeWork','breakDay','breakWeek' ;
 *	En caso de tener algun problema retorna el primero que encuentra
 */
    DECLARE vLastIn DATETIME ;
    DECLARE vLastOut DATETIME ;
    DECLARE vDayWorkMax INT;
    DECLARE vDayBreak INT;
    DECLARE vWeekBreak INT ;
	DECLARE vWeekScope INT;
    DECLARE vDayStayMax INT;
    DECLARE vProblem VARCHAR(20) DEFAULT NULL;
    DECLARE vTimedWorked INT;
    DECLARE vCalendarStateType VARCHAR(20) DEFAULT NULL;
    DECLARE vDepartmentFk INT;
    DECLARE vTo VARCHAR(50) DEFAULT NULL;
    DECLARE vUserName VARCHAR(50) DEFAULT NULL;
    DECLARE vBody VARCHAR(255) DEFAULT NULL;
	  
	SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax 
		INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax
		FROM vn.workerTimeControlParams;

    SELECT MAX(timed) INTO vLastIn
		FROM vn.workerTimeControl 
        WHERE userFk = vUserFk 
			AND direction = 'in';
        
    SELECT MAX(timed) INTO vLastOut
		FROM vn.workerTimeControl 
        WHERE userFk = vUserFk 
			AND direction = 'out'; 
	
    SELECT email INTO vTo
		FROM vn.worker w
        WHERE w.id = (SELECT bossFk FROM vn.worker WHERE id = vUserFk);
        
	SELECT CONCAT(firstName,' ',lastName) INTO vUserName
		FROM vn.worker w
        WHERE w.id = vUserFk;
	
 
   IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA
       
       -- VERIFICAR DESCANSO DIARIO 
		IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN 
            SELECT "Descansos 12 h" AS problem;
            -- ENVIAMOS CORREO AL BOSSFK
				SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody;
				CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody);
            LEAVE proc;
        END IF;   
        
        -- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ
		IF (SELECT MOD(COUNT(*),2) -- <>0 							
				FROM vn.workerTimeControl 
				WHERE userFk = vUserFk
					AND timed >= vLastIn
			) THEN				
			SELECT "Dias con fichadas impares" AS problem;
            -- ENVIAMOS CORREO AL BOSSFK
				SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody;
				CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody);
            LEAVE proc;	  
		END IF;
        
        -- VERIFICAR VACACIONES
        SELECT cs.type INTO vCalendarStateType
			FROM postgresql.calendar_employee ce
				JOIN postgresql.business b USING(business_id)
				JOIN postgresql.profile pr ON pr.profile_id = b.client_id
				JOIN postgresql.person p ON p.person_id = pr.person_id
				JOIN postgresql.calendar_state cs USING(calendar_state_id)
				JOIN vn.worker w ON w.id = p.id_trabajador
			WHERE ce.date = CURDATE() 
				AND cs.isAllowedToWork = FALSE 
				AND w.userFk = vUserFk
			LIMIT 1;
        
         IF(LENGTH(vCalendarStateType)) THEN
			SELECT vCalendarStateType AS problem;
            -- ENVIAMOS CORREO AL BOSSFK
				SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody;
				CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody);
            LEAVE proc;	
             
         END IF;
        
        
        -- VERIFICAR CONTRATO EN VIGOR
		 IF (SELECT COUNT(*)
			FROM postgresql.business b
				JOIN postgresql.profile pr ON pr.profile_id = b.client_id
				JOIN postgresql.person p ON p.person_id = pr.person_id
				JOIN vn.worker w ON w.id = p.id_trabajador
			WHERE w.userFk = vUserFk
				AND b.date_start <= vDated
				AND IFNULL(b.date_end,vDated) >= vDated
				) = 0 THEN
                SELECT "No hay un contrato en vigor" AS problem;
                -- ENVIAMOS CORREO AL BOSSFK
				SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody;
				CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody);
				LEAVE proc;	
                 
			END IF;

	   -- VERIFICAR DESCANSO SEMANAL
		SET @vHasBreakWeek:= FALSE;
		SET @vLastTimed:= UNIX_TIMESTAMP((NOW() - INTERVAL vWeekScope SECOND)); 
        
		DROP TEMPORARY TABLE IF EXISTS tmp.trash;
		CREATE TEMPORARY TABLE tmp.trash
        SELECT  IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias,
				@vLastTimed:= UNIX_TIMESTAMP(timed)
			FROM workerTimeControl 
			WHERE timed>= (NOW() - INTERVAL vWeekScope SECOND)
				AND userFk= vUserFk
				AND direction IN ('in','out')
			ORDER BY timed ASC;   
            
		IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA     
			SELECT "Descansos 36 h" AS problem;
            -- ENVIAMOS CORREO AL BOSSFK
				SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody;
				CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody);
            LEAVE proc;
		END IF;
		
        DROP TEMPORARY TABLE tmp.trash;    
    
    ELSE  -- DIA ACTUAL   
		
		-- VERIFICA QUE EL TIEMPO EFECTIVO NO SUPERE EL MÁXIMO
		SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) -  IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(NOW()), 0) INTO vTimedWorked 
			FROM vn.workerTimeControl wtc
			WHERE userFk = vUserFk 
				AND timed >= vLastIn
			ORDER BY timed;

        IF  vTimedWorked > vDayWorkMax THEN 
            SELECT "Jornadas" AS problem;
            -- ENVIAMOS CORREO AL BOSSFK
				SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Jornadas") INTO vBody;
				CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody);
            LEAVE proc;
		END IF;

	END IF;
    
     -- VERIFICAR DEPARTAMENTO
		IF vTabletFk IS NOT NULL  THEN
			SELECT wtcu.departmentFk INTO vDepartmentFk
				FROM vn.workerTimeControlUserInfo wtcu
				WHERE wtcu.userFk = vUserFk;
			IF (SELECT COUNT(td.tabletFk)
						FROM vn.tabletDepartment td
						WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk
					) = 0 THEN
					SELECT "No perteneces a este departamento." AS problem;
                    -- ENVIAMOS CORREO AL BOSSFK
					SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody;
					CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody);
					LEAVE proc;	
			END IF;
		END IF;
	
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_remove` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_remove`(IN vUserFk INT, IN vTimed DATETIME)
BEGIN

	DECLARE vDirectionRemove VARCHAR(6);
	DECLARE vDirectionPrevious VARCHAR(6);
    DECLARE vTimedPrevious DATETIME;

	SELECT direction INTO vDirectionRemove 
		FROM vn.workerTimeControl 
		WHERE userFk = vUserFk 
			AND timed = vTimed ;

	IF vDirectionRemove = 'out' THEN
	
		 SELECT timed, direction INTO vTimedPrevious, vDirectionPrevious
			FROM vn.workerTimeControl 
			WHERE userFk =  vUserFk 
				AND timed < vTimed
			ORDER BY timed DESC
			LIMIT 1;       
                
         IF  vDirectionPrevious = "middle" THEN
			UPDATE vn.workerTimeControl 
				SET direction = "out"
                WHERE userFk = vUserFk
					AND timed = vTimedPrevious;
         END IF;
   
	ELSE IF vDirectionRemove = 'in' THEN

			UPDATE vn.workerTimeControl 
				SET direction = "in"
				WHERE userFk = vUserFk
					AND timed > vTimed
				ORDER BY timed ASC
				LIMIT 1; 
          END IF;
			
	END IF;
	
	DELETE FROM vn.workerTimeControl
		WHERE userFk =  vUserFk 
			AND timed = vTimed;
            
    CALL vn.workerTimeControlSOWP(vUserFk, vTimed);
 
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_repair` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_repair`()
proc: BEGIN
/**
 * Corrige las fichadas
 *
 */

/*1- poner todos a middle*/
UPDATE vn.workerTimeControl SET direction = 'middle';

/*2- poner los out*/
UPDATE vn.workerTimeControl wtc 
	JOIN 
		(SELECT userFk,MAX(timed) maxTimed FROM
				(SELECT id, userFk, timed, date(timed) dated
					FROM vn.workerTimeControl 
				) sub 
		GROUP BY userFk,dated
		)sub
	SET direction = "out"
	WHERE   wtc.userFk = sub.userFk 
		AND wtc.timed =  sub.maxTimed;
        
 /*3- poner los in*/       
UPDATE vn.workerTimeControl wtc 
	JOIN 
		(SELECT userFk,MIN(timed) maxTimed FROM
				(SELECT id, userFk, timed, date(timed) dated
					FROM vn.workerTimeControl 
				) sub 
		GROUP BY userFk,dated
		)sub
	SET direction = "in"
	WHERE   wtc.userFk = sub.userFk 
		AND wtc.timed =  sub.maxTimed ;   
	
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerWeekControl` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `workerWeekControl`(vUserFk INT, vDated DATE, vTabletFk VARCHAR(100))
BEGIN

/* Devuelve la cantidad de descansos de 12h y de 36 horas que ha disfrutado el trabajador
*  en la semana inmediatamente anterior a la fecha que pasa como parámetro.
*
*	UPDATED PAK 2019/09/02
*	PENDING REVIEW
*/

DECLARE vDescansos12h INT;
DECLARE vDescansos36h INT;
DECLARE vJornadas INT;
DECLARE vImpares INT;
DECLARE vHasSignedToday BOOLEAN;
DECLARE v12hoursInMinutes INT DEFAULT 719;
DECLARE v36hoursInMinutes INT DEFAULT 2159;
DECLARE vCantWork VARCHAR(50) DEFAULT '';
DECLARE vDepartmentFk INT;
DECLARE isEnabled BOOLEAN DEFAULT TRUE;


SELECT COUNT(*) INTO vHasSignedToday 
	FROM vn.workerTimeControl WHERE timed >= vDated AND userFk = vUserFk;

SET @day := 0;
SET @lastTimed := NOW();

SELECT SUM(IF(interval_in_minutes >= v12hoursInMinutes,1,0)),  SUM(FLOOR(interval_in_minutes/ v36hoursInMinutes)) , SUM(jornadas)
	INTO vDescansos12h, vDescansos36h, vJornadas
	FROM
    (
	SELECT fichada_anterior, fichada_actual, interval_in_minutes, jornadas
		FROM
			(
			SELECT  @lastTimed fichada_anterior, 
					timed,
					CAST(time_to_sec(timediff(timed,@lastTimed )) / 60 AS UNSIGNED) as interval_in_minutes,
                    IF(day(timed) != @day, 1, 0) as  jornadas,
					@day := day(timed) dia_del_mes,
					@lastTimed := timed fichada_actual                    
				FROM
				(
					SELECT day(timed) as dayNumber, dayname(timed) as dayName, timed
					FROM 
						(SELECT TIMESTAMPADD(DAY, -11, NOW()) as timed, vUserFk as userFk -- Fichada virtual para los en los que no se ha trabajado la semana anterior
							UNION ALL
						 SELECT timed, userFk
							FROM vn.workerTimeControl wtc
							WHERE userFk = vUserFk
								AND timed >= TIMESTAMPADD(DAY, -10,vDated)
                            UNION ALL
						SELECT IF(vHasSignedToday, '2000-01-01 00:00', NOW()) as timed, vUserFk         
						) sub4
					ORDER BY timed
				) sub
			
			) sub2
		WHERE fichada_actual >= TIMESTAMPADD(WEEK, -1, vDated)
	) sub3		;

SELECT IFNULL(SUM(impar),0) into vImpares
FROM (
	SELECT 	day(timed) as dayNumber, 
			count(*) mod 2 as impar
		FROM vn.workerTimeControl wtc
		WHERE userFk = vUserFk
			AND timed >= TIMESTAMPADD(WEEK, -1,vDated) AND timed < vDated
		GROUP BY dayNumber
	) sub;

-- Vacaciones    
SELECT cs.type INTO vCantWork
	FROM postgresql.calendar_employee ce
		JOIN postgresql.business b USING(business_id)
		JOIN postgresql.profile pr ON pr.profile_id = b.client_id
		JOIN postgresql.person p ON p.person_id = pr.person_id
		JOIN postgresql.calendar_state cs USING(calendar_state_id)
        JOIN vn.worker w ON w.id = p.id_trabajador
	WHERE ce.date = CURDATE() 
		AND cs.isAllowedToWork = FALSE 
        AND w.userFk = vUserFk
	LIMIT 1;
    
-- Contrato en vigor
SELECT IF(COUNT(*),vCantWork,'Sin contrato') INTO vCantWork
	FROM postgresql.business b
		JOIN postgresql.profile pr ON pr.profile_id = b.client_id
		JOIN postgresql.person p ON p.person_id = pr.person_id
        JOIN vn.worker w ON w.id = p.id_trabajador
	WHERE w.userFk = vUserFk
		AND b.date_start <= vDated
        AND IFNULL(b.date_end,vDated) >= vDated;
        
-- Departamento si vTabletFk es 0 no hacemos comprobacion (Madrid y Vilassar)
IF vTabletFk <> '0'  THEN
-- 1 Obtener el departamento del usuario
		SELECT wtcu.departmentFk INTO vDepartmentFk
			FROM vn.workerTimeControlUserInfo wtcu
            WHERE wtcu.userFk = vUserFk;
-- 2 Comprobar si la tablet pertenece al departamento		
        SELECT COUNT(td.tabletFk) INTO isEnabled
			FROM vn.tabletDepartment td
            WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk;
      
END IF;
	

   
IF vJornadas IS NOT NULL THEN
    
		SELECT 'Jornadas' as Item, vJornadas as Cantidad, 'Correcto' AS Análisis

		UNION ALL

		SELECT 'Descansos 12 h' as Item, vDescansos12h as Cantidad, IF(vDescansos12h >= vJornadas, 'Correcto','Error: 1 por jornada') as Análisis

		UNION ALL

		SELECT 'Descansos 36 h' as Item, vDescansos36h as Cantidad, IF(vDescansos36h / 2 >= FLOOR(vJornadas/10), 'Correcto','Error: mínimo 2 cada 14 dias') as Análisis

		UNION ALL

		SELECT 'Dias con fichadas impares' as Item, vImpares as Cantidad, IF(vImpares = 0, 'Correcto','Error') as Análisis
        
        UNION ALL

		SELECT 	IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, 
				'' as Cantidad, 
                IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis
                
		UNION ALL

		SELECT 'El fichador no pertenece a tu departamento.' as Item, '' as Cantidad, IF(isEnabled, 'Correcto','Error') as Análisis
                
		;

ELSE


		SELECT 'Jornadas' as Item, vJornadas as Cantidad, 'Correcto' AS Análisis

		UNION ALL

		SELECT 'Descansos 12 h' as Item, vDescansos12h as Cantidad, 'Correcto'  as Análisis

		UNION ALL

		SELECT 'Descansos 36 h' as Item, vDescansos36h as Cantidad, 'Correcto'  as Análisis

		UNION ALL

		SELECT 'Dias con fichadas impares' as Item, vImpares as Cantidad, 'Correcto'  as Análisis
        
        UNION ALL

		SELECT 	IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, 
				'' as Cantidad, IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis
                
		UNION ALL

		SELECT 'El fichador no pertenece a tu departamento.' as Item, '' as Cantidad, IF(isEnabled, 'Correcto','Error') as Análisis
		;

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

/*
*	Muestra una tabla con los 7 dias inmediatamente anteriores a la fecha proporcionada
*   y las fichadas de cada dia, en columnas por dia
*
*/

CALL vn.workerTimeControlSetOrder_by_User_and_dateRange(vUserFk,TIMESTAMPADD(DAY,-8,vDated),vDated);

DROP TEMPORARY TABLE IF EXISTS tmp.workerWeekTiming;
CREATE TEMPORARY TABLE tmp.workerWeekTiming
SELECT  	orden `orden`,
			max(hace7dias) 7_dias_antes, 
			max(hace6dias) 6_dias_antes,
			max(hace5dias) 5_dias_antes,
			max(hace4dias) 4_dias_antes,
			max(hace3dias) 3_dias_antes,
			max(antesdeayer) 2_dias_antes,
			max(ayer) 1_dia_antes,
			max(hoy) mismo_dia
		FROM
		(
		SELECT  IF(dias = 7, fichada, '') as hace7dias,
				IF(dias = 6, fichada, '') as hace6dias,
				IF(dias = 5, fichada, '') as hace5dias,
				IF(dias = 4, fichada, '') as hace4dias,
				IF(dias = 3, fichada, '') as hace3dias,
				IF(dias = 2, fichada, '') as antesdeayer,
				IF(dias = 1, fichada, '') as ayer,
				IF(dias = 0, fichada, '') as hoy,
				orden

		FROM
			(
				SELECT `order` as orden, datediff(vDated, timed) as dias, date(timed) as fecha, TIME_FORMAT(timed,'%H:%i') as fichada
					FROM vn.workerTimeControl wtc
					WHERE userFk = vUserFk
						AND timed >= TIMESTAMPADD(DAY, -7, vDated)
			) sub
		)sub2
	GROUP BY orden
	;
    
DROP TEMPORARY TABLE IF EXISTS tmp.workerWeekTiming_Aux;
CREATE TEMPORARY TABLE tmp.workerWeekTiming_Aux
	SELECT * FROM tmp.workerWeekTiming;

INSERT INTO tmp.workerWeekTiming( 7_dias_antes,6_dias_antes,5_dias_antes,4_dias_antes,3_dias_antes,2_dias_antes,1_dia_antes,mismo_dia)
	VALUES('total','','','','','','','');
    
INSERT INTO tmp.workerWeekTiming( orden, 7_dias_antes,6_dias_antes,5_dias_antes,4_dias_antes,3_dias_antes,2_dias_antes,1_dia_antes, mismo_dia)
SELECT 	0, 
		IFNULL(DATE_FORMAT(SEC_TO_TIME(SUM(IF(orden MOD 2, - TIME_TO_SEC(7_dias_antes), TIME_TO_SEC(7_dias_antes)))),'%H:%i'),''),
		IFNULL(DATE_FORMAT(SEC_TO_TIME(SUM(IF(orden MOD 2, - TIME_TO_SEC(6_dias_antes), TIME_TO_SEC(6_dias_antes)))),'%H:%i'),''),
        IFNULL(DATE_FORMAT(SEC_TO_TIME(SUM(IF(orden MOD 2, - TIME_TO_SEC(5_dias_antes), TIME_TO_SEC(5_dias_antes)))),'%H:%i'),''),
        IFNULL(DATE_FORMAT(SEC_TO_TIME(SUM(IF(orden MOD 2, - TIME_TO_SEC(4_dias_antes), TIME_TO_SEC(4_dias_antes)))),'%H:%i'),''),
        IFNULL(DATE_FORMAT(SEC_TO_TIME(SUM(IF(orden MOD 2, - TIME_TO_SEC(3_dias_antes), TIME_TO_SEC(3_dias_antes)))),'%H:%i'),''),
        IFNULL(DATE_FORMAT(SEC_TO_TIME(SUM(IF(orden MOD 2, - TIME_TO_SEC(2_dias_antes), TIME_TO_SEC(2_dias_antes)))),'%H:%i'),''),
        IFNULL(DATE_FORMAT(SEC_TO_TIME(SUM(IF(orden MOD 2, - TIME_TO_SEC(1_dia_antes), TIME_TO_SEC(1_dia_antes)))),'%H:%i'),''),
        ''
	FROM tmp.workerWeekTiming_Aux;
    
INSERT INTO tmp.workerWeekTiming_Aux( orden, 1_dia_antes)
SELECT 	0, 	ROUND((
		IFNULL(TIME_TO_SEC(7_dias_antes),0) +
		IFNULL(TIME_TO_SEC(6_dias_antes),0) +
		IFNULL(TIME_TO_SEC(5_dias_antes),0) +
		IFNULL(TIME_TO_SEC(4_dias_antes),0) +
		IFNULL(TIME_TO_SEC(3_dias_antes),0) +
		IFNULL(TIME_TO_SEC(2_dias_antes),0) +
		IFNULL(TIME_TO_SEC(1_dia_antes),0)
			) / 3600,1)
	FROM tmp.workerWeekTiming
		WHERE orden = 0;	


INSERT INTO tmp.workerWeekTiming( 7_dias_antes,6_dias_antes,5_dias_antes,4_dias_antes,3_dias_antes,2_dias_antes,1_dia_antes,mismo_dia)
	SELECT '','','','','','',1_dia_antes,''
    FROM tmp.workerWeekTiming_Aux
		WHERE orden = 0;
		
SELECT 7_dias_antes,6_dias_antes,5_dias_antes,4_dias_antes,3_dias_antes,2_dias_antes,1_dia_antes,mismo_dia FROM tmp.workerWeekTiming;

DROP TEMPORARY TABLE tmp.workerWeekTiming;
DROP TEMPORARY TABLE tmp.workerWeekTiming_Aux;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `worker_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
-- eliminar no se usa
    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 `worker_getHierarchy` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET 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_getHierarchy`(vBoss INT)
BEGIN
    DECLARE EXIT HANDLER FOR 1062 BEGIN
		CALL util.throw('INFINITE_LOOP');
    END;

	DROP TEMPORARY TABLE IF EXISTS workerHierarchy;
	CREATE TEMPORARY TABLE workerHierarchy
		(PRIMARY KEY (workerFk))
		ENGINE = MEMORY
		SELECT vBoss AS workerFk;
            
	DROP TEMPORARY TABLE IF EXISTS tmp.workerHierarchyList;
	CREATE TEMPORARY TABLE tmp.workerHierarchyList
		(PRIMARY KEY (workerFk))
		ENGINE = MEMORY
		SELECT vBoss AS workerFk, 0 AS isChecked;


    WHILE (SELECT COUNT(*) FROM tmp.workerHierarchyList WHERE NOT isChecked) > 0 DO

	INSERT INTO tmp.workerHierarchyList
		SELECT w.id, 0 
			FROM worker w
				JOIN workerHierarchy wh ON wh.workerFk = w.bossFk;

	UPDATE tmp.workerHierarchyList whl
			JOIN workerHierarchy wh ON  wh.workerFk = whl.workerFk
		SET whl.isChecked = 1;

	TRUNCATE workerHierarchy;

	INSERT INTO workerHierarchy
		SELECT workerFk 
			FROM tmp.workerHierarchyList
			WHERE NOT isChecked;

    END WHILE;
    
    DROP TEMPORARY TABLE IF EXISTS workerHierarchy;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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_getProductionErrors` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `worker_getProductionErrors`(vDepartment VARCHAR(25), vStateCode VARCHAR(25) CHARSET utf8, vDatedFrom DATETIME, vDatedTo DATETIME)
BEGIN

DROP TEMPORARY TABLE IF EXISTS tmp.total;
    CREATE TEMPORARY TABLE tmp.total
        ENGINE = MEMORY
    SELECT tt.workerFk, Count(tt.ticketFk) AS CuentaDeId_Ticket
    FROM state s
    INNER JOIN ticketTracking  tt ON s.id = tt.stateFk
    INNER JOIN ticket t ON tt.ticketFk = t.id
    INNER JOIN worker w ON tt.workerFk = w.id
    WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND s.code = vStateCode
    GROUP BY tt.workerFk;

SELECT w.code, w.firstName, w.lastName, CAST(tmp.total.CuentaDeId_Ticket AS DECIMAL(10,0)) AS Totaltickets,
     CAST(sub.CuentaDeId_Ticket AS DECIMAL(10,0))  AS Fallos
fROM  tmp.total
     JOIN worker w ON w.id= tmp.total.workerFk
LEFT JOIN (    SELECT Count(s.ticketFk) AS CuentaDeId_Ticket, cd.workerFk
    FROM (claimDevelopment cd
    INNER JOIN ((sale s
    INNER JOIN claimBeginning cb ON s.id = cb.saleFk)
    INNER JOIN ticket t ON s.ticketFk = t.id) ON cd.claimFk = cb.claimFk)
    INNER JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id
    WHERE t.shipped BETwEEN vDatedFrom AND vDatedTo AND cr.description=vDepartment
    GROUP BY cd.workerFk)sub ON  tmp.total.workerFk = sub.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 `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  = 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 `xdiarioNextId`()
BEGIN
 DECLARE vNewAsien INT;
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
        ROLLBACK;
        RESIGNAL;
    END;

 START TRANSACTION;
    
    SELECT bookFk + 1 INTO vNewAsien FROM config FOR UPDATE;
    UPDATE config SET bookFk = 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 `zoneGeo_calcTree` */;
/*!50003 SET @saved_cs_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 `zoneGeo_calcTree`()
BEGIN
/**
 * Calculates the #path, #lft, #rgt, #sons and #depth columns of
 * the #zoneGeo table. To build the tree, it uses the #parentFk
 * column.
 */
	DECLARE vIndex INT DEFAULT 0;
	DECLARE vSons INT;

	DROP TEMPORARY TABLE IF EXISTS tNestedTree;
	CREATE TEMPORARY TABLE tNestedTree
		SELECT id, path, lft, rgt, depth, sons
			FROM zoneGeo LIMIT 0;

	SET max_sp_recursion_depth = 5;
	CALL zoneGeo_calcTreeRec(NULL, '/', 0, vIndex, vSons);
	SET max_sp_recursion_depth = 0;

	UPDATE zoneGeo z
		JOIN tNestedTree t ON t.id = z.id
		SET z.path = t.path,
			z.lft = t.lft,
			z.rgt = t.rgt,
			z.depth = t.depth,
			z.sons = t.sons;

	DROP TEMPORARY TABLE tNestedTree;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zoneGeo_calcTreeRec` */;
/*!50003 SET @saved_cs_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 `zoneGeo_calcTreeRec`(
	vSelf INT,
    vPath VARCHAR(255),
    vDepth INT,
    INOUT vIndex INT,
    OUT vSons INT
)
BEGIN
/**
 * Calculates and sets the #path, #lft, #rgt, #sons and #depth
 * columns for all children of the passed node. Once calculated
 * the last node rgt index and the number of sons are returned.
 * To update it's children, this procedure calls itself recursively
 * for each one.
 *
 * @vSelf The node identifier
 * @vPath The initial path
 * @vDepth The initial depth
 * @vIndex The initial lft index
 * @vSons The number of direct sons
 */
    DECLARE vChildFk INT;
    DECLARE vLft INT;
    DECLARE vMySons INT;
	DECLARE vDone BOOL;
	DECLARE vChildren CURSOR FOR
		SELECT id FROM zoneGeo
			WHERE (vSelf IS NULL AND parentFk IS NULL)
				OR (vSelf IS NOT NULL AND parentFk = vSelf);

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
    
    SET vSons = 0;

	OPEN vChildren;
	myLoop: LOOP
		SET vDone = FALSE;
		FETCH vChildren INTO vChildFk;

		IF vDone THEN
			LEAVE myLoop;
		END IF;
        
        SET vIndex = vIndex + 1;
        SET vLft = vIndex;
        SET vSons = vSons + 1;
    
		CALL zoneGeo_calcTreeRec(
			vChildFk,
            CONCAT(vPath, vChildFk, '/'),
            vDepth + 1,
            vIndex,
            vMySons
		);

        SET vIndex = vIndex + 1;

		INSERT INTO tNestedTree
			SET id = vChildFk,
				path = vPath,
				lft = vLft,
				rgt = vIndex,
				depth = vDepth,
				sons = vMySons;
	END LOOP;
	CLOSE vChildren;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zoneGeo_checkName` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = 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 `zoneGeo_checkName`(vName VARCHAR(255))
BEGIN
	IF vName = '' THEN
		SIGNAL SQLSTATE '45000'
			SET MESSAGE_TEXT = 'Column `name` cannot be empty';
	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 `zoneGeo_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 `zoneGeo_delete`(vSelf INT)
BEGIN
/**
 * Deletes a node from the #zoneGeo table. Also sets a mark
 * to force the tree recalculation.
 *
 * @vSelf The node identifier
 */
	DELETE FROM zoneGeo WHERE id = vSelf;
	UPDATE zoneGeoRecalc SET isChanged = 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 `zoneGeo_doCalc` */;
/*!50003 SET @saved_cs_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 `zoneGeo_doCalc`()
proc: BEGIN
/**
 * Recalculates the zones tree.
 */
    DECLARE vIsChanged BOOL;

	DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
    BEGIN
		DO RELEASE_LOCK('vn.zoneGeo_doCalc');
        RESIGNAL;
	END;

	IF !GET_LOCK('vn.zoneGeo_doCalc', 0) THEN
		LEAVE proc;
	END IF;

	SELECT isChanged INTO vIsChanged
		FROM zoneGeoRecalc;
        
	IF vIsChanged THEN
		UPDATE zoneGeoRecalc SET isChanged = FALSE;
        CALL vn.zoneGeo_calcTree;
	END IF;

	DO RELEASE_LOCK('vn.zoneGeo_doCalc');
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zoneGeo_setParent` */;
/*!50003 SET @saved_cs_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 `zoneGeo_setParent`(vSelf INT, vParentFk INT)
BEGIN
/**
 * Updates the parent of a node. Also sets a mark
 * to force the tree recalculation.
 *
 * @vSelf The node identifier
 * @vParentFk The new parent identifier
 */
	UPDATE zoneGeo SET parentFk = vParentFk
		WHERE id = vSelf;

	UPDATE zoneGeoRecalc SET isChanged = 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 `zoneGeo_throwNotEditable` */;
/*!50003 SET @saved_cs_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 `zoneGeo_throwNotEditable`()
BEGIN
	SIGNAL SQLSTATE '45000'
		SET MESSAGE_TEXT = 'Column `geoFk` cannot be modified';
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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
 */
 
	CALL zone_getAgency(vAddress,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 `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
*/
	CALL zone_getLanded(vShipped,vAddress,vAgencyMode,vWarehouse);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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
/**
 * OBSOLETO usar zone_getShippedWarehouse
 * 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
 */
	CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk);
    	
	SELECT * FROM tmp.zoneGetShipped WHERE warehouseFk <> vWarehouseFk;
    DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zoneGetShippedWarehouse` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShippedWarehouse`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT)
BEGIN
/**
 * Devuelve la mínima fecha de envío para cada warehouse
 * 
 * @param vLanded La fecha de recepcion
 * @param vAddressFk Id del consignatario
 * @param vAgencyModeFk Id de la agencia
 * @return tmp.zoneGetShipped
 */
	CALL zone_getShippedWarehouse(vLanded, vAddressFk, 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 `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 vGeoFk INT;
    
    SELECT p.geoFk INTO vGeoFk
		FROM address a 
			JOIN town t ON t.provinceFk = a.provinceFk
			JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode
	WHERE a.id = vAddress
	ORDER BY (a.city SOUNDS LIKE t.`name`) DESC
	LIMIT 1;

        
	SELECT * FROM (
		SELECT * FROM (
			SELECT am.id agencyModeFk, 
					am.name agencyMode, 
					am.description, 
					am.deliveryMethodFk,
					TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, 
					z.warehouseFk,
					zi.isIncluded,
                    z.id zoneFk
				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.`id` = vGeoFk
					AND delivered = vLanded
					AND z.warehouseFk = vWarehouse
					AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE)
				ORDER BY z.id, zgFather.depth DESC) t 
			GROUP BY zoneFk 
			HAVING isIncluded > 0) t
		GROUP BY agencyModeFk;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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 vGeoFk INT;
    
    SELECT p.geoFk INTO vGeoFk
		FROM address a 
			JOIN town t ON t.provinceFk = a.provinceFk
			JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode
	WHERE a.id = vAddress
	ORDER BY (a.city SOUNDS LIKE t.`name`) DESC
	LIMIT 1;

	SELECT * FROM (
		SELECT * FROM (
			SELECT am.id agencyModeFk, 
					am.name agencyMode, 
					am.description, 
					am.deliveryMethodFk,
					TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, 
					z.warehouseFk,
					zi.isIncluded,
                    z.id zoneFk
				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.`id` = vGeoFk
					AND delivered = vLanded
					AND z.warehouseFk = vWarehouse
					AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE)
				ORDER BY z.id, zgFather.depth DESC) t 
			GROUP BY zoneFk 
			HAVING isIncluded > 0) t
		GROUP BY agencyModeFk;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_getAgency` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getAgency`(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 vLanded Fecha de recogida
 * @select Listado de agencias disponibles
 */
 
	CALL zone_getFromGeo(address_getGeo(vAddress));
    CALL zone_getOptionsForLanding(vLanded);

	DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetAgency;
	CREATE TEMPORARY TABLE tmp.zoneGetAgency
			(INDEX (agencyModeFk)) ENGINE = MEMORY
		SELECT am.name agencyMode, 
			am.description,
            z.agencyModeFk, 
			am.deliveryMethodFk,
			TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped,
			TRUE isIncluded,
			zo.zoneFk
		FROM tmp.zoneOption zo
			JOIN zone z ON z.id = zo.zoneFk
            JOIN agencyMode am ON am.id = z.agencyModeFk
		GROUP BY agencyModeFk;
            
	DROP TEMPORARY TABLE
		tmp.zone,
        tmp.zoneOption;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_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  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getAvailable`(vAddress INT, vLanded DATE)
BEGIN
    CALL zone_getFromGeo(address_getGeo(vAddress));
    CALL zone_getOptionsForLanding(vLanded);

    SELECT * FROM tmp.zoneOption;

	DROP TEMPORARY TABLE
		tmp.zone,
        tmp.zoneOption;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_getEvents` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getEvents`(
	vProvinceFk INT,
    vPostCode VARCHAR(255),
    vAgencyModeFk INT)
BEGIN
/**
 * Returns available events for the passed province/postcode and agency.
 *
 * @param vAgencyModeFk The agency mode id
 * @param vProvinceFk The province id
 * @param vPostCode The postcode or %NULL to use the province
 */
	DECLARE vGeoFk INT;
	
	IF vPostCode IS NOT NULL THEN
		SELECT p.geoFk INTO vGeoFk
			FROM postCode p
				JOIN town t ON t.id = p.townFk
			WHERE p.`code` = vPostCode
				AND t.provinceFk = vProvinceFk;
	ELSE
		SELECT geoFk INTO vGeoFk
			FROM province
			WHERE id = vProvinceFk;
	END IF;

	CALL zone_getFromGeo(vGeoFk);

	IF vAgencyModeFk IS NOT NULL THEN
		DELETE t FROM tmp.zone t
			JOIN zone z ON z.id = t.id
			WHERE z.agencyModeFk != vAgencyModeFk;
	END IF;

	SELECT e.zoneFk, e.`type`, e.dated, e.`started`, e.`ended`, e.weekDays
		FROM tmp.zone t
			JOIN zoneEvent e ON e.zoneFk = t.id;

	SELECT e.zoneFk, e.dated
		FROM tmp.zone t
			JOIN zoneExclusion e ON e.zoneFk = t.id;

	DROP TEMPORARY TABLE tmp.zone;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_getFromGeo` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getFromGeo`(vGeoFk INT)
BEGIN
/**
 * Returns all zones which have the passed geo included.
 *
 * @param vGeoFk The geo id
 * @return tmp.zone(id) The list of zones
 */
 	DECLARE vChildFk INT DEFAULT vGeoFk;
 	DECLARE vParentFk INT;
    DECLARE vLevel INT DEFAULT 1;
	
    DROP TEMPORARY TABLE IF EXISTS tNodes;
	CREATE TEMPORARY TABLE tNodes
		(PRIMARY KEY (id))
        ENGINE = MEMORY
		SELECT vGeoFk id, vLevel `level`;
 
	myLoop: LOOP
		SELECT parentFk INTO vParentFk
			FROM zoneGeo
			WHERE id = vChildFk;
		
        SET vChildFk = vParentFk;
        SET vLevel = vLevel + 1;

		INSERT IGNORE INTO tNodes
			SELECT vChildFk, vLevel
				FROM DUAL
				WHERE vChildFk IS NOT NULL;
        
        IF ROW_COUNT() = 0 THEN
			LEAVE myLoop;
		END IF;
    END LOOP;

    DROP TEMPORARY TABLE IF EXISTS tmp.zone;
    CREATE TEMPORARY TABLE tmp.zone
		(INDEX (id))
		ENGINE = MEMORY
        SELECT id FROM (
			SELECT zoneFk id, isIncluded
				FROM (
					SELECT i.zoneFk, i.isIncluded
						FROM tNodes n
							JOIN zoneIncluded i ON i.geoFk = n.id
						ORDER BY zoneFk, n.`level`
				) t
				GROUP BY id HAVING isIncluded
		) t;

	DROP TEMPORARY TABLE tNodes;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_getLanded` */;
/*!50003 SET @saved_cs_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 `zone_getLanded`(vShipped DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT)
BEGIN
/**
* Devuelve una tabla temporal con el dia de recepcion para vShipped.
*
* @param vShipped Fecha de preparacion de mercancia
* @param vAddressFk Id de consignatario, %NULL para recogida
* @param vAgencyModeFk Id agencia
* @param vWarehouseFk vWarehouseFk
* @table tmp.zoneGetLanded Datos de recepciÃ³n
*/

	CALL zone_getFromGeo(address_getGeo(vAddressFk));
    CALL zone_getOptionsForShipment(vShipped);

	DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded;
	CREATE TEMPORARY TABLE tmp.zoneGetLanded
			ENGINE = MEMORY
		SELECT vWarehouseFk warehouseFk,
            TIMESTAMPADD(DAY,zo.travelingDays, vShipped) landed,
			zo.zoneFk
		FROM tmp.zoneOption zo
			JOIN zone z ON z.id = zo.zoneFk
            JOIN zoneWarehouse zw ON zw.zoneFk = z.id
		WHERE agencyModeFk = vAgencyModeFk
			AND zw.warehouseFk = vWarehouseFk;
            
	DROP TEMPORARY TABLE
		tmp.zone,
        tmp.zoneOption;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_getLeaves` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getLeaves`(
	vSelf INT,
    vParentFk INT,
    vSearch VARCHAR(255)
)
BEGIN 
	DECLARE vIsNumber BOOL;
	DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != '';

	DROP TEMPORARY TABLE IF EXISTS tNodes;
	CREATE TEMPORARY TABLE tNodes
		(UNIQUE (id))
		ENGINE = MEMORY
		SELECT id FROM zoneGeo LIMIT 0;

	IF vIsSearch THEN
		SET vIsNumber = vSearch REGEXP '^[0-9]+$';

		INSERT INTO tNodes
			SELECT id FROM zoneGeo
				WHERE (vIsNumber AND `name` = vSearch)
					OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%'))
				LIMIT 1000;
	ELSEIF vParentFk IS NULL THEN
		INSERT INTO tNodes
			SELECT geoFk FROM zoneIncluded
				WHERE zoneFk = vSelf;
	END IF;

	IF vParentFk IS NULL THEN
		DROP TEMPORARY TABLE IF EXISTS tChilds;
		CREATE TEMPORARY TABLE tChilds
			ENGINE = MEMORY
			SELECT id FROM tNodes;

		DROP TEMPORARY TABLE IF EXISTS tParents;
		CREATE TEMPORARY TABLE tParents
			ENGINE = MEMORY
			SELECT id FROM zoneGeo LIMIT 0;

		myLoop: LOOP
			DELETE FROM tParents;
			INSERT INTO tParents
				SELECT parentFk id
					FROM zoneGeo g
						JOIN tChilds c ON c.id = g.id
					WHERE g.parentFk IS NOT NULL;
			
			INSERT IGNORE INTO tNodes
				SELECT id FROM tParents;
			
			IF ROW_COUNT() = 0 THEN
				LEAVE myLoop;
			END IF;
			
			DELETE FROM tChilds;
			INSERT INTO tChilds
				SELECT id FROM tParents;
		END LOOP;
		
		DROP TEMPORARY TABLE
			tChilds,
			tParents;
	END IF;

	IF !vIsSearch THEN
		INSERT IGNORE INTO tNodes
			SELECT id FROM zoneGeo
				WHERE parentFk <=> vParentFk;
	END IF;

	SELECT g.id,
			g.`name`,
			g.parentFk,
			g.sons,
			isIncluded selected
		FROM zoneGeo g
			JOIN tNodes n ON n.id = g.id
			LEFT JOIN zoneIncluded i
				ON i.geoFk = g.id AND i.zoneFk = vSelf
		ORDER BY depth, selected DESC, `name`;

	DROP TEMPORARY TABLE tNodes;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_getOptionsForLanding` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForLanding`(vLanded DATE)
BEGIN
/**
 * Gets computed options for the passed zones and delivery date.
 *
 * @table tmp.zones(id) The zones ids
 * @param vLanded The delivery date
 * @return tmp.zoneOption The computed options
 */
	DECLARE vHour TIME DEFAULT TIME(NOW());
	
	DROP TEMPORARY TABLE IF EXISTS tTemp;
	CREATE TEMPORARY TABLE tTemp
		ENGINE = MEMORY
		SELECT t.id zoneFk,
				IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`,
				IFNULL(e.travelingDays, z.travelingDays) travelingDays,
				IFNULL(e.price, z.price) price,
				IFNULL(e.bonus, z.bonus) bonus,
				CASE
					WHEN e.`type` = 'day'
						THEN 1
					WHEN e.`type` = 'range'
						THEN 2
						ELSE 3
				END specificity
			FROM tmp.zone t
				JOIN zone z ON z.id = t.id
				JOIN zoneEvent e ON e.zoneFk = t.id
			WHERE (
					e.`type` = 'day'
					AND e.dated = vLanded
				) OR (
					e.`type` != 'day'
					AND e.weekDays & (1 << WEEKDAY(vLanded))
					AND (e.`started` IS NULL OR vLanded >= e.`started`)
					AND (e.`ended` IS NULL OR vLanded <= e.`ended`)
				);

	DELETE t FROM tTemp t
		JOIN zoneExclusion e
			ON e.zoneFk = t.zoneFk AND e.`dated` = vLanded;

	DELETE FROM tTemp
		WHERE (@shipped := TIMESTAMPADD(DAY, -travelingDays, vLanded)) < CURDATE()
			OR @shipped = CURDATE() AND vHour > `hour`;

	DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption;
	CREATE TEMPORARY TABLE tmp.zoneOption
		ENGINE = MEMORY
		SELECT *
			FROM (
				SELECT * FROM tTemp
				ORDER BY zoneFk, specificity
			) t
			GROUP BY zoneFk;

	DROP TEMPORARY TABLE tTemp;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_getOptionsForShipment` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForShipment`(vShipped DATE)
BEGIN
/**
 * Gets computed options for the passed zones and shipping date.
 *
 * @table tmp.zones(id) The zones ids
 * @param vShipped The shipping date
 * @return tmp.zoneOption(zoneFk, hour, travelingDays, price, bonus, specificity) The computed options
 */
	DROP TEMPORARY TABLE IF EXISTS tLandings;
	CREATE TEMPORARY TABLE tLandings
		(INDEX (eventFk))
		ENGINE = MEMORY
		SELECT e.id eventFk,
				@travelingDays := IFNULL(e.travelingDays, z.travelingDays) travelingDays,
				TIMESTAMPADD(DAY, @travelingDays, vShipped) landed
			FROM tmp.zone t
				JOIN zone z ON z.id = t.id
				JOIN zoneEvent e ON e.zoneFk = t.id;

	DROP TEMPORARY TABLE IF EXISTS tTemp;
	CREATE TEMPORARY TABLE tTemp
		ENGINE = MEMORY
		SELECT t.id zoneFk,
				IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`,
				IFNULL(e.price, z.price) price,
				IFNULL(e.bonus, z.bonus) bonus,
				CASE
					WHEN e.`type` = 'day'
						THEN 1
					WHEN e.`type` = 'range'
						THEN 2
						ELSE 3
				END specificity,
				l.travelingDays,
                l.landed
			FROM tmp.zone t
				JOIN zone z ON z.id = t.id
				JOIN zoneEvent e ON e.zoneFk = t.id
				JOIN tLandings l ON l.eventFk = e.id
			WHERE (
					e.`type` = 'day'
					AND e.`dated` = l.landed
				) OR (
					e.`type` != 'day'
					AND e.weekDays & (1 << WEEKDAY(l.landed))
					AND (e.`started` IS NULL OR l.landed >= e.`started`)
					AND (e.`ended` IS NULL OR l.landed <= e.`ended`)
				);

	DELETE t FROM tTemp t
		JOIN zoneExclusion e
			ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed;

	DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption;
	CREATE TEMPORARY TABLE tmp.zoneOption
		ENGINE = MEMORY
		SELECT *
			FROM (
				SELECT * FROM tTemp
				ORDER BY zoneFk, specificity
			) t
			GROUP BY zoneFk;

	DROP TEMPORARY TABLE
		tTemp,
        tLandings;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_getShippedWarehouse` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getShippedWarehouse`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT)
BEGIN
/**
 * Devuelve la mÃ­nima fecha de envÃ­o para cada warehouse
 * 
 * @param vLanded La fecha de recepcion
 * @param vAddressFk Id del consignatario
 * @param vAgencyModeFk Id de la agencia
 * @return tmp.zoneGetShipped
 */
 
	CALL zone_getFromGeo(address_getGeo(vAddressFk));
    CALL zone_getOptionsForLanding(vLanded);
        
	DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped;
	CREATE TEMPORARY TABLE tmp.zoneGetShipped
			ENGINE = MEMORY
		SELECT * FROM (
				SELECT zo.zoneFk,
						TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped,
						zw.warehouseFk,
                        z.agencyModeFk
					FROM tmp.zoneOption zo
						JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk
                        JOIN zone z ON z.id = zo.zoneFk
					WHERE z.agencyModeFk = vAgencyModeFk
                ORDER BY shipped) t
			GROUP BY warehouseFk;
            
	DROP TEMPORARY TABLE
		tmp.zone,
        tmp.zoneOption;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_getWarehouse` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getWarehouse`(vAddress INT, vLanded DATE, vWarehouse INT)
BEGIN
/**
 * Devuelve el listado de agencias disponibles para la fecha,
 * dirección y almacén pasados.
 * 
 * @param vAddress
 * @param vWarehouse warehouse
 * @param vLanded Fecha de recogida
 * @select Listado de agencias disponibles
 */
 
	CALL zone_getFromGeo(address_getGeo(vAddress));
    CALL zone_getOptionsForLanding(vLanded);
    
	SELECT am.id agencyModeFk, 
			am.name agencyMode, 
			am.description, 
			am.deliveryMethodFk,
			TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, 
			zw.warehouseFk,
			z.id zoneFk
		FROM tmp.zoneOption zo
			JOIN zone z ON z.id = zo.zoneFk
            JOIN agencyMode am ON am.id = z.agencyModeFk
            JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk
		WHERE zw.warehouseFk
		GROUP BY z.agencyModeFk
		ORDER BY agencyMode;
        
	DROP TEMPORARY TABLE
		tmp.zone,
        tmp.zoneOption;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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=InnoDBDEFAULT 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 `inter_ibfk_1` FOREIGN KEY (`Id_Ticket`) REFERENCES `vn`.`ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `inter_state` FOREIGN KEY (`state_id`) REFERENCES `vn`.`state` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `responsable` FOREIGN KEY (`Id_Supervisor`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!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 `ticketTracking_beforeInsert`
	BEFORE INSERT ON `inter`
	FOR EACH ROW
BEGIN
/*
	-- 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;
*//* 
	-- PAK 08/05/18 Los sacadores no deben de poner los tickets en revisión

	DECLARE vIsSacador BOOL;
    
	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 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 THEN -- Preparación
		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  = 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 `vncontrol`.`ticketTracking_afterInsert`
	AFTER INSERT ON `inter`
	FOR EACH ROW
BEGIN
	REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name)
		SELECT NEW.Id_Ticket, NEW.inter_id, `name`
			FROM vn.state
			WHERE 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  = 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 `vncontrol`.`ticketTracking_afterUpdate`
	AFTER UPDATE ON `inter`
	FOR EACH ROW
BEGIN
	DECLARE vTicketFk INT;
    DECLARE vTicketTrackingFk INT;
    DECLARE vStateName VARCHAR(15);
    
	IF NEW.state_id <> OLD.state_id THEN
		REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name)
			SELECT NEW.Id_Ticket, NEW.inter_id, `name`
				FROM vn.state
				WHERE id = NEW.state_id;
    END IF;
    
    IF NEW.Id_Ticket <> OLD.Id_Ticket THEN
		SELECT i.Id_Ticket, i.inter_id, s.`name`
			INTO vTicketFk, vTicketTrackingFk, vStateName 
			FROM vncontrol.inter i 
				JOIN vn.state s ON i.state_id = s.id 
			WHERE Id_Ticket = NEW.Id_Ticket 
			ORDER BY odbc_date DESC 
			LIMIT 1;

		IF vTicketFk > 0 THEN
			REPLACE INTO vn.ticketLastState(ticketFk, ticketTrackingFk,name)
				VALUES(vTicketFk, vTicketTrackingFk, vStateName);
		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  = 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 `vncontrol`.`ticketTracking_afterDelete`
	AFTER DELETE ON `inter`
	FOR EACH ROW
BEGIN
	DECLARE vTicketFk INT;
	DECLARE vTicketTrackingFk INT;
	DECLARE vStateName VARCHAR(15);

	DECLARE CONTINUE HANDLER FOR SQLSTATE '23000'
	BEGIN
		DELETE FROM vn.ticketLastState
			WHERE ticketFk = OLD.Id_Ticket;
	END;

		SELECT i.Id_Ticket, i.inter_id, s.`name`
			INTO vTicketFk, vTicketTrackingFk, vStateName 
			FROM vncontrol.inter i 
				JOIN vn.state s ON i.state_id = s.id 
			WHERE Id_Ticket = OLD.Id_Ticket 
			ORDER BY odbc_date DESC 
			LIMIT 1;

		IF vTicketFk > 0 THEN
			REPLACE INTO vn.ticketLastState(ticketFk, ticketTrackingFk,name)
				VALUES(vTicketFk, vTicketTrackingFk, vStateName);
		END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;

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

--
-- Dumping routines for database 'vncontrol'
--
/*!50003 DROP PROCEDURE IF EXISTS `clean` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `clean`()
BEGIN
    DECLARE vDate DATETIME DEFAULT TIMESTAMPADD(MONTH, -2, CURDATE());
    DELETE i FROM inter i JOIN vn.ticket t ON i.Id_Ticket = t.id
		WHERE t.shipped <= 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      = 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 `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 `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 `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 */;

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

USE `cache`;

--
-- Current Database: `edi`
--

USE `edi`;

--
-- 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_general_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`.`hasPdf` AS `hasPdf` 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 `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 `myOrderTicket`
--

/*!50001 DROP VIEW IF EXISTS `myOrderTicket`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `myOrderTicket` 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 `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      = 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 `orderTicket` AS select `b`.`orderFk` AS `orderFk`,`b`.`ticketFk` AS `ticketFk` from `vn`.`orderTicket` `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_general_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`.`md5Secret` AS `md5secret`,`u`.`nickname` 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`,`c`.`transport` AS `transport`,`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 (((`pbx`.`sip` `s` join `account`.`user` `u` on((`u`.`id` = `s`.`user_id`))) left join `pbx`.`sipReg` `r` on((`s`.`user_id` = `r`.`userId`))) join `pbx`.`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`;

--
-- 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`,`cs`.`code` AS `code` 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 `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 `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 `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 `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 `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 `cmr_list`
--

/*!50001 DROP VIEW IF EXISTS `cmr_list`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `cmr_list` AS select `cmr`.`id` AS `cmrFk`,`cmr`.`ticketFk` AS `ticketFk`,`cmr`.`truckPlate` AS `truckPlate`,`cmr`.`observations` AS `observations`,`cmr`.`senderInstruccions` AS `senderInstruccions`,`cmr`.`paymentInstruccions` AS `paymentInstruccions`,`cmr`.`specialAgreements` AS `specialAgreements`,`cmr`.`created` AS `created`,`t`.`addressFk` AS `addressFk`,`t`.`shipped` AS `shipped`,`a`.`nickname` AS `clientName`,`a`.`postalCode` AS `clientPostalCode`,`a`.`street` AS `clientStreet`,`a`.`city` AS `clientCity`,`p`.`name` AS `clientProvince`,`co`.`country` AS `clientCountry`,`su`.`name` AS `companyName`,`su`.`street` AS `companyStreet`,`su`.`postCode__` AS `companyPostCode`,`su`.`city` AS `companyCity`,`sc`.`country` AS `companyCountry`,`w`.`addressName` AS `warehouseAddress`,`c`.`name` AS `clientOficialName`,ifnull(`ags`.`name`,`agm`.`name`) AS `carrierName`,`ags`.`street` AS `carrierStreet`,`ags`.`postCode` AS `carrierPostCode`,`ags`.`city` AS `carrierCity`,`sco`.`country` AS `carrierCountry`,ifnull(`a`.`phone`,`c`.`phone`) AS `phone`,ifnull(`a`.`mobile`,`c`.`mobile`) AS `mobile` from ((((((((((((`cmr` join `ticket` `t` on((`t`.`id` = `cmr`.`ticketFk`))) join `address` `a` on((`a`.`id` = `t`.`addressFk`))) join `province` `p` on((`p`.`id` = `a`.`provinceFk`))) join `country` `co` on((`co`.`id` = `p`.`countryFk`))) join `warehouse` `w` on((`w`.`id` = `t`.`warehouseFk`))) join `supplier` `su` on((`su`.`id` = `t`.`companyFk`))) join `country` `sc` on((`sc`.`id` = `su`.`countryFk`))) join `client` `c` on((`c`.`id` = `t`.`clientFk`))) join `agencyMode` `agm` on((`agm`.`id` = `t`.`agencyModeFk`))) join `agency` `ag` on((`ag`.`id` = `agm`.`agencyFk`))) left join `supplier` `ags` on((`ags`.`id` = `ag`.`supplierFk`))) left join `country` `sco` on((`sco`.`id` = `ags`.`countryFk`))) */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `collectionReportSource`
--

/*!50001 DROP VIEW IF EXISTS `collectionReportSource`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `collectionReportSource` AS select `tc`.`collectionFk` AS `collectionFk`,`tc`.`ticketFk` AS `ticketFk`,`s`.`itemFk` AS `itemFk`,`s`.`concept` AS `concept`,`i`.`size` AS `size`,`s`.`quantity` AS `quantity`,`ip`.`code` AS `nicho`,`tc`.`level` AS `level` from (((((`collection` `c` join `ticketCollection` `tc` on((`tc`.`collectionFk` = `c`.`id`))) join `ticket` `t` on((`t`.`id` = `tc`.`ticketFk`))) join `sale` `s` on((`s`.`ticketFk` = `t`.`id`))) join `item` `i` on((`i`.`id` = `s`.`itemFk`))) join `itemPlacement` `ip` on(((`ip`.`itemFk` = `s`.`itemFk`) and (`ip`.`warehouseFk` = `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 `component`
--

/*!50001 DROP VIEW IF EXISTS `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 `component` AS select `t`.`Id_Componente` AS `id`,`t`.`Componente` AS `name`,`t`.`tarifa_componentes_series_id` AS `typeFk`,`t`.`tarifa_class` AS `classRate`,`t`.`tax` AS `tax`,`t`.`is_renewable` AS `isRenewable`,`t`.`code` AS `code` 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 `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      = 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 `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`,`t`.`code` AS `code` 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 `componentType`
--

/*!50001 DROP VIEW IF EXISTS `componentType`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `componentType` AS select `t`.`tarifa_componentes_series_id` AS `id`,`t`.`Serie` AS `type`,`t`.`base` AS `base`,`t`.`margen` AS `isMargin` 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 `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      = 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 `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 `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 `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 (`department` `node` join `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 `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 `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 ((`entry` `e` join `buy` `b` on((`e`.`id` = `b`.`entryFk`))) join `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 `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 `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 `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 `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 (((((`buy` `b` join `item` `i` on((`b`.`itemFk` = `i`.`id`))) join `itemType` `it` on((`it`.`id` = `i`.`typeFk`))) join `itemCategory` `ic` on((`ic`.`id` = `it`.`categoryFk`))) join `entry` `e` on((`e`.`id` = `b`.`entryFk`))) join `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 `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      = 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 `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 `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 (`ink` `k` left join `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 `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 (`sale` `s` join `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 `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 `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 (`itemCategory` `c` left join `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 `itemEntryIn`
--

/*!50001 DROP VIEW IF EXISTS `itemEntryIn`*/;
/*!50001 SET @saved_cs_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 `itemEntryIn` AS select `t`.`warehouseInFk` AS `warehouseInFk`,`t`.`landed` AS `landed`,`b`.`itemFk` AS `itemFk`,`b`.`quantity` AS `quantity`,`t`.`isReceived` AS `isReceived`,`e`.`isRaid` AS `isVirtualStock`,`e`.`id` AS `entryFk` from ((`buy` `b` join `entry` `e` on((`b`.`entryFk` = `e`.`id`))) join `travel` `t` on((`e`.`travelFk` = `t`.`id`))) where ((`e`.`isInventory` = 0) and (`b`.`quantity` <> 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 `itemEntryOut`
--

/*!50001 DROP VIEW IF EXISTS `itemEntryOut`*/;
/*!50001 SET @saved_cs_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 `itemEntryOut` AS select `t`.`warehouseOutFk` AS `warehouseOutFk`,`t`.`shipped` AS `shipped`,`b`.`itemFk` AS `itemFk`,-(`b`.`quantity`) AS `quantity`,`t`.`isDelivered` AS `isDelivered`,`e`.`id` AS `entryFk` from ((`buy` `b` join `entry` `e` on((`b`.`entryFk` = `e`.`id`))) join `travel` `t` on((`e`.`travelFk` = `t`.`id`))) where ((`e`.`isInventory` = 0) and (`e`.`isRaid` = 0) and (`b`.`quantity` <> 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 `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`,ifnull(`isps`.`created`,`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`,max(`p`.`code`) AS `parking`,`ips`.`sectorFk` AS `sectorFk` from (((((((`itemPlacementSupply` `ips` join `item` `i` on((`i`.`id` = `ips`.`itemFk`))) left join `worker` `w` on((`w`.`userFk` = `ips`.`userFk`))) left join `worker` `rw` on((`rw`.`userFk` = `ips`.`repoUserFk`))) left join `itemShelvingPlacementSupply` `isps` on((`isps`.`itemPlacementSupplyFk` = `ips`.`id`))) left join `itemShelving` `ish` on((`ish`.`id` = `isps`.`itemShelvingFk`))) left join `shelving` `s` on((`ish`.`shelvingFk` = `s`.`code`))) left join `parking` `p` on((`s`.`parkingFk` = `p`.`id`))) where (`ips`.`created` >= curdate()) group by `ips`.`priority`,`ips`.`id`,`p`.`sectorFk` */;
/*!50001 SET character_set_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`,max(`p`.`code`) AS `parking`,max(`p`.`sectorFk`) AS `sectorFk` from (((((((`itemPlacementSupply` `ips` join `itemShelving` `ish` on((`ish`.`itemFk` = `ips`.`itemFk`))) join `item` `i` on((`i`.`id` = `ish`.`itemFk`))) left join `worker` `w` on((`w`.`userFk` = `ips`.`userFk`))) left join `worker` `rw` on((`rw`.`userFk` = `ips`.`repoUserFk`))) left join `itemShelvingPlacementSupply` `isps` on((`isps`.`itemPlacementSupplyFk` = `ips`.`id`))) left join `shelving` `s` on((`ish`.`shelvingFk` = `s`.`code`))) left join `parking` `p` on((`s`.`parkingFk` = `p`.`id`))) where (`ips`.`created` >= curdate()) group by `ips`.`priority`,`ips`.`id`,`p`.`sectorFk` */;
/*!50001 SET character_set_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`,0 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`,`stock`.`visible` AS `available`,`stock`.`sectorFk` AS `sectorFk`,`stock`.`shelvingFk` AS `matricula`,`stock`.`parkingFk` AS `parking`,`stock`.`itemShelvingFk` AS `itemShelving`,`am`.`name` AS `Agency`,`t`.`shipped` AS `shipped`,`stock`.`grouping` AS `grouping`,`stock`.`packing` AS `packing`,`z`.`hour` AS `hour`,`st`.`isPreviousPreparable` AS `isPreviousPreparable`,`sv`.`physicalVolume` AS `physicalVolume` 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`.`itemShelvingStock` `stock` on((`stock`.`itemFk` = `i`.`id`))) left join `vn`.`saleTracking` `stk` on((`stk`.`saleFk` = `s`.`id`))) left join `vn`.`zone` `z` on((`z`.`id` = `t`.`zoneFk`))) left join `vn`.`saleVolume` `sv` on((`sv`.`saleFk` = `s`.`id`))) where ((`t`.`shipped` between `util`.`yesterday`() and `util`.`dayend`(curdate())) and isnull(`stk`.`id`) and (`stock`.`visible` > 0) and isnull(`stk`.`saleFk`) 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 (((`itemShelving` `ish` join `shelving` `sh` on((`sh`.`code` = `ish`.`shelvingFk`))) join `item` `i` on((`i`.`id` = `ish`.`itemFk`))) left join `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`,`p`.`id` AS `parkingFk`,`p`.`sectorFk` AS `sectorFk` from (((`itemShelving` `ish` join `shelving` `sh` on((`sh`.`code` = `ish`.`shelvingFk`))) left join `parking` `p` on((`p`.`id` = `sh`.`parkingFk`))) join `item` `i` on((`i`.`id` = `ish`.`itemFk`))) 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 `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 (((((`itemShelving` `ish` join `shelving` `sh` on((`sh`.`code` = `ish`.`shelvingFk`))) left join `parking` `p` on((`p`.`id` = `sh`.`parkingFk`))) join `item` `i` on((`i`.`id` = `ish`.`itemFk`))) 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 `itemShelvingSaleSum`
--

/*!50001 DROP VIEW IF EXISTS `itemShelvingSaleSum`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemShelvingSaleSum` AS select `iss`.`id` AS `id`,`iss`.`itemShelvingFk` AS `itemShelvingFk`,`iss`.`saleFk` AS `saleFk`,sum(`iss`.`quantity`) AS `quantity`,`iss`.`created` AS `created`,`p`.`sectorFk` AS `sectorFk` from (((`itemShelvingSale` `iss` join `itemShelving` `ish` on((`ish`.`id` = `iss`.`itemShelvingFk`))) join `shelving` `sh` on((`sh`.`code` = `ish`.`shelvingFk`))) join `parking` `p` on((`p`.`id` = `sh`.`parkingFk`))) group by `iss`.`saleFk` */;
/*!50001 SET character_set_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`,min(`ish`.`grouping`) AS `grouping`,`s`.`description` AS `sector`,sum(`ish`.`visible`) AS `visibleOriginal`,sum(`issr`.`removed`) AS `removed`,`p`.`sectorFk` AS `sectorFk`,`s`.`warehouseFk` AS `warehouseFk`,`ish`.`shelvingFk` AS `shelvingFk`,`p`.`code` AS `parkingCode`,`sh`.`parkingFk` AS `parkingFk`,`ish`.`id` AS `itemShelvingFk`,`ish`.`created` AS `created` from ((((`itemShelving` `ish` left join `shelving` `sh` on((`sh`.`code` = `ish`.`shelvingFk`))) left join `parking` `p` on((`p`.`id` = `sh`.`parkingFk`))) left join `sector` `s` on((`s`.`id` = `p`.`sectorFk`))) left join `itemShelvingStockRemoved` `issr` on((`issr`.`itemShelvingFk` = `ish`.`id`))) where ((`ish`.`visible` <> 0) and `p`.`sectorFk`) group by `ish`.`itemFk`,`p`.`sectorFk` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `itemShelvingStockFull`
--

/*!50001 DROP VIEW IF EXISTS `itemShelvingStockFull`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `itemShelvingStockFull` AS select `ish`.`itemFk` AS `itemFk`,`ish`.`visible` AS `quantity`,`ish`.`packing` AS `packing`,`ish`.`grouping` AS `grouping`,`s`.`description` AS `sector`,`issr`.`removed` AS `removed`,`p`.`sectorFk` AS `sectorFk`,`s`.`warehouseFk` AS `warehouseFk`,`ish`.`shelvingFk` AS `shelvingFk`,`p`.`code` AS `parkingCode`,`sh`.`parkingFk` AS `parkingFk`,`ish`.`id` AS `itemShelvingFk`,`ish`.`created` AS `created` 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`))) */;
/*!50001 SET character_set_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 `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 `itemTicketOut`
--

/*!50001 DROP VIEW IF EXISTS `itemTicketOut`*/;
/*!50001 SET @saved_cs_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 `itemTicketOut` AS select `t`.`warehouseFk` AS `warehouseFk`,`t`.`shipped` AS `shipped`,`s`.`itemFk` AS `itemFk`,-(`s`.`quantity`) AS `quantity`,`s`.`isPicked` AS `isPicked`,`s`.`reserved` AS `reserved`,`t`.`refFk` AS `refFk`,`s`.`id` AS `saleFk`,`s`.`ticketFk` AS `ticketFk` from (`sale` `s` join `ticket` `t` on((`s`.`ticketFk` = `t`.`id`))) where (`s`.`quantity` <> 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 `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 (`itemType` `t` left join `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 `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 (`origin` `o` left join `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 `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 ((`packageEquivalent` `pe` join `packaging` `i` on((`i`.`id` = `pe`.`packageFk`))) join `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 `personMedia`
--

/*!50001 DROP VIEW IF EXISTS `personMedia`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `personMedia` 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 personal') */;
/*!50001 SET character_set_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 `saleFreight`
--

/*!50001 DROP VIEW IF EXISTS `saleFreight`*/;
/*!50001 SET @saved_cs_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 `saleFreight` AS select `s`.`ticketFk` AS `ticketFk`,`t`.`clientFk` AS `clientFk`,`t`.`routeFk` AS `routeFk`,`s`.`id` AS `saleFk`,`t`.`zoneFk` AS `zoneFk`,`t`.`companyFk` AS `companyFk`,`t`.`shipped` AS `shipped`,`zc`.`price` AS `price`,((((`s`.`quantity` * `r`.`cm3`) * `zc`.`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`.`packaging` `cb` on((`cb`.`id` = '94'))) join `bi`.`rotacion` `r` on(((`r`.`Id_Article` = `s`.`itemFk`) and (`r`.`warehouse_id` = `t`.`warehouseFk`)))) join `vn`.`zoneCalendar` `zc` on(((`zc`.`zoneFk` = `t`.`zoneFk`) and (`zc`.`delivered` = `t`.`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 `saleValue`
--

/*!50001 DROP VIEW IF EXISTS `saleValue`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `saleValue` AS select `wh`.`name` AS `warehouse`,`c`.`name` AS `client`,`c`.`typeFk` AS `clientTypeFk`,`u`.`name` AS `buyer`,`it`.`name` AS `family`,`s`.`itemFk` AS `itemFk`,`s`.`concept` AS `concept`,`s`.`quantity` AS `quantity`,(((`b`.`buyingValue` + `b`.`freightValue`) + `b`.`comissionValue`) + `b`.`packageValue`) AS `cost`,((((`b`.`buyingValue` + `b`.`freightValue`) + `b`.`comissionValue`) + `b`.`packageValue`) * `s`.`quantity`) AS `value`,`tm`.`year` AS `year`,`tm`.`week` AS `week` from (((((((((`vn`.`sale` `s` join `vn`.`item` `i` on((`i`.`id` = `s`.`itemFk`))) join `vn`.`itemType` `it` on((`it`.`id` = `i`.`typeFk`))) join `account`.`user` `u` on((`u`.`id` = `it`.`workerFk`))) join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `vn`.`client` `c` on((`c`.`id` = `t`.`clientFk`))) join `vn`.`warehouse` `wh` on((`wh`.`id` = `t`.`warehouseFk`))) join `vn`.`time` `tm` on((`tm`.`dated` = cast(`t`.`shipped` as date)))) join `cache`.`last_buy` `lb` on(((`lb`.`item_id` = `i`.`id`) and (`lb`.`warehouse_id` = `wh`.`id`)))) join `vn`.`buy` `b` on((`b`.`id` = `lb`.`buy_id`))) where `wh`.`isManaged` */;
/*!50001 SET character_set_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`.`ticketFk` AS `ticketFk`,`s`.`id` AS `saleFk`,ifnull(round(((((`i`.`compression` * (greatest(`i`.`density`,167) / 167)) * `r`.`cm3`) * `s`.`quantity`) / 1000),2),0) AS `litros`,`t`.`routeFk` AS `routeFk`,`t`.`shipped` AS `shipped`,(((`s`.`quantity` * `r`.`cm3`) * `i`.`compression`) / 1000000) AS `volume`,((((`s`.`quantity` * `r`.`cm3`) * `i`.`compression`) * (greatest(`i`.`density`,167) / 167)) / 1000000) AS `physicalWeight`,(((`s`.`quantity` * `r`.`cm3`) * `i`.`density`) / 1000000) AS `weight`,(((`s`.`quantity` * `r`.`cm3`) * `i`.`compression`) / 1000000) AS `physicalVolume` from (((`vn`.`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`)))) */;
/*!50001 SET character_set_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 ((((((`buy` `b` join `item` `i` on((`i`.`id` = `b`.`itemFk`))) join `packaging` `p` on((`p`.`itemFk` = `i`.`id`))) join `entry` `e` on((`e`.`id` = `b`.`entryFk`))) join `supplier` `s` on((`s`.`id` = `e`.`supplierFk`))) join `travel` `tr` on((`tr`.`id` = `e`.`travelFk`))) join `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 `ticketGetVolume__`
--

/*!50001 DROP VIEW IF EXISTS `ticketGetVolume__`*/;
/*!50001 SET @saved_cs_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 `ticketGetVolume__` AS select `s`.`ticketFk` AS `ticketFk`,`t`.`routeFk` AS `routeFk`,`s`.`id` AS `saleFk`,`t`.`shipped` AS `shipped`,(((`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 `bi`.`rotacion` `r` on(((`r`.`Id_Article` = `s`.`itemFk`) 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 `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 (((`ticket` `t` join `sale` `s` on((`s`.`ticketFk` = `t`.`id`))) join `client` `c` on((`c`.`id` = `t`.`clientFk`))) join `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 `ticketPreviousPreparingList`
--

/*!50001 DROP VIEW IF EXISTS `ticketPreviousPreparingList`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketPreviousPreparingList` AS select `t`.`id` AS `ticketFk`,`w`.`code` AS `code`,count(`st`.`id`) AS `saleLines`,sum((`st`.`isChecked` <> 0)) AS `alreadyMadeSaleLines`,(sum((`st`.`isChecked` <> 0)) / count(`st`.`id`)) AS `madeRate`,`st`.`created` AS `created`,`i`.`sectorFk` AS `sectorFk`,`p`.`code` AS `parking` from (((((((`ticket` `t` join `sale` `s` on((`s`.`ticketFk` = `t`.`id`))) join `item` `i` on((`i`.`id` = `s`.`itemFk`))) join `saleTracking` `st` on((`st`.`saleFk` = `s`.`id`))) join `state` on((`state`.`id` = `st`.`stateFk`))) left join `worker` `w` on((`w`.`id` = `st`.`workerFk`))) left join `ticketParking` `tp` on((`tp`.`ticketFk` = `t`.`id`))) left join `parking` `p` on((`p`.`id` = `tp`.`parkingFk`))) where ((`state`.`code` = 'PREVIOUS_PREPARATION') and (`t`.`shipped` >= (curdate() + interval -(1) day))) group by `s`.`ticketFk`,`i`.`sectorFk` */;
/*!50001 SET character_set_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      = 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 `ticketState` AS select `i`.`odbc_date` AS `updated`,`i`.`state_id` AS `stateFk`,`i`.`Id_Trabajador` AS `workerFk`,`tls`.`ticketFk` AS `ticketFk`,`s`.`id` AS `state`,`s`.`order` AS `productionOrder`,`s`.`alertLevel` AS `alertLevel`,`s`.`code` AS `code`,`tls`.`ticketFk` AS `ticket`,`i`.`Id_Trabajador` AS `worker`,`s`.`isPreviousPreparable` AS `isPreviousPreparable`,`s`.`isPicked` AS `isPicked` from ((`vn`.`ticketLastState` `tls` join `vncontrol`.`inter` `i` on((`i`.`inter_id` = `tls`.`ticketTrackingFk`))) join `vn`.`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`,`ts`.`isPicked` AS `isPicked` 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 `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 `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 `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      = 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 `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`))) order by `b`.`date_start` 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 `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      = 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 `workerMana__` AS select `ms`.`Id_Trabajador` AS `workerFk`,`ms`.`size` AS `size`,`ms`.`used` AS `amount`,`ms`.`prices_modifier_rate` AS `pricesModifierRate`,`ms`.`prices_modifier_activated` AS `isPricesModifierActivated`,`ms`.`minRate` AS `minRate`,`ms`.`maxRate` AS `maxRate` from `bs`.`mana_spellers` `ms` */;
/*!50001 SET character_set_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 `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      = 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 `workerTeamCollegues` AS select distinct `w`.`workerFk` AS `workerFk`,`t`.`workerFk` AS `collegueFk` from (`workerTeam` `w` join `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 `workerTimeControlUserInfo`
--

/*!50001 DROP VIEW IF EXISTS `workerTimeControlUserInfo`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `workerTimeControlUserInfo` AS select `u`.`id` AS `userFk`,`w`.`firstName` AS `name`,`w`.`lastName` AS `surname`,`u`.`name` AS `user`,`u`.`password` AS `password`,`u`.`bcryptPassword` AS `bcryptPassword`,`wd`.`departmentFk` AS `departmentFk`,left(`w`.`fi`,8) AS `dni` from ((`account`.`user` `u` join `vn`.`worker` `w` on((`w`.`userFk` = `u`.`id`))) left join `vn`.`workerDepartment` `wd` on((`wd`.`workerFk` = `w`.`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 `workerTimeControlWorking`
--

/*!50001 DROP VIEW IF EXISTS `workerTimeControlWorking`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = utf8 */;
/*!50001 SET character_set_results     = utf8 */;
/*!50001 SET collation_connection      = utf8_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `workerTimeControlWorking` AS select `wtc`.`userFk` AS `userFk`,`wtc`.`timed` AS `timed`,`w`.`firstName` AS `name`,`w`.`lastName` AS `surname`,`pm`.`mediaValue` AS `phone`,`wm`.`mediaValue` AS `workerPhone`,`d`.`name` AS `department`,`wc`.`name` AS `workerCenter`,count(`wtc`.`order`) AS `maxOrder` from (((((((`vn`.`workerTimeControl` `wtc` join `vn`.`worker` `w` on((`w`.`userFk` = `wtc`.`userFk`))) left join `vn`.`personMedia` `pm` on((`pm`.`workerFk` = `w`.`id`))) left join `vn`.`workerMedia` `wm` on((`wm`.`workerFk` = `w`.`id`))) left join `vn`.`workerDepartment` `wd` on((`wd`.`workerFk` = `w`.`id`))) left join `vn`.`department` `d` on((`d`.`id` = `wd`.`departmentFk`))) left join `vn`.`workerLabour` `wl` on((`wl`.`businessFk` = (select `wl2`.`businessFk` from `vn`.`workerLabour` `wl2` where (`wl2`.`workerFk` = `w`.`id`) order by `wl2`.`started` desc limit 1)))) left join `vn`.`workCenter` `wc` on((`wc`.`id` = `wl`.`workCenterFk`))) where (cast(`wtc`.`timed` as date) = curdate()) group by `wtc`.`userFk` having ((`maxOrder` % 2) = 1) order by `wtc`.`timed` 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 `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 (`workerTimeControl` `wtc` join `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 (`workerTimeControl` `wtc` join `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: `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 2020-01-15  7:33:42
