-- MariaDB dump 10.19 Distrib 10.5.23-MariaDB, for debian-linux-gnu (x86_64)
--
-- Host: db.verdnatura.es Database: account
-- ------------------------------------------------------
-- Server version 10.11.6-MariaDB-1:10.11.6+maria~deb12-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 utf8mb3 COLLATE utf8mb3_general_ci */;
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,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `account_fk_editor` (`editorFk`),
CONSTRAINT `account_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `user` (`id`),
CONSTRAINT `account_ibfk_3` FOREIGN KEY (`id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Users allowed to have an account';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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,
`homedir` varchar(50) NOT NULL COMMENT 'The base folder for users home directory',
`shell` varchar(50) NOT NULL COMMENT 'The default shell',
`idBase` int(11) NOT NULL COMMENT 'Base id for Posix users and groups',
`min` smallint(6) NOT NULL,
`max` smallint(6) NOT NULL COMMENT 'Maximum password age (seconds)',
`warn` smallint(6) NOT NULL COMMENT 'Warn to change password when elapsed (seconds)',
`inact` smallint(6) NOT NULL COMMENT 'Maximum inactivity time (seconds)',
PRIMARY KEY (`id`),
CONSTRAINT `accountConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`pid` varchar(255) NOT NULL,
`user` varchar(255) NOT NULL,
`host` varchar(255) NOT NULL,
`rhost` varchar(255) NOT NULL,
`time` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`server` varchar(255) NOT NULL COMMENT 'The LDAP server access url',
`rdn` varchar(255) NOT NULL COMMENT 'The LDAP user',
`password` varchar(255) NOT NULL COMMENT 'The LDAP password',
`userDn` varchar(255) DEFAULT NULL COMMENT 'The base DN for users',
`groupDn` varchar(255) DEFAULT NULL COMMENT 'The base DN for groups',
PRIMARY KEY (`id`),
CONSTRAINT `ldapConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`description` varchar(255) DEFAULT NULL,
`isPublic` tinyint(4) NOT NULL DEFAULT 1,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `alias` (`alias`),
KEY `mailAlias_fk_editor` (`editorFk`),
CONSTRAINT `mailAlias_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`mailAlias` int(10) unsigned NOT NULL,
`account` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `mailAlias` (`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=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Mail alias that is assigned to each account';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `mailAliasAcl`
--
DROP TABLE IF EXISTS `mailAliasAcl`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mailAliasAcl` (
`mailAliasFk` int(10) unsigned NOT NULL,
`roleFk` int(10) unsigned NOT NULL,
KEY `mailAliasFk` (`mailAliasFk`),
KEY `roleFk` (`roleFk`),
CONSTRAINT `mailAliasAcl_ibfk_1` FOREIGN KEY (`mailAliasFk`) REFERENCES `mailAlias` (`id`),
CONSTRAINT `mailAliasAcl_ibfk_2` FOREIGN KEY (`roleFk`) REFERENCES `role` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `mailClientAccess__`
--
DROP TABLE IF EXISTS `mailClientAccess__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mailClientAccess__` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`client` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL,
`action` set('OK','REJECT') CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL DEFAULT 'REJECT',
`description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `mailFrom` (`client`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='@deprecated 2023-09-03';
/*!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,
`domain` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `mailConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`account`),
KEY `mailForward_fk_editor` (`editorFk`),
CONSTRAINT `mailForward_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `user` (`id`),
CONSTRAINT `mailForward_ibfk_1` FOREIGN KEY (`account`) REFERENCES `account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Mail forwarding';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `mailSenderAccess__`
--
DROP TABLE IF EXISTS `mailSenderAccess__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mailSenderAccess__` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`sender` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL,
`action` set('OK','REJECT') NOT NULL DEFAULT 'REJECT',
`description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `mailFrom` (`sender`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='@deprecated 2023-09-03';
/*!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(79) NOT NULL COMMENT 'MariaDB doesn''t support more than 79 chars for proxied user names',
`description` varchar(100) DEFAULT NULL,
`hasLogin` tinyint(3) unsigned NOT NULL DEFAULT 1,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`modified` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
KEY `role_fk_editor` (`editorFk`),
CONSTRAINT `role_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`mysqlPassword` varchar(255) NOT NULL COMMENT 'The password used for MySQL user roles, base64 encoded',
`rolePrefix` char(2) NOT NULL,
`userPrefix` char(2) DEFAULT NULL,
`userHost` varchar(255) NOT NULL,
`tplUser` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `roleConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci 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` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`role` int(10) unsigned NOT NULL,
`inheritsFrom` int(10) unsigned NOT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `role` (`role`,`inheritsFrom`),
KEY `owner_id` (`inheritsFrom`),
KEY `roleInherit_fk_editor` (`editorFk`),
CONSTRAINT `roleInherit_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `user` (`id`),
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=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Role inheritance';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `roleLog`
--
DROP TABLE IF EXISTS `roleLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `roleLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`originFk` int(10) unsigned DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete','select') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` enum('Role','RoleInherit') NOT NULL DEFAULT 'Role',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `userFk` (`userFk`),
KEY `roleLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `roleLog_originFk` (`originFk`,`creationDate`),
CONSTRAINT `roleLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!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` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`role` int(10) unsigned NOT NULL,
`inheritsFrom` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `role` (`role`,`inheritsFrom`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`adDomain` varchar(255) NOT NULL COMMENT 'Active directory domain',
`adController` varchar(255) NOT NULL COMMENT 'The hosname of domain controller',
`adUser` varchar(255) DEFAULT NULL COMMENT 'Active directory user',
`adPassword` varchar(255) DEFAULT NULL COMMENT 'Active directory password',
`verifyCert` tinyint(3) unsigned NOT NULL DEFAULT 1 COMMENT 'Whether to verify server certificate',
`userDn` varchar(255) NOT NULL COMMENT 'Base DN for users without domain DN part',
PRIMARY KEY (`id`),
CONSTRAINT `sambaConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Global configuration parameters for accounts';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `signInLog`
--
DROP TABLE IF EXISTS `signInLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `signInLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`token` varchar(255) NOT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`userName` varchar(30) NOT NULL,
`ip` varchar(100) NOT NULL,
`owner` tinyint(1) DEFAULT 1,
PRIMARY KEY (`id`),
KEY `userFk` (`userFk`),
CONSTRAINT `signInLog_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_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(10) unsigned NOT NULL AUTO_INCREMENT,
`realm` varchar(512) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`name` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`nickname` varchar(127) NOT NULL,
`password` varchar(512) NOT NULL,
`role` int(10) unsigned NOT NULL DEFAULT 2,
`active` tinyint(1) NOT NULL DEFAULT 1,
`email` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`emailVerified` tinyint(1) DEFAULT NULL,
`verificationToken` varchar(512) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`lang` char(2) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`lastPassChange` datetime DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`updated` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`image` varchar(255) DEFAULT NULL,
`password__` char(64) NOT NULL COMMENT 'Deprecated',
`recoverPass` tinyint(3) unsigned NOT NULL DEFAULT 1 COMMENT 'Deprecated',
`sync` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'Deprecated',
`hasGrant` tinyint(1) NOT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
`passExpired` date DEFAULT NULL,
`twoFactor` enum('email') DEFAULT NULL COMMENT 'Two-factor auth type',
`username` varchar(30) GENERATED ALWAYS AS (`name`) VIRTUAL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
UNIQUE KEY `mail` (`email`),
KEY `role` (`role`),
KEY `email` (`email`),
KEY `nickname` (`nickname`),
KEY `lang` (`lang`),
KEY `user_fk_editor` (`editorFk`),
CONSTRAINT `user_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `user` (`id`),
CONSTRAINT `user_ibfk_2` FOREIGN KEY (`role`) REFERENCES `role` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Global users';
/*!40101 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` (
`id` int(10) unsigned NOT NULL,
`loginKey` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `userConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!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 DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete','select') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` enum('VnUser','Account','MailAliasAccount','MailForward') NOT NULL DEFAULT 'VnUser',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `userFk` (`userFk`),
KEY `userLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `userLog_originFk` (`originFk`,`creationDate`),
CONSTRAINT `userLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!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 COMMENT 'Minimal length',
`nAlpha` tinyint(3) unsigned NOT NULL COMMENT 'Minimum of alphabetic characters',
`nUpper` tinyint(3) unsigned NOT NULL COMMENT 'Minimum of uppercase letters',
`nDigits` tinyint(3) unsigned NOT NULL COMMENT 'Minimum of digits',
`nPunct` tinyint(3) unsigned NOT NULL COMMENT 'Minimum of symbols',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Restrictions on user passwords';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `userSync`
--
DROP TABLE IF EXISTS `userSync`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `userSync` (
`name` varchar(30) NOT NULL COMMENT 'The user name',
PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Users pending to be synchronized';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping events for database 'account'
--
--
-- Dumping routines for database 'account'
--
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `myUser_checkLogin` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `myUser_checkLogin`() 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `myUser_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `myUser_getId`() RETURNS int(11)
READS SQL DATA
DETERMINISTIC
BEGIN
/**
* Returns the current user id.
*
* @return The user id
*/
DECLARE vUser INT DEFAULT NULL;
IF myUser_checkLogin()
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `myUser_getName` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `myUser_getName`() RETURNS varchar(30) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
NO SQL
DETERMINISTIC
BEGIN
/**
* Returns the current user name.
*
* @return The user name
*/
DECLARE vUser VARCHAR(30) DEFAULT NULL;
IF myUser_checkLogin()
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `myUser_hasPriv` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `myUser_hasPriv`(vChain VARCHAR(100),
vPrivilege ENUM('SELECT','INSERT','UPDATE','DELETE')
) RETURNS tinyint(1)
READS SQL DATA
BEGIN
/**
* Search if my user has privileges on table or column
*
* @param vChain string passed with this syntax dbName.tableName[.columnName]
* @param vPrivilege privileges to check ('SELECT','INSERT','UPDATE','DELETE')
* @return vHasPrivilege
*/
RETURN user_hasPriv(vChain, vPrivilege, myUser_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `myUser_hasRole` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `myUser_hasRole`(vRoleName VARCHAR(255)) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
/**
* Checks if current user has/inherits a role.
*
* @param vRoleName Role to check
* @return %TRUE if it has role, %FALSE otherwise
*/
RETURN user_hasRole(myUser_getName(), 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `myUser_hasRoleId` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `myUser_hasRoleId`(vRoleId INT) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
/**
* Checks if current user has/inherits a role.
*
* @param vRoleName Role id to check
* @return %TRUE if it has role, %FALSE otherwise
*/
RETURN user_hasRoleId(myUser_getName(), 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `myUser_hasRoutinePriv` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `myUser_hasRoutinePriv`(vType ENUM('PROCEDURE', 'FUNCTION'),
vChain VARCHAR(100)
) RETURNS tinyint(1)
READS SQL DATA
BEGIN
/**
* Search if my user has privileges on routines
*
* @param vType procedure or function
* @param vChain string passed with this syntax dbName.tableName
* @return vHasPrivilege
*/
RETURN user_hasRoutinePriv(vType, vChain, myUser_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `passwordGenerate`() RETURNS text CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
READS SQL DATA
BEGIN
/**
* Generates a random password that meets the minimum requirements.
*
* @return Generated password
*/
DECLARE vMinLength TINYINT;
DECLARE vMinAlpha TINYINT;
DECLARE vMinUpper TINYINT;
DECLARE vMinDigits TINYINT;
DECLARE vMinPunct TINYINT;
DECLARE vAlpha TINYINT DEFAULT 0;
DECLARE vUpper TINYINT DEFAULT 0;
DECLARE vDigits TINYINT DEFAULT 0;
DECLARE vPunct TINYINT 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `user_getMysqlRole` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `user_getMysqlRole`(vUserName VARCHAR(255)) RETURNS varchar(255) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
DETERMINISTIC
BEGIN
/**
* From a username, it returns the associated MySQL wich should be used when
* using external authentication systems.
*
* @param vUserName The user name
* @return The associated MySQL role
*/
DECLARE vRole VARCHAR(255);
SELECT CONCAT(IF(r.hasLogin, c.rolePrefix, ''), r.name) INTO vRole
FROM role r
JOIN user u ON u.role = r.id
JOIN roleConfig c
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `user_getNameFromId` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `user_getNameFromId`(vSelf INT) RETURNS varchar(30) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
DETERMINISTIC
BEGIN
/**
* Gets user name from it's id.
*
* @param vSelf The user id
* @return The user name
*/
DECLARE vName VARCHAR(30);
SELECT `name` INTO vName
FROM user
WHERE id = vSelf;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `user_hasPriv` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `user_hasPriv`(vChain VARCHAR(100),
vPrivilege ENUM('SELECT','INSERT','UPDATE','DELETE'),
vUserFk INT
) RETURNS tinyint(1)
READS SQL DATA
BEGIN
/**
* Search if the user has privileges on table or column
*
* @param vChain string passed with this syntax dbName.tableName[.columnName]
* @param vPrivilege privileges to check('SELECT','INSERT','UPDATE','DELETE')
* @param vUserFk user to check
* @return vHasPrivilege
*/
DECLARE vHasPrivilege BOOL DEFAULT FALSE;
DECLARE vDb VARCHAR(50);
DECLARE vTableName VARCHAR(50);
DECLARE vColumnName VARCHAR(50);
DECLARE vPrivilegeFlag INT;
DECLARE vChainExists BOOL;
SET vDb = SUBSTRING_INDEX(vChain, '.', 1);
SET vChain = SUBSTRING(vChain, LENGTH(vDb) + 2);
IF LOCATE('.', vChain) > 0 THEN
SET vTableName = SUBSTRING_INDEX(vChain, '.', 1);
SET vColumnName = SUBSTRING(vChain, LENGTH(vTableName) + 2);
ELSE
SET vTableName = vChain;
END IF;
SELECT COUNT(*) INTO vChainExists
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = vDb
AND TABLE_NAME = vTableName
AND (COLUMN_NAME = vColumnName OR vColumnName IS NULL)
LIMIT 1;
IF NOT vChainExists THEN
RETURN FALSE;
END IF;
CASE vPrivilege
WHEN 'Select' THEN SET vPrivilegeFlag = 1;
WHEN 'Insert' THEN SET vPrivilegeFlag = 2;
WHEN 'Update' THEN SET vPrivilegeFlag = 4;
WHEN 'Delete' THEN SET vPrivilegeFlag = 8;
ELSE BEGIN END;
END CASE;
DROP TEMPORARY TABLE IF EXISTS tRole;
CREATE TEMPORARY TABLE tRole
(INDEX (`name`))
ENGINE = MEMORY
SELECT r.`name`
FROM user u
JOIN roleRole rr ON rr.role = u.role
JOIN `role` r ON r.id = rr.inheritsFrom
WHERE u.id = vUserFk;
SELECT hasPrivilege INTO vHasPrivilege
FROM (SELECT JSON_VALUE(Priv, '$.access') & vPrivilegeFlag hasPrivilege
FROM mysql.global_priv gp
JOIN tRole tr ON CONCAT(tr.name) = gp.User
HAVING hasPrivilege
LIMIT 1)sub;
IF NOT vHasPrivilege THEN
SELECT sub.privilege = 'Y' INTO vHasPrivilege
FROM
(SELECT CASE vPrivilege
WHEN 'SELECT' THEN Select_priv
WHEN 'INSERT' THEN Insert_priv
WHEN 'UPDATE' THEN Update_priv
WHEN 'DELETE' THEN Delete_priv
END privilege
FROM mysql.db db
JOIN tRole tr ON tr.name = db.User
WHERE db.Db = vDb)sub;
END IF;
IF NOT vHasPrivilege THEN
SELECT TRUE INTO vHasPrivilege
FROM tRole tr
LEFT JOIN (
SELECT User, Table_priv privilege
FROM mysql.tables_priv
WHERE Db = vDb
AND Table_name = vTableName
UNION
SELECT User, Column_priv
FROM mysql.columns_priv
WHERE Db = vDb
AND Table_name = vTableName
AND Column_name = vColumnName
)sub ON sub.`User` = tr.name
WHERE sub.privilege = vPrivilege;
END IF;
DROP TEMPORARY TABLE tRole;
RETURN vHasPrivilege;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `user_hasRole` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `user_hasRole`(vUserName VARCHAR(255), vRoleName VARCHAR(255)) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
/**
* Checks if user has/inherits a role.
*
* @param vUserName The user name
* @param vRoleName Role to check
* @return %TRUE if it has role, %FALSE otherwise
*/
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` = vUserName
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `user_hasRoleId` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `user_hasRoleId`(vUser VARCHAR(255), vRoleId INT) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
/**
* Checks if user has/inherits a role.
*
* @param vUserName The user name
* @param vRoleId Role id to check
* @return %TRUE if it has role, %FALSE otherwise
*/
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `user_hasRoutinePriv` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `user_hasRoutinePriv`(vType ENUM('PROCEDURE', 'FUNCTION'),
vChain VARCHAR(100),
vUserFk INT
) RETURNS tinyint(1)
READS SQL DATA
BEGIN
/**
* Search if the user has privileges on routines.
*
* @param vType procedure or function
* @param vChain string passed with this syntax dbName.tableName
* @param vUserFk user to ckeck
* @return vHasPrivilege
*/
DECLARE vHasPrivilege BOOL DEFAULT FALSE;
DECLARE vDb VARCHAR(50);
DECLARE vObject VARCHAR(50);
DECLARE vChainExists BOOL;
DECLARE vExecutePriv INT DEFAULT 262144;
-- 262144 = CONV(1000000000000000000, 2, 10)
-- 1000000000000000000 execution permission expressed in binary base
SET vDb = SUBSTRING_INDEX(vChain, '.', 1);
SET vChain = SUBSTRING(vChain, LENGTH(vDb) + 2);
SET vObject = SUBSTRING_INDEX(vChain, '.', 1);
SELECT COUNT(*) INTO vChainExists
FROM mysql.proc
WHERE db = vDb
AND `name` = vObject
AND `type` = vType
LIMIT 1;
IF NOT vChainExists THEN
RETURN FALSE;
END IF;
DROP TEMPORARY TABLE IF EXISTS tRole;
CREATE TEMPORARY TABLE tRole
(INDEX (`name`))
ENGINE = MEMORY
SELECT r.`name`
FROM user u
JOIN roleRole rr ON rr.role = u.role
JOIN `role` r ON r.id = rr.inheritsFrom
WHERE u.id = vUserFk;
SELECT TRUE INTO vHasPrivilege
FROM mysql.global_priv gp
JOIN tRole tr ON tr.name = gp.`User`
OR CONCAT('$', tr.name) = gp.`User`
WHERE JSON_VALUE(gp.Priv, '$.access') >= vExecutePriv
AND gp.Host = ''
LIMIT 1;
IF NOT vHasPrivilege THEN
SELECT TRUE INTO vHasPrivilege
FROM mysql.db db
JOIN tRole tr ON tr.name = db.`User`
WHERE db.Db = vDb
AND db.Execute_priv = 'Y';
END IF;
IF NOT vHasPrivilege THEN
SELECT TRUE INTO vHasPrivilege
FROM mysql.procs_priv pp
JOIN tRole tr ON tr.name = pp.`User`
WHERE pp.Db = vDb
AND pp.Routine_name = vObject
AND pp.Routine_type = vType
AND pp.Proc_priv = 'Execute'
LIMIT 1;
END IF;
DROP TEMPORARY TABLE tRole;
RETURN vHasPrivilege;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `account_enable` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `account_enable`(vSelf INT)
BEGIN
/**
* Enables an account and sets up email configuration.
*/
UPDATE user
SET active = TRUE
WHERE id = vSelf;
INSERT IGNORE INTO account
SET id = vSelf;
INSERT IGNORE INTO mailAliasAccount (mailAlias, account)
SELECT id, vSelf
FROM mailAlias
WHERE alias = 'general';
INSERT IGNORE INTO mailForward (account, forwardTo)
SELECT vSelf, email
FROM 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 */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myUser_login` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myUser_login`(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 myUser_loginWithName (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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myUser_loginWithKey` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myUser_loginWithKey`(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 myUser_loginWithName(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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myUser_loginWithName` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myUser_loginWithName`(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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myUser_logout` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myUser_logout`()
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `role_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `role_checkName`(vRoleName VARCHAR(255))
BEGIN
/**
* Checks that role name meets the necessary syntax requirements, otherwise it
* throws an exception.
* Role name must be written in camelCase.
*
* @param vRoleName The role name
*/
IF BINARY vRoleName NOT REGEXP '^[a-z][a-zA-Z]+$' THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Role name must be written in camelCase';
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `role_getDescendents`(vSelf INT)
BEGIN
/**
* Gets the identifiers of all the subroles implemented by a role (Including
* itself).
*
* @param vSelf The role identifier
* @table tmp.role Subroles implemented by the role
*/
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 t
JOIN role r ON r.id = t.id
WHERE r.`name` = 'root';
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `role_sync`()
BEGIN
/**
* Synchronize the @roleRole table with the current role hierarchy. This
* procedure must be called every time the @roleInherit table is modified so
* that the changes made on it are effective.
*/
DECLARE vRoleId INT;
DECLARE vDone BOOL;
DECLARE cur CURSOR FOR
SELECT id FROM role;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DROP TEMPORARY TABLE IF EXISTS tRoleRole;
CREATE TEMPORARY TABLE tRoleRole
ENGINE = MEMORY
SELECT * FROM roleRole LIMIT 0;
OPEN cur;
l: LOOP
SET vDone = FALSE;
FETCH cur INTO vRoleId;
IF vDone THEN
LEAVE l;
END IF;
CALL role_getDescendents(vRoleId);
INSERT INTO tRoleRole (role, inheritsFrom)
SELECT vRoleId, id FROM tmp.role;
DROP TEMPORARY TABLE tmp.role;
END LOOP;
CLOSE cur;
START TRANSACTION;
DELETE FROM roleRole;
INSERT INTO roleRole SELECT * FROM tRoleRole;
COMMIT;
DROP TEMPORARY TABLE tRoleRole;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `role_syncPrivileges`()
BEGIN
/**
* Synchronizes permissions of MySQL role users based on role hierarchy.
* The computed role users of permission mix will be named according to
* pattern [vGenRolePrefix][roleName].
*
* If [vTplUser]@[vRoleHost] user exists, it will be taken as a template for
* basic attributes.
*
* Warning! This procedure should only be called when MySQL privileges
* are modified. If role hierarchy is modified, you must call the role_sync()
* procedure wich calls this internally.
*/
DECLARE vIsMariaDb BOOL DEFAULT VERSION() LIKE '%MariaDB%';
DECLARE vVersion INT DEFAULT SUBSTRING_INDEX(VERSION(), '.', 1);
DECLARE vTplUser VARCHAR(255);
DECLARE vRoleHost VARCHAR(255);
DECLARE vUserPrefix VARCHAR(2);
DECLARE vUserHost VARCHAR(255);
DECLARE vGenRolePrefix VARCHAR(2);
DECLARE vGenRoleHost VARCHAR(255);
DECLARE vPrefixedLike VARCHAR(255);
DECLARE vPassword VARCHAR(255) DEFAULT '';
SELECT rolePrefix, userPrefix, userHost, tplUser
INTO vGenRolePrefix, vUserPrefix, vUserHost, vTplUser
FROM roleConfig;
-- Deletes computed role users
SET vPrefixedLike = CONCAT(vGenRolePrefix, '%');
SET vGenRoleHost = vUserHost;
IF vIsMariaDb THEN
SET vRoleHost = '';
DELETE FROM mysql.global_priv
WHERE `User` LIKE vPrefixedLike;
DELETE FROM mysql.roles_mapping
WHERE `User` LIKE vPrefixedLike
OR (
`Role` LIKE vPrefixedLike
AND (`User`, `Host`) = ('root', 'localhost')
);
ELSE
SET vRoleHost = 'localhost';
DELETE FROM mysql.user
WHERE `User` LIKE vPrefixedLike;
END IF;
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;
-- Temporary tables
DROP TEMPORARY TABLE IF EXISTS tRole;
CREATE TEMPORARY TABLE tRole
(INDEX (id))
ENGINE = MEMORY
SELECT
id,
`name` `role`,
CONCAT(vGenRolePrefix, `name`) prefixedRole
FROM `role`
WHERE hasLogin;
-- Get role inheritance
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
JOIN mysql.`user` u
ON u.`User` = ri.`name` AND u.`Host` = vRoleHost;
-- Recreate role users
IF vIsMariaDb THEN
-- Roles
INSERT INTO mysql.global_priv (`Host`, `User`, `Priv`)
SELECT vRoleHost, prefixedRole,
JSON_OBJECT(
'is_role', TRUE,
'access', 0
)
FROM tRole r
UNION
SELECT vRoleHost, CONCAT(vGenRolePrefix, 'root'),
JSON_OBJECT(
'is_role', TRUE,
'access', 0
);
INSERT INTO mysql.roles_mapping (`Host`, `User`, `Role`, `Admin_option`)
SELECT vRoleHost, prefixedRole, inheritsFrom, 'N'
FROM tRoleInherit
UNION
SELECT vRoleHost, CONCAT(vGenRolePrefix, 'root'), prefixedRole, 'Y'
FROM tRole;
INSERT INTO mysql.roles_mapping (`Host`, `User`, `Role`, `Admin_option`)
SELECT 'localhost', 'root', prefixedRole, 'Y'
FROM tRole
UNION
SELECT 'localhost', 'root', CONCAT(vGenRolePrefix, 'root'), 'Y';
-- Role users
INSERT INTO mysql.global_priv (
`User`,
`Host`,
`Priv`
)
SELECT
r.prefixedRole,
vGenRoleHost,
JSON_MERGE_PATCH(
IFNULL(t.`Priv`, '{}'),
IFNULL(u.`Priv`, '{}'),
JSON_OBJECT(
'mysql_old_password', JSON_VALUE(t.`Priv`, '$.mysql_old_password'),
'mysql_native_password', JSON_VALUE(t.`Priv`, '$.mysql_native_password'),
'authentication_string', JSON_VALUE(t.`Priv`, '$.authentication_string'),
'ssl_type', JSON_VALUE(t.`Priv`, '$.ssl_type'),
'default_role', r.prefixedRole,
'access', 0,
'is_role', FALSE
)
)
FROM tRole r
LEFT JOIN mysql.global_priv t
ON (t.`User`, t.Host) = (vTplUser, vRoleHost)
LEFT JOIN mysql.global_priv u
ON (u.`User`, u.Host) = (r.`role`, vRoleHost);
INSERT INTO mysql.roles_mapping (`Host`, `User`, `Role`, `Admin_option`)
SELECT vGenRoleHost, prefixedRole, prefixedRole, 'N'
FROM tRole;
-- Accounts
DROP TEMPORARY TABLE IF EXISTS tAccounts;
CREATE TEMPORARY TABLE tAccounts
(INDEX (`name`))
ENGINE = MEMORY
SELECT p.`User` `name`, r.prefixedRole
FROM mysql.global_priv p
JOIN `user` u ON u.`name` = p.`User`
JOIN tRole r ON r.`id` = u.`role`
WHERE JSON_EXTRACT(p.`Priv`, '$.autogenerated') = 'true';
UPDATE mysql.global_priv p
JOIN tAccounts c ON c.`name` = p.`User`
SET p.`Priv` = JSON_SET(p.`Priv`, '$.default_role', c.prefixedRole)
WHERE p.`Host` = vUserHost;
UPDATE IGNORE mysql.roles_mapping m
JOIN tAccounts c ON c.`name` = m.`User`
SET m.`Role` = c.prefixedRole
WHERE m.`Host` = vUserHost;
DROP TEMPORARY TABLE tAccounts;
ELSE
DROP TEMPORARY TABLE IF EXISTS tUser;
CREATE TEMPORARY TABLE tUser
SELECT
r.prefixedRole `User`,
vGenRoleHost `Host`,
IFNULL(t.`authentication_string`,
'') `authentication_string`,
IFNULL(t.`plugin`,
'mysql_native_password') `plugin`,
IFNULL(IF('' != u.`ssl_type`,
u.`ssl_type`, t.`ssl_type`),
'') `ssl_type`,
IFNULL(IF('' != u.`ssl_cipher`,
u.`ssl_cipher`, t.`ssl_cipher`),
'') `ssl_cipher`,
IFNULL(IF('' != u.`x509_issuer`,
u.`x509_issuer`, t.`x509_issuer`),
'') `x509_issuer`,
IFNULL(IF('' != u.`x509_subject`,
u.`x509_subject`, t.`x509_subject`),
'') `x509_subject`,
IFNULL(IF(0 != u.`max_questions`,
u.`max_questions`, t.`max_questions`),
0) `max_questions`,
IFNULL(IF(0 != u.`max_updates`,
u.`max_updates`, t.`max_updates`),
0) `max_updates`,
IFNULL(IF(0 != u.`max_connections`,
u.`max_connections`, t.`max_connections`),
0) `max_connections`,
IFNULL(IF(0 != u.`max_user_connections`,
u.`max_user_connections`, t.`max_user_connections`),
0) `max_user_connections`
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;
IF vVersion <= 5 THEN
SELECT `Password` INTO vPassword
FROM mysql.user
WHERE `User` = vTplUser
AND `Host` = vRoleHost;
INSERT INTO mysql.user (
`User`,
`Host`,
`Password`,
`authentication_string`,
`plugin`,
`ssl_type`,
`ssl_cipher`,
`x509_issuer`,
`x509_subject`,
`max_questions`,
`max_updates`,
`max_connections`,
`max_user_connections`
)
SELECT
`User`,
`Host`,
vPassword,
`authentication_string`,
`plugin`,
`ssl_type`,
`ssl_cipher`,
`x509_issuer`,
`x509_subject`,
`max_questions`,
`max_updates`,
`max_connections`,
`max_user_connections`
FROM tUser;
ELSE
INSERT INTO mysql.user (
`User`,
`Host`,
`authentication_string`,
`plugin`,
`ssl_type`,
`ssl_cipher`,
`x509_issuer`,
`x509_subject`,
`max_questions`,
`max_updates`,
`max_connections`,
`max_user_connections`
)
SELECT
`User`,
`Host`,
`authentication_string`,
`plugin`,
`ssl_type`,
`ssl_cipher`,
`x509_issuer`,
`x509_subject`,
`max_questions`,
`max_updates`,
`max_connections`,
`max_user_connections`
FROM tUser;
END IF;
DROP TEMPORARY TABLE tUser;
-- Proxy privileges
INSERT INTO mysql.proxies_priv (
`User`,
`Host`,
`Proxied_user`,
`Proxied_host`,
`Grantor`
)
SELECT
'',
vUserHost,
prefixedRole,
vGenRoleHost,
CONCAT(prefixedRole, '@', vGenRoleHost)
FROM tRole;
-- Global privileges
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` = vGenRoleHost
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;
-- Schema level privileges
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,
vGenRoleHost,
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`;
-- Table level privileges
INSERT INTO mysql.tables_priv (
`User`,
`Host`,
`Db`,
`Table_name`,
`Grantor`,
`Timestamp`,
`Table_priv`,
`Column_priv`
)
SELECT
r.prefixedRole,
vGenRoleHost,
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`;
-- Column level privileges
INSERT INTO mysql.columns_priv (
`User`,
`Host`,
`Db`,
`Table_name`,
`Column_name`,
`Timestamp`,
`Column_priv`
)
SELECT
r.prefixedRole,
vGenRoleHost,
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`;
-- Routine privileges
INSERT IGNORE INTO mysql.procs_priv (
`User`,
`Host`,
`Db`,
`Routine_name`,
`Routine_type`,
`Grantor`,
`Timestamp`,
`Proc_priv`
)
SELECT
r.prefixedRole,
vGenRoleHost,
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;
END IF;
-- Cleanup
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `user_checkName`(vUserName VARCHAR(255))
BEGIN
/**
* Checks that username meets the necessary syntax requirements, otherwise it
* throws an exception.
* The user name must only contain lowercase letters or, starting with second
* character, numbers or underscores.
*/
IF vUserName NOT REGEXP BINARY '^[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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 */ ;
--
-- Current Database: `bi`
--
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`Importe` decimal(10,2) NOT NULL,
`Fecha` datetime DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci ROW_FORMAT=COMPACT;
/*!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=utf8mb3 COLLATE=utf8mb3_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) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`Eurodebe` double DEFAULT NULL,
`Eurohaber` double DEFAULT NULL,
`Fecha` date DEFAULT NULL,
`FECHA_EX` date DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `Cuenta` (`SUBCTA`),
KEY `empresa` (`empresa_id`),
KEY `Fecha` (`Fecha`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`Reino` varchar(45) NOT NULL,
`Comercial` varchar(3) NOT NULL,
`Comprador` varchar(3) NOT NULL,
`Provincia` varchar(30) NOT NULL,
`almacen` varchar(20) NOT NULL,
`Año` smallint(5) unsigned NOT NULL,
`Mes` tinyint(3) unsigned NOT NULL,
`Semana` tinyint(3) unsigned NOT NULL,
`Vista` varchar(45) DEFAULT NULL,
`Importe` double NOT NULL,
PRIMARY KEY (`id`),
KEY `Año` (`Año`,`Semana`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) 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=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`ventas` int(11) NOT NULL,
`año` int(11) NOT NULL,
`periodo` int(11) NOT NULL,
`typeFk` smallint(5) unsigned DEFAULT NULL,
UNIQUE KEY `familia` (`familia`,`periodo`),
KEY `periodo` (`periodo`),
KEY `analisis_ventas_familia_evolution_FK` (`typeFk`),
CONSTRAINT `analisis_ventas_familia_evolution_FK` FOREIGN KEY (`typeFk`) REFERENCES `vn`.`itemType` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #5196 Deprecated 2023-06-05';
/*!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) NOT NULL,
`ventas` int(11) NOT NULL,
`año` int(11) NOT NULL,
`periodo` int(11) NOT NULL,
`countryCode` varchar(2) NOT NULL,
UNIQUE KEY `provincia` (`provincia`,`periodo`),
KEY `periodo` (`periodo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) 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=utf8mb3 COLLATE=utf8mb3_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) 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=utf8mb3 COLLATE=utf8mb3_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) 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=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
PRIMARY KEY (`calidad_parametros_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `claims_ratio`
--
DROP TABLE IF EXISTS `claims_ratio`;
/*!50001 DROP VIEW IF EXISTS `claims_ratio`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `claims_ratio` AS SELECT
1 AS `Id_Cliente`,
1 AS `Consumo`,
1 AS `Reclamaciones`,
1 AS `Ratio`,
1 AS `recobro`,
1 AS `inflacion` */;
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=utf8mb3 COLLATE=utf8mb3_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;
--
-- Temporary table structure for view `defaulters`
--
DROP TABLE IF EXISTS `defaulters`;
/*!50001 DROP VIEW IF EXISTS `defaulters`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `defaulters` AS SELECT
1 AS `client`,
1 AS `date`,
1 AS `amount`,
1 AS `defaulterSince`,
1 AS `hasChanged`,
1 AS `frozened` */;
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=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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 */;
--
-- Temporary table structure for view `facturacion_media_anual`
--
DROP TABLE IF EXISTS `facturacion_media_anual`;
/*!50001 DROP VIEW IF EXISTS `facturacion_media_anual`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `facturacion_media_anual` AS SELECT
1 AS `Id_Cliente`,
1 AS `Consumo` */;
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=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #5744 Deprecated 2023-06-06';
/*!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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`table_name` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`date_field` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`table_depending` varchar(15) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`execution_order` tinyint(3) unsigned NOT NULL,
PRIMARY KEY (`schema_name`,`table_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #5744 Deprecated 2023-06-06';
/*!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=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #5744 Deprecated 2023-06-06';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `rotacion`
--
DROP TABLE IF EXISTS `rotacion`;
/*!50001 DROP VIEW IF EXISTS `rotacion`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `rotacion` AS SELECT
1 AS `Id_Article`,
1 AS `warehouse_id`,
1 AS `total`,
1 AS `rotacion`,
1 AS `cm3`,
1 AS `almacenaje`,
1 AS `manipulacion`,
1 AS `auxiliar`,
1 AS `mermas`,
1 AS `cm3reparto`,
1 AS `grams` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `rutasBoard`
--
DROP TABLE IF EXISTS `rutasBoard`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `rutasBoard` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`Id_Ruta` int(10) unsigned NOT NULL DEFAULT 0,
`Id_Agencia` int(11) NOT NULL DEFAULT 0,
`km__` varchar(9) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
`Dia__` varchar(9) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
`Fecha` date NOT NULL,
`Terceros__` int(11) DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
`Bultos` int(11) NOT NULL DEFAULT 0,
`Matricula__` varchar(10) DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
`Tipo__` varchar(1) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
`year__` int(4) DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
`month__` int(2) DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
`warehouse_id__` smallint(5) unsigned DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
`coste_bulto__` decimal(10,2) unsigned DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
`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,
`m3__` decimal(10,1) unsigned DEFAULT NULL COMMENT '@deprecated 2023-11-01, refs #6087',
PRIMARY KEY (`id`),
UNIQUE KEY `rutasBoard_Ruta` (`Id_Ruta`),
KEY `rutasBoard_ix1` (`year__`),
KEY `rutasBoard_ix2` (`month__`),
KEY `rutasBoard_ix3` (`warehouse_id__`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Se usa en https://grafana.verdnatura.es/d/c089276b-5ab5-430f-aa76-e5d8e0e7fe2e/analisis-de-volumen-y-rendimiento-por-agencia?orgId=1';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `tarifa_componentes`
--
DROP TABLE IF EXISTS `tarifa_componentes`;
/*!50001 DROP VIEW IF EXISTS `tarifa_componentes`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `tarifa_componentes` AS SELECT
1 AS `Id_Componente`,
1 AS `Componente`,
1 AS `tarifa_componentes_series_id`,
1 AS `tarifa_class`,
1 AS `tax`,
1 AS `is_renewable`,
1 AS `code` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `tarifa_componentes_series`
--
DROP TABLE IF EXISTS `tarifa_componentes_series`;
/*!50001 DROP VIEW IF EXISTS `tarifa_componentes_series`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `tarifa_componentes_series` AS SELECT
1 AS `tarifa_componentes_series_id`,
1 AS `Serie`,
1 AS `base`,
1 AS `margen` */;
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) NOT NULL,
PRIMARY KEY (`Id_Premisa`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #5744 Deprecated 2023-06-06';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `tarifa_warehouse__`
--
DROP TABLE IF EXISTS `tarifa_warehouse__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tarifa_warehouse__` (
`Id_Tarifa_Warehouse` int(11) NOT NULL AUTO_INCREMENT,
`warehouse_id` int(11) NOT NULL,
`Id_Premisa` int(11) NOT NULL,
`Valor` double NOT NULL,
PRIMARY KEY (`Id_Tarifa_Warehouse`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #5744 Deprecated 2023-06-06\nAlmacena 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `analisis_ventas_evolution_add`()
BEGIN
DECLARE vPreviousPeriod INT;
DECLARE vCurrentPeriod INT;
DECLARE vLastPeriod INT;
DECLARE vMinPeriod INT DEFAULT 201400;
DECLARE vMaxPeriod INT;
DECLARE vYear INT;
DECLARE vWeek INT;
SELECT t.period INTO vMaxPeriod
FROM vn.`time` t
WHERE t.dated = util.VN_CURDATE();
-- Almacen
SET vCurrentPeriod = IFNULL(vLastPeriod, vMinPeriod);
WHILE vCurrentPeriod < vMaxPeriod
DO
SELECT MAX(Periodo) INTO vPreviousPeriod
FROM analisis_ventas_almacen_evolution
WHERE Periodo < vMaxPeriod;
SELECT MIN(period) INTO vCurrentPeriod
FROM vn.time
WHERE period > vPreviousPeriod;
SET vYear = FLOOR(vCurrentPeriod / 100);
SET vWeek = vCurrentPeriod - (vYear * 100);
DELETE FROM analisis_ventas_almacen_evolution
WHERE Periodo = vCurrentPeriod;
REPLACE 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 analisis_ventas
WHERE vYear = Año
AND vWeek = Semana
GROUP BY almacen
UNION ALL
SELECT almacen, - SUM(Importe) AS Ventas
FROM analisis_ventas
WHERE vYear - 1 = Año
AND vWeek = Semana
GROUP BY almacen
UNION ALL
SELECT Almacen, Ventas
FROM 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 analisis_ventas_reino_evolution
WHERE periodo < vMaxPeriod;
SELECT MIN(period) INTO vCurrentPeriod
FROM vn.time
WHERE period > vPreviousPeriod;
SET vYear = FLOOR(vCurrentPeriod / 100);
SET vWeek = vCurrentPeriod - (vYear * 100);
DELETE FROM analisis_ventas_reino_evolution
WHERE Periodo = vCurrentPeriod;
REPLACE 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 analisis_ventas
WHERE vYear = Año
AND vWeek = Semana
GROUP BY Reino
UNION ALL
SELECT Reino, - SUM(Importe) AS ventas
FROM analisis_ventas
WHERE vYear - 1 = Año
AND vWeek = Semana
GROUP BY Reino
UNION ALL
SELECT reino, ventas
FROM analisis_ventas_reino_evolution
WHERE Periodo = vPreviousPeriod
) sub
GROUP BY reino;
END WHILE;
-- Provincia
SET vCurrentPeriod = vMinPeriod;
WHILE vCurrentPeriod < vMaxPeriod
DO
SELECT MAX(periodo) INTO vPreviousPeriod
FROM analisis_ventas_provincia_evolution
WHERE periodo < vMaxPeriod;
SELECT MIN(period) INTO vCurrentPeriod
FROM vn.time
WHERE period > vPreviousPeriod;
SET vYear = FLOOR(vCurrentPeriod / 100);
SET vWeek = vCurrentPeriod - (vYear * 100);
DELETE FROM analisis_ventas_provincia_evolution
WHERE Periodo = vCurrentPeriod;
REPLACE analisis_ventas_provincia_evolution(provincia, countryCode, ventas, semana,año, periodo)
SELECT Provincia, code, SUM(ventas) AS ventas, vWeek, vYear, vCurrentPeriod
FROM (
SELECT a.Provincia, c.code, SUM(a.Importe) AS ventas
FROM analisis_ventas a
JOIN vn.province p ON p.name= a.provincia
JOIN vn.country c ON c.id = p.countryFk
WHERE vYear = a.Año
AND vWeek = a.Semana
GROUP BY a.Provincia
UNION ALL
SELECT a.Provincia, c.code, - SUM(a.Importe) AS ventas
FROM analisis_ventas a
JOIN vn.province p ON p.name= a.provincia
JOIN vn.country c ON c.id = p.countryFk
WHERE vYear - 1 = a.Año
AND vWeek = a.Semana
GROUP BY a.Provincia
UNION ALL
SELECT a.provincia,a.countryCode, a.ventas
FROM analisis_ventas_provincia_evolution a
WHERE a.Periodo = vPreviousPeriod
) sub
GROUP BY Provincia;
END WHILE;
-- Vista
SET vCurrentPeriod = vMinPeriod;
WHILE vCurrentPeriod < vMaxPeriod
DO
SELECT MAX(periodo) INTO vPreviousPeriod
FROM analisis_ventas_vista_evolution
WHERE periodo < vMaxPeriod;
SELECT MIN(period) INTO vCurrentPeriod
FROM vn.time
WHERE period > vPreviousPeriod;
SET vYear = FLOOR(vCurrentPeriod / 100);
SET vWeek = vCurrentPeriod - (vYear * 100);
DELETE FROM analisis_ventas_vista_evolution
WHERE Periodo = vCurrentPeriod;
REPLACE 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 analisis_ventas
WHERE vYear = Año
AND vWeek = Semana
GROUP BY Vista
UNION ALL
SELECT Vista, - SUM(Importe) AS ventas
FROM analisis_ventas
WHERE vYear - 1 = Año
AND vWeek = Semana
GROUP BY Vista
UNION ALL
SELECT vista, ventas
FROM 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 analisis_ventas_vendedor_evolution
WHERE periodo < vMaxPeriod;
SELECT MIN(period) INTO vCurrentPeriod
FROM vn.time
WHERE period > vPreviousPeriod;
SET vYear = FLOOR(vCurrentPeriod / 100);
SET vWeek = vCurrentPeriod - (vYear * 100);
DELETE FROM analisis_ventas_vendedor_evolution
WHERE Periodo = vCurrentPeriod;
REPLACE 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 analisis_ventas
WHERE vYear = Año
AND vWeek = Semana
GROUP BY Comercial
UNION ALL
SELECT Comercial, - SUM(Importe) AS ventas
FROM analisis_ventas
WHERE vYear - 1 = Año
AND vWeek = Semana
GROUP BY Comercial
UNION ALL
SELECT vendedor, ventas
FROM 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `analisis_ventas_simple`()
BEGIN
/**
* Vacia y rellena la tabla 'analisis_grafico_simple' desde 'analisis_grafico_ventas'
*/
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `analisis_ventas_update`()
BEGIN
DECLARE vLastMonth DATE;
SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, util.VN_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
it.name,
ic.name,
w.code,
w2.code,
p.name,
wa.name,
tm.year,
tm.month,
tm.week,
dm.description,
bt.importe
FROM bs.ventas bt
LEFT JOIN vn.itemType it ON it.id = bt.tipo_id
LEFT JOIN vn.itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN vn.client c on c.id = bt.Id_Cliente
LEFT JOIN vn.worker w ON w.id = c.salesPersonFk
LEFT JOIN vn.worker w2 ON w2.id = it.workerFk
JOIN vn.time tm ON tm.dated = bt.fecha
JOIN vn.sale s ON s.id = bt.Id_Movimiento
LEFT JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.agencyMode am ON am.id = t.agencyModeFk
LEFT JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk
LEFT JOIN vn.address a ON a.id = t.addressFk
LEFT JOIN vn.province p ON p.id = a.provinceFk
LEFT JOIN vn.warehouse wa ON wa.id = t.warehouseFk
WHERE bt.fecha >= vLastMonth AND ic.merchandise;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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
*/
-- Reclamaciones demasiado sensibles
INSERT INTO vn.greuge(shipped, clientFk, description,
amount, greugeTypeFk, ticketFk)
SELECT c.ticketCreated
, c.clientFk
, concat('Claim ', c.id,' : ', s.concept)
,round( -1 * ((c.responsibility -1)/4) * s.quantity *
s.price * (100 - s.discount) / 100, 2)
, 4
, s.ticketFk
FROM vn.sale s
JOIN vn.claimEnd ce ON ce.saleFk = s.id
JOIN vn.claim c ON c.id = ce.claimFk
WHERE ce.claimDestinationFk NOT IN (1,5)
AND NOT ce.isGreuge
AND c.claimStateFk = 3;
-- Reclamaciones que pasan a Maná
INSERT INTO vn.greuge(shipped, clientFk, description,
amount, greugeTypeFk, ticketFk)
SELECT c.ticketCreated
, c.clientFk
, concat('Claim_mana ',c.id,' : ', s.concept)
,round( ((c.responsibility -1)/4) * s.quantity * s.price * (100 - s.discount) / 100, 2)
,3
,s.ticketFk
FROM vn.sale s
JOIN vn.claimEnd ce ON ce.saleFk = s.id
JOIN vn.claim c ON c.id = ce.claimFk
WHERE ce.claimDestinationFk NOT IN (1,5)
AND NOT ce.isGreuge
AND c.claimStateFk = 3
AND c.isChargedToMana;
-- Marcamos para no repetir
UPDATE vn.claimEnd ce
JOIN vn.claim c ON c.id = ce.claimFk
SET c.isChargedToMana = TRUE
WHERE ce.claimDestinationFk NOT IN (1,5)
AND NOT ce.isGreuge
AND c.claimStateFk = 3;
-- Recobros
DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list;
CREATE TEMPORARY TABLE tmp.ticket_list
(PRIMARY KEY (Id_Ticket))
SELECT DISTINCT t.id Id_Ticket
FROM vn.saleComponent sc
JOIN vn.sale s ON sc.saleFk = s.id
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.ticketLastState ts ON ts.ticketFk = t.id
JOIN vn.ticketTracking tt ON tt.id = ts.ticketTrackingFk
JOIN vn.state st ON st.id = tt.stateFk
WHERE sc.componentFk = 17
AND sc.isGreuge = 0
AND t.shipped >= '2016-10-01'
AND t.shipped < util.VN_CURDATE()
AND st.alertLevel >= 3;
DELETE g.*
FROM vn.greuge g
JOIN tmp.ticket_list t ON g.ticketFk = t.Id_Ticket
WHERE g.greugeTypeFk = 2;
INSERT INTO vn.greuge(clientFk, description, amount,shipped,
greugeTypeFk, ticketFk)
SELECT t.clientFk
,concat('recobro ', s.ticketFk), - round(SUM(sc.value*s.quantity),2)
AS dif,
date(t.shipped)
, 2
,tt.Id_Ticket
FROM vn.sale s
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.id
JOIN vn.saleComponent sc
ON sc.saleFk = s.id AND sc.componentFk = 17
GROUP BY t.id
HAVING ABS(dif) > 1;
UPDATE vn.saleComponent sc
JOIN vn.sale s ON s.id = sc.saleFk
JOIN tmp.ticket_list tt ON tt.Id_Ticket = s.ticketFk
SET sc.isGreuge = 1
WHERE sc.componentFk = 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, 0,0,0,0
FROM vn.client;
REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro)
SELECT fm.Id_Cliente, 12 * fm.Consumo, Reclamaciones,
round(Reclamaciones / (12*fm.Consumo),4), 0
FROM bi.facturacion_media_anual fm
LEFT JOIN(
SELECT c.clientFk, round(sum(-1 * ((c.responsibility -1)/4) *
s.quantity * s.price * (100 - s.discount) / 100))
AS Reclamaciones
FROM vn.sale s
JOIN vn.claimEnd ce ON ce.saleFk = s.id
JOIN vn.claim c ON c.id = ce.claimFk
WHERE ce.claimDestinationFk NOT IN (1,5)
AND c.claimStateFk = 3
AND c.ticketCreated >= TIMESTAMPADD(YEAR, -1, util.VN_CURDATE())
GROUP BY c.clientFk
) claims ON claims.clientFk = fm.Id_Cliente;
-- Calculamos el porcentaje del recobro para añadirlo al precio de venta
UPDATE bi.claims_ratio cr
JOIN (
SELECT clientFk Id_Cliente, IFNULL(SUM(amount), 0) AS Greuge
FROM vn.greuge
WHERE shipped <= util.VN_CURDATE()
GROUP BY clientFk
) g ON g.Id_Cliente = cr.Id_Cliente
SET recobro = GREATEST(0,round(IFNULL(Greuge, 0) /
(IFNULL(Consumo, 0) * 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,util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`()
BEGIN
DECLARE vDateShort DATETIME;
DECLARE vDateLong DATETIME;
DECLARE vOneYearAgo DATETIME;
SET vDateShort = TIMESTAMPADD(MONTH, -2, util.VN_CURDATE());
SET vDateLong = TIMESTAMPADD(MONTH, -18,util.VN_CURDATE());
SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,util.VN_CURDATE());
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `defaultersFromDate`(IN vDate DATE)
BEGIN
SELECT t1.*, c.name Cliente, w.code workerCode, c.payMethodFk pay_met_id, c.dueDay 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 vn.client c ON c.id = t1.client
left join vn.worker w ON w.id = c.salesPersonFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `defaulting` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `defaulting`(IN `vDate` DATE)
BEGIN
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 d.client, d.amount, pm.graceDays
FROM bi.defaulters d
JOIN vn.client c ON c.id = d.client
JOIN vn.payMethod pm ON pm.id = c.payMethodFk
WHERE hasChanged AND date = vDate;
DECLARE invoices CURSOR FOR
SELECT dued Vencimiento, amount importe FROM vn.invoiceOut
WHERE issued >= '2016-01-01' AND clientFk = vClient ORDER BY issued 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 c.id, vDate, IFNULL(FLOOR(SUM(cro.amount)),0) AS amount
FROM vn.`client` c
LEFT JOIN bi.customerRiskOverdue cro ON c.id = cro.customer_id
GROUP BY c.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
LIMIT 10000000000000000000) t GROUP BY client
) yesterday using(client)
SET d.hasChanged = (IFNULL(d.amount,0) <> IFNULL(yesterday.amount,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;
DELETE FROM defaulters
WHERE amount = 0
AND hasChanged = FALSE
AND `date` = vDate;
UPDATE defaulters d
JOIN vn.config ON TRUE
SET d.frozened = NULL
WHERE `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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `defaulting_launcher`()
BEGIN
/**
* Calcula la morosidad de los clientes.
*/
CALL bi.defaulting(util.VN_CURDATE());
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `facturacion_media_anual_update`()
BEGIN
TRUNCATE TABLE bs.clientAnnualConsumption;
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,util.VN_CURDATE()) AND TIMESTAMPADD(DAY, - DAY(util.VN_CURDATE()),util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `greuge_dif_porte_add`()
BEGIN
/**
* Calculates the greuge based on a specific date in the 'grievanceConfig' table
*/
DECLARE vDateStarted DATETIME;
DECLARE vDateEnded DATETIME DEFAULT (util.VN_CURDATE() - INTERVAL 1 DAY);
DECLARE vDaysAgoOffset INT;
SELECT daysAgoOffset INTO vDaysAgoOffset
FROM vn.greugeConfig;
SET vDateStarted = util.VN_CURDATE() - INTERVAL vDaysAgoOffset DAY;
DROP TEMPORARY TABLE IF EXISTS tmp.dp;
-- Agencias que no cobran por volumen
CREATE TEMPORARY TABLE tmp.dp
(PRIMARY KEY (ticketFk))
ENGINE = MEMORY
SELECT t.id ticketFk,
SUM((t.zonePrice - t.zoneBonus) * ebv.ratio) teorico,
00000.00 practico,
00000.00 greuge,
t.clientFk,
t.shipped
FROM vn.ticket t
JOIN vn.client c ON c.id = t.clientFk
LEFT JOIN vn.expedition e ON e.ticketFk = t.id
JOIN vn.expeditionBoxVol ebv ON ebv.boxFk = e.freightItemFk
JOIN vn.zone z ON t.zoneFk = z.id
JOIN vn.company cp ON cp.id = t.companyFk
WHERE t.shipped BETWEEN vDateStarted AND vDateEnded
AND c.isRelevant
AND cp.code IN ('VNL', 'VNH')
AND NOT z.isVolumetric
GROUP BY t.id;
-- Agencias que cobran por volumen
INSERT INTO tmp.dp
SELECT sv.ticketFk,
SUM(IFNULL(sv.freight,0)) teorico,
00000.00 practico,
00000.00 greuge,
sv.clientFk,
sv.shipped
FROM vn.saleVolume sv
JOIN vn.zone z ON z.id = sv.zoneFk
AND sv.shipped BETWEEN vDateStarted AND vDateEnded
AND z.isVolumetric != FALSE
GROUP BY sv.ticketFk;
DROP TEMPORARY TABLE IF EXISTS tmp.dp_aux;
CREATE TEMPORARY TABLE tmp.dp_aux
(PRIMARY KEY (ticketFk))
ENGINE = MEMORY
SELECT dp.ticketFk, SUM(s.quantity * sc.value) valor
FROM tmp.dp
JOIN vn.sale s ON s.ticketFk = dp.ticketFk
JOIN vn.saleComponent sc ON sc.saleFk = s.id
JOIN vn.component c ON c.id = sc.componentFk
WHERE c.code = 'delivery'
GROUP BY dp.ticketFk;
UPDATE tmp.dp
JOIN tmp.dp_aux USING(ticketFk)
SET practico = IFNULL(valor,0);
DROP TEMPORARY TABLE tmp.dp_aux;
CREATE TEMPORARY TABLE tmp.dp_aux
(PRIMARY KEY (ticketFk))
ENGINE = MEMORY
SELECT dp.ticketFk, SUM(g.amount) Importe
FROM tmp.dp
JOIN vn.greuge g ON g.ticketFk = dp.ticketFk
JOIN vn.greugeType gt ON gt.id = g.greugeTypeFk
WHERE gt.code = 'freightDifference' -- dif_porte
GROUP BY dp.ticketFk;
UPDATE tmp.dp
JOIN tmp.dp_aux USING(ticketFk)
SET greuge = IFNULL(Importe,0);
INSERT INTO vn.greuge (clientFk,description,amount,shipped,greugeTypeFk,ticketFk)
SELECT dp.clientFk,
CONCAT('dif_porte ', dp.ticketFk),
ROUND(IFNULL(dp.teorico,0) - IFNULL(dp.practico,0) - IFNULL(dp.greuge,0),2) Importe,
date(dp.shipped),
1,
dp.ticketFk
FROM tmp.dp
JOIN vn.client c ON c.id = dp.clientFk
WHERE ABS(IFNULL(dp.teorico,0) - IFNULL(dp.practico,0) - IFNULL(dp.greuge,0)) > 1
AND c.isRelevant;
DROP TEMPORARY TABLE
tmp.dp,
tmp.dp_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `Greuge_Evolution_Add` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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'));
CALL vn.mail_insert(
'jgallego@verdnatura.es,pako@verdnatura.es',
'noreply@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,util.VN_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 clientFk Id_Cliente, max(issued) as maxFecha
FROM vn.invoiceOut
GROUP BY clientFk
HAVING maxFecha < timestampadd(month,-2,datFEC);
WHILE datFEC < util.VN_CURDATE() DO
REPLACE bi.Greuge_Evolution(Id_Cliente, Fecha, Greuge, Ventas, Fosil)
SELECT Id_Cliente, datFEC as Fecha, Greuge, Ventas, 0
FROM (
SELECT clientFk Id_Cliente, sum(amount) as Greuge
FROM vn.greuge
where shipped <= datFEC
group by clientFk
) 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 a.clientFk Id_Cliente, sum(sc.value * s.quantity) as Importe
FROM vn.ticket t
JOIN vn.address a on a.id = t.addressFk
JOIN vn.sale s on s.ticketFk = t.id
JOIN vn.saleComponent sc on sc.saleFk = s.id
WHERE t.shipped >= datFEC
AND t.shipped < datFEC_TOMORROW
AND sc.componentFk = 17 -- Recobro
GROUP BY a.clientFk
) 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `rutasAnalyze`(
vDatedFrom DATE,
vDatedTo DATE
)
BEGIN
/**
* Analiza los costes de las rutas de reparto
* y lo almacena en la tabla bi.rutasBoard
*/
DELETE FROM rutasBoard
WHERE Fecha BETWEEN vDatedFrom AND vDatedTo;
-- Rellenamos la tabla con los datos de las rutas VOLUMETRICAS, especialmente con los bultos "virtuales"
INSERT INTO rutasBoard(
Id_Ruta,
Id_Agencia,
Fecha,
bultos)
SELECT r.id,
r.agencyModeFk,
r.created,
SUM(sv.volume / ebv.m3)
FROM vn.route r
JOIN vn.ticket t ON t.routeFk = r.id
LEFT JOIN vn.`zone` z ON z.id = t.zoneFk
JOIN vn.saleVolume sv ON sv.ticketFk = t.id
JOIN vn.expeditionBoxVol ebv ON ebv.code = 'transportBox'
WHERE r.created BETWEEN vDatedFrom AND vDatedTo
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 rutasBoard(
Id_Ruta,
Id_Agencia,
Fecha,
Bultos)
SELECT r.id,
r.agencyModeFk,
r.created,
SUM(t.packages)
FROM vn.route r
JOIN vn.ticket t ON t.routeFk = r.id
LEFT JOIN vn.`zone` z ON z.id = t.zoneFk
WHERE r.created BETWEEN vDatedFrom AND vDatedTo
AND NOT z.isVolumetric
GROUP BY r.id
ON DUPLICATE KEY UPDATE Bultos = Bultos + VALUES(Bultos);
-- Coste PRACTICO de cada bulto, de acuerdo con los componentes de tipo AGENCIA en cada linea de venta
UPDATE rutasBoard r
JOIN (
SELECT t.routeFk,
SUM(s.quantity * sc.value) totalPractice
FROM vn.route r
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.code = 'FREIGHT'
AND r.created BETWEEN vDatedFrom AND vDatedTo
GROUP BY r.id
) sub ON sub.routeFk = r.Id_Ruta
SET r.practico = IFNULL(sub.totalPractice / r.Bultos, 0);
-- Coste TEORICO de una caja "virtual" para cada ruta, teniendo en cuenta que hay carros, pallets, etc
UPDATE rutasBoard r
JOIN (
SELECT t.routeFk,
SUM(t.zonePrice/ ebv.ratio) / COUNT(*) averageTheoreticalVolume
FROM vn.ticket t
JOIN vn.route r ON r.id = t.routeFk
JOIN vn.expedition e ON e.ticketFk = t.id
JOIN vn.expeditionBoxVol ebv ON ebv.boxFk = e.freightItemFk
JOIN vn.address ad ON ad.id = t.addressFk
JOIN vn.client c ON c.id = ad.clientFk
LEFT JOIN vn.`zone` z ON z.id = t.zoneFk
WHERE r.created BETWEEN vDatedFrom AND vDatedTo
AND NOT z.isVolumetric
GROUP BY t.routeFk
) sub ON r.Id_Ruta = sub.routeFk
SET r.teorico = IFNULL(sub.averageTheoreticalVolume, 0);
-- Coste VOLUMETRICO TEORICO de una caja "virtual" para cada ruta
UPDATE rutasBoard r
JOIN (
SELECT t.routeFk,
SUM(freight) averageTheoreticalVolume
FROM vn.ticket t
JOIN vn.route r ON r.id = t.routeFk
JOIN vn.saleVolume sf ON sf.ticketFk = t.id
JOIN vn.client c ON c.id = t.clientFk
JOIN vn.`zone` z ON z.id = t.zoneFk
WHERE r.created BETWEEN vDatedFrom AND vDatedTo
AND z.isVolumetric
GROUP BY t.routeFk
) sub ON r.Id_Ruta = sub.routeFk
SET r.teorico = IFNULL(sub.averageTheoreticalVolume / r.Bultos, 0);
-- La diferencia entre el teorico y el practico se deberia de cobrar en greuges, cada noche
UPDATE rutasBoard r
JOIN (
SELECT t.routeFk,
SUM(g.amount) greuge
FROM vn.ticket t
JOIN vn.route r ON r.id = t.routeFk
JOIN vn.greuge g ON g.ticketFk = t.id
JOIN vn.greugeType gt ON gt.id = g.greugeTypeFk
WHERE r.created BETWEEN vDatedFrom AND vDatedTo
AND gt.code = 'freightDifference'
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `rutasAnalyze_launcher` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `rutasAnalyze_launcher`()
BEGIN
/**
* Call rutasAnalyze
*/
CALL rutasAnalyze(util.VN_CURDATE() - INTERVAL 30 DAY , util.VN_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 */ ;
--
-- Current Database: `bs`
--
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bs` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */;
USE `bs`;
--
-- Table structure for table `bancos_evolution`
--
DROP TABLE IF EXISTS `bancos_evolution`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bancos_evolution` (
`Fecha` date NOT NULL,
`Id_Banco` int(11) NOT NULL,
`saldo` decimal(10,2) NOT NULL DEFAULT 0.00,
`quilla` decimal(10,2) NOT NULL DEFAULT 0.00,
`deuda` decimal(10,2) NOT NULL DEFAULT 0.00,
`liquidez` decimal(10,2) NOT NULL DEFAULT 0.00,
`disponibilidad ajena` decimal(10,2) NOT NULL DEFAULT 0.00,
`saldo_aux` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Saldo auxiliar para el calculo de lo dispuesto en las polizas',
PRIMARY KEY (`Fecha`,`Id_Banco`),
KEY `fk_banco_evolution_idx` (`Id_Banco`),
CONSTRAINT `fk_banco_evolution` FOREIGN KEY (`Id_Banco`) REFERENCES `vn`.`accounting` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacena los saldos bancarios';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `carteras`
--
DROP TABLE IF EXISTS `carteras`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `carteras` (
`CodigoTrabajador` varchar(3) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
`Año` int(11) NOT NULL,
`Mes` int(11) NOT NULL,
`Peso` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`CodigoTrabajador`,`Año`,`Mes`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `clientAnnualConsumption`
--
DROP TABLE IF EXISTS `clientAnnualConsumption`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientAnnualConsumption` (
`clientFk` int(11) NOT NULL,
`invoiced` double(17,0) DEFAULT NULL,
PRIMARY KEY (`clientFk`),
CONSTRAINT `fmaId_Cliente` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `clientDied`
--
DROP TABLE IF EXISTS `clientDied`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientDied` (
`clientFk` int(11) NOT NULL DEFAULT 0,
`clientName__` varchar(50) NOT NULL COMMENT '@deprecated 2023-10-15',
`lastInvoiced` date DEFAULT NULL,
`workerCode__` varchar(3) NOT NULL COMMENT '@deprecated 2023-10-15',
`Boss__` varchar(3) NOT NULL COMMENT '@deprecated 2023-10-15',
`warning` enum('first','second','third') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
PRIMARY KEY (`clientFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Clientes que no han comprado en los ultimos 3 meses, se actualiza con proceso nocturno el 3 de cada mes';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `clientDiedPeriod`
--
DROP TABLE IF EXISTS `clientDiedPeriod`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientDiedPeriod` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`countryFk` mediumint(8) unsigned NOT NULL,
`days` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `clientDiedPeriod_UN` (`countryFk`),
CONSTRAINT `clientDiedPeriod_FK` FOREIGN KEY (`countryFk`) REFERENCES `vn`.`country` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Define lo que es un periodo para los clientes de los diferentes países';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `clientNewBorn`
--
DROP TABLE IF EXISTS `clientNewBorn`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientNewBorn` (
`clientFk` int(11) NOT NULL,
`firstShipped` date NOT NULL COMMENT 'Primer pedido o de la relacion comercial, o después de un año de inactividad',
`lastShipped` date NOT NULL COMMENT 'último pedido del cliente',
`isModified` tinyint(4) DEFAULT 0,
`isRookie` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'define un cliente que ha de ser cuidado por ser nuevo o recuperado',
PRIMARY KEY (`clientFk`),
CONSTRAINT `clientNewBorn_fk1` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Listado de clientes que se consideran nuevos a efectos de cobrar la comision adicional del comercial';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `compradores__`
--
DROP TABLE IF EXISTS `compradores__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `compradores__` (
`Id_Trabajador` int(10) unsigned NOT NULL,
`año` int(4) NOT NULL,
`semana` int(2) NOT NULL,
`importe` decimal(10,2) DEFAULT NULL,
`comision` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`Id_Trabajador`,`año`,`semana`),
CONSTRAINT `comprador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `compradores_evolution`
--
DROP TABLE IF EXISTS `compradores_evolution`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `compradores_evolution` (
`Id_Trabajador` int(10) unsigned NOT NULL,
`fecha` date NOT NULL,
`importe` decimal(10,0) DEFAULT NULL,
PRIMARY KEY (`Id_Trabajador`,`fecha`),
CONSTRAINT `evo_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `customerEvolution`
--
DROP TABLE IF EXISTS `customerEvolution`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `customerEvolution` (
`dated` date NOT NULL,
`quantity` int(11) NOT NULL,
PRIMARY KEY (`dated`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `defaulter`
--
DROP TABLE IF EXISTS `defaulter`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `defaulter` (
`clientFk` int(11) NOT NULL,
`created` date NOT NULL,
`amount` double NOT NULL DEFAULT 0,
`defaulterSinced` date DEFAULT NULL,
`hasChanged` tinyint(1) DEFAULT NULL,
`frozened` date DEFAULT NULL,
PRIMARY KEY (`clientFk`,`created`),
KEY `client` (`clientFk`),
KEY `date` (`created`),
KEY `defaulter_amount_IDX` (`amount`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `experienceIberflora2016`
--
DROP TABLE IF EXISTS `experienceIberflora2016`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `experienceIberflora2016` (
`Id_Cliente` int(11) NOT NULL,
`isVisitor` tinyint(4) NOT NULL DEFAULT 0,
PRIMARY KEY (`Id_Cliente`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lista de clientes que participan en el estudio sobre la mejora del consumo tras la visita a las instalaciones de Silla';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `fondo_maniobra`
--
DROP TABLE IF EXISTS `fondo_maniobra`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `fondo_maniobra` (
`fecha` date NOT NULL,
`fondo` double DEFAULT NULL,
`clientes_facturas` double DEFAULT NULL,
`clientes_cobros` double DEFAULT NULL,
`proveedores_facturas` double DEFAULT NULL,
`proveedores_pagos` double DEFAULT NULL,
`fondo_medio` double DEFAULT NULL,
PRIMARY KEY (`fecha`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `indicators`
--
DROP TABLE IF EXISTS `indicators`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `indicators` (
`updated` date NOT NULL,
`lastYearSales` int(11) DEFAULT NULL,
`totalGreuge` int(11) DEFAULT NULL,
`latePaymentRate` decimal(5,4) DEFAULT NULL,
`countEmployee` decimal(10,2) DEFAULT NULL,
`averageMana` int(11) DEFAULT NULL,
`bankingPool` int(11) DEFAULT NULL,
`lastMonthActiveClients` int(11) DEFAULT NULL,
`lastMonthLostClients` int(11) DEFAULT NULL,
`lastMonthNewClients` int(11) DEFAULT NULL,
`lastMonthWebBuyingRate` decimal(5,4) DEFAULT NULL,
`thisWeekSales` decimal(10,2) DEFAULT NULL,
`lastYearWeekSales` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`updated`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacena los valores actuales para una consulta diaria rápida por los directivos.';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `inspeccionSS_2021`
--
DROP TABLE IF EXISTS `inspeccionSS_2021`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `inspeccionSS_2021` (
`business_id` int(11) DEFAULT NULL,
`id` int(11) NOT NULL DEFAULT 0,
`firstName` varchar(50) DEFAULT NULL,
`lastName` varchar(50) DEFAULT NULL,
`name` varchar(45) NOT NULL,
`timed` datetime NOT NULL,
`hours_week` smallint(6) DEFAULT NULL,
`year` int(4) NOT NULL,
`week` int(2) NOT NULL,
`dated` date NOT NULL,
`orden` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='bs.inspeccionSS_2021_add()';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `inventoryDiscrepancy`
--
DROP TABLE IF EXISTS `inventoryDiscrepancy`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `inventoryDiscrepancy` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`warehouseFk` int(11) NOT NULL,
`timed` timestamp NOT NULL DEFAULT current_timestamp(),
`alert` int(11) NOT NULL DEFAULT 0,
`quantity` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='This table collects the discrepancies between theorical inventory and located items';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `inventoryDiscrepancyDetail`
--
DROP TABLE IF EXISTS `inventoryDiscrepancyDetail`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `inventoryDiscrepancyDetail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`warehouseFk` int(11) NOT NULL,
`itemFk` int(11) NOT NULL,
`theorical` int(11) DEFAULT NULL COMMENT 'theorical stock: purchases vs. sales',
`visible` int(11) DEFAULT NULL COMMENT 'located stock',
`notPicked` int(11) DEFAULT NULL COMMENT 'sales not picked yet',
`alert` int(11) DEFAULT NULL COMMENT 'alert level for this discrepancy',
PRIMARY KEY (`id`),
UNIQUE KEY `inventoryDiscrepancyDetail_UN` (`warehouseFk`,`itemFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Last discrepancies';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `lastIndicators`
--
DROP TABLE IF EXISTS `lastIndicators`;
/*!50001 DROP VIEW IF EXISTS `lastIndicators`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `lastIndicators` AS SELECT
1 AS `updated`,
1 AS `lastYearSales`,
1 AS `incLastYearSales`,
1 AS `totalGreuge`,
1 AS `incTotalGreuge`,
1 AS `latePaymentRate`,
1 AS `incLatePaymentRate`,
1 AS `countEmployee`,
1 AS `incCountEmployee`,
1 AS `averageMana`,
1 AS `incAverageMana`,
1 AS `bankingPool`,
1 AS `incbankingPool`,
1 AS `lastMonthActiveClients`,
1 AS `incLastMonthActiveClients`,
1 AS `lastMonthLostClients`,
1 AS `incLastMonthLostClients`,
1 AS `lastMonthNewClients`,
1 AS `incLastMonthNewClients`,
1 AS `lastMonthWebBuyingRate`,
1 AS `incLastMonthWebBuyingRate`,
1 AS `thisWeekSales`,
1 AS `lastYearWeekSales` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `m3`
--
DROP TABLE IF EXISTS `m3`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `m3` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`fecha` date NOT NULL,
`provinceFk` smallint(5) unsigned DEFAULT NULL,
`warehouseFk` smallint(6) unsigned NOT NULL DEFAULT 0,
`m3` decimal(10,2) DEFAULT NULL,
`year` int(11) DEFAULT NULL,
`month` int(11) DEFAULT NULL,
`week` int(11) DEFAULT NULL,
`day` int(11) DEFAULT NULL,
`dayName` varchar(12) DEFAULT NULL,
`euros` decimal(10,2) DEFAULT 0.00,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `nightTask`
--
DROP TABLE IF EXISTS `nightTask`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `nightTask` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`started` datetime DEFAULT NULL,
`finished` datetime DEFAULT NULL,
`lastFinished` datetime DEFAULT NULL,
`order` int(11) DEFAULT NULL,
`schema` varchar(45) NOT NULL,
`procedure` varchar(100) NOT NULL,
`error` varchar(255) DEFAULT NULL,
`errorCode` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `nightTaskConfig`
--
DROP TABLE IF EXISTS `nightTaskConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `nightTaskConfig` (
`id` int(10) unsigned NOT NULL,
`logMail` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `nightTaskConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `packingSpeed`
--
DROP TABLE IF EXISTS `packingSpeed`;
/*!50001 DROP VIEW IF EXISTS `packingSpeed`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `packingSpeed` AS SELECT
1 AS `hora`,
1 AS `minuto`,
1 AS `cm3`,
1 AS `warehouse_id`,
1 AS `odbc_date` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `payMethodClient`
--
DROP TABLE IF EXISTS `payMethodClient`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payMethodClient` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dated` date NOT NULL,
`payMethodFk` tinyint(3) unsigned NOT NULL DEFAULT 0,
`clientFk` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY `FkPayMethod_idx` (`payMethodFk`),
KEY `FkClientPayMethod_idx` (`clientFk`),
KEY `FkDateClientPayMethod` (`dated`,`clientFk`),
CONSTRAINT `FkClientPayMethod` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FkPayMethodClient` FOREIGN KEY (`payMethodFk`) REFERENCES `vn`.`payMethod` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_bin;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `payMethodClientEvolution`
--
DROP TABLE IF EXISTS `payMethodClientEvolution`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payMethodClientEvolution` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dated` date NOT NULL,
`payMethodName` varchar(45) NOT NULL,
`amountClient` int(11) NOT NULL,
`amount` decimal(10,2) NOT NULL,
`equalizationTax` decimal(10,2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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` (
`saleFk` int(11) NOT NULL,
`amount` decimal(10,3) NOT NULL DEFAULT 0.000,
`surcharge` decimal(10,3) NOT NULL DEFAULT 0.000,
`dated` date NOT NULL,
`typeFk` smallint(5) unsigned NOT NULL,
`clientFk` int(11) NOT NULL DEFAULT 1,
`companyFk` int(10) unsigned NOT NULL DEFAULT 442,
`margin` decimal(10,3) NOT NULL DEFAULT 0.000,
PRIMARY KEY (`saleFk`),
KEY `tip_to_tip_idx` (`typeFk`),
KEY `clientes_bs_ventas_idx` (`clientFk`),
KEY `empresa_bs_ventas_idx` (`companyFk`),
KEY `fecha_bs` (`dated`,`clientFk`),
CONSTRAINT `saleCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `vn`.`company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sale_FK` FOREIGN KEY (`saleFk`) REFERENCES `vn`.`sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sale_FK_1` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sale_FK_3` FOREIGN KEY (`typeFk`) REFERENCES `vn`.`itemType` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `salesByItemTypeDay`
--
DROP TABLE IF EXISTS `salesByItemTypeDay`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `salesByItemTypeDay` (
`itemTypeFk` smallint(5) unsigned NOT NULL,
`dated` date NOT NULL,
`netSale__` int(11) NOT NULL DEFAULT 0 COMMENT '@deprecated 2023-08-31, Mismo valor que campo sale',
`stems` int(11) NOT NULL DEFAULT 0 COMMENT 'Número de tallos vendidos',
`references` int(11) NOT NULL DEFAULT 0 COMMENT 'Número de artículos distintos por tipo vendidos',
`trash` int(11) NOT NULL DEFAULT 0 COMMENT 'Tallos basura',
`faults` int(11) NOT NULL DEFAULT 0 COMMENT 'Tallos faltas',
`claimed` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Valor total de reclamaciones',
`accepted` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Valor total de reclamaciones aceptadas',
`sale` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Ventas totales',
`buy` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Valor de compras totales',
`costComponent` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Suma de componentes que son valor de compra',
`marginComponent` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Suma de componentes que son márgen',
PRIMARY KEY (`itemTypeFk`,`dated`),
KEY `itemTypeSalesByweek_period_idx` (`dated`),
CONSTRAINT `itemTypeSalesByweek_itemTypeFk` FOREIGN KEY (`itemTypeFk`) REFERENCES `vn`.`itemType` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Ventas diarias agrupadas por reino y familia';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `salesByWeek`
--
DROP TABLE IF EXISTS `salesByWeek`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `salesByWeek` (
`week` int(11) NOT NULL,
`year` int(11) NOT NULL,
`sales` double DEFAULT NULL,
UNIQUE KEY `week` (`week`,`year`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `salesByclientSalesPerson`
--
DROP TABLE IF EXISTS `salesByclientSalesPerson`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `salesByclientSalesPerson` (
`dated` date NOT NULL DEFAULT '0000-00-00',
`salesPersonFk` int(10) unsigned DEFAULT NULL,
`clientFk` int(11) NOT NULL,
`amount` decimal(10,3) NOT NULL DEFAULT 0.000,
`equalizationTax` decimal(10,3) NOT NULL DEFAULT 0.000,
`amountNewBorn` decimal(10,3) NOT NULL DEFAULT 0.000,
PRIMARY KEY (`dated`,`clientFk`),
KEY `clientSalePersonEvolution_clientFk` (`clientFk`),
KEY `salesByclientSalesPerson_salesPerson` (`salesPersonFk`),
KEY `salesByclientSalesPerson_dated` (`dated`,`clientFk`,`amount`),
CONSTRAINT `clientSalePersonEvolution_clientFk` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON UPDATE CASCADE,
CONSTRAINT `salesByclientSalesPerson_salesPerson` FOREIGN KEY (`salesPersonFk`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Ventas diarias por cliente y comercial';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `salesMonthlySnapshot___`
--
DROP TABLE IF EXISTS `salesMonthlySnapshot___`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `salesMonthlySnapshot___` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`salesPersonName` varchar(100) DEFAULT '',
`teamName` varchar(100) DEFAULT NULL,
`year` int(11) DEFAULT NULL,
`month` int(11) DEFAULT NULL,
`currentSale` decimal(10,3) DEFAULT NULL,
`commissionSale` decimal(10,3) DEFAULT NULL,
`individualPlus` decimal(10,3) DEFAULT NULL,
`teamPlus` decimal(10,3) DEFAULT NULL,
`teamScore` decimal(10,3) DEFAULT NULL,
`newClientPlus` decimal(10,3) DEFAULT NULL,
`newClientScore` decimal(10,3) DEFAULT NULL,
`teamBossPlus` decimal(10,3) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2022-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `salesPersonEvolution`
--
DROP TABLE IF EXISTS `salesPersonEvolution`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `salesPersonEvolution` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dated` date NOT NULL DEFAULT '0000-00-00',
`salesPersonFk` int(10) unsigned DEFAULT NULL,
`amount` decimal(10,3) NOT NULL DEFAULT 0.000,
`equalizationTax` decimal(10,3) NOT NULL DEFAULT 0.000,
`amountNewBorn` decimal(10,3) NOT NULL DEFAULT 0.000,
PRIMARY KEY (`id`),
KEY `salesPersonEvolution_salesPerson` (`salesPersonFk`),
CONSTRAINT `salesPersonEvolution_salesPerson` FOREIGN KEY (`salesPersonFk`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Evolución Comerciales';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `salesPerson__`
--
DROP TABLE IF EXISTS `salesPerson__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `salesPerson__` (
`workerFk` int(10) unsigned NOT NULL,
`year` int(4) NOT NULL,
`month` int(2) NOT NULL,
`amount` decimal(10,2) DEFAULT NULL,
`commission` decimal(10,2) DEFAULT NULL,
`leasedCommission` decimal(10,2) DEFAULT NULL COMMENT 'comision proveniente de clientes que han sido donados. Ver tabla Clientes_cedidos',
`cededCommission` decimal(10,2) DEFAULT NULL COMMENT 'comision generada por los clientes que han sido donados. Ver tabla Clientes_cedidos',
`newCommission` decimal(10,2) DEFAULT NULL,
`leasedReplacement` decimal(10,2) DEFAULT NULL,
`itemTypeBorrowed` decimal(10,2) DEFAULT NULL,
`portfolioWeight` decimal(10,2) DEFAULT NULL COMMENT 'Pero de la cartera del comercial a fecha vendedores.updated',
`updated` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`workerFk`,`year`,`month`),
CONSTRAINT `salesPerson_FK` FOREIGN KEY (`workerFk`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2022-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `vendedores_evolution__`
--
DROP TABLE IF EXISTS `vendedores_evolution__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `vendedores_evolution__` (
`workerFk` int(10) unsigned NOT NULL,
`year` int(11) NOT NULL,
`sales` decimal(10,2) DEFAULT NULL,
`month` int(11) NOT NULL,
PRIMARY KEY (`workerFk`,`year`,`month`),
CONSTRAINT `evo_vendedor_trabajador` FOREIGN KEY (`workerFk`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2022-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `ventas`
--
DROP TABLE IF EXISTS `ventas`;
/*!50001 DROP VIEW IF EXISTS `ventas`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ventas` AS SELECT
1 AS `Id_Movimiento`,
1 AS `importe`,
1 AS `recargo`,
1 AS `fecha`,
1 AS `tipo_id`,
1 AS `Id_Cliente`,
1 AS `empresa_id`,
1 AS `margen` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `ventas_contables`
--
DROP TABLE IF EXISTS `ventas_contables`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ventas_contables` (
`year` int(4) NOT NULL,
`month` int(2) NOT NULL,
`venta` decimal(10,2) DEFAULT NULL,
`grupo` int(1) NOT NULL,
`reino_id` int(10) unsigned NOT NULL,
`tipo_id` smallint(5) unsigned NOT NULL,
`empresa_id` int(4) NOT NULL,
`gasto` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`year`,`month`,`grupo`,`reino_id`,`tipo_id`,`empresa_id`,`gasto`),
KEY `ventas_contables_expense_FK` (`gasto`),
CONSTRAINT `ventas_contables_expense_FK` FOREIGN KEY (`gasto`) REFERENCES `vn`.`expense` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `waste`
--
DROP TABLE IF EXISTS `waste`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `waste` (
`buyer` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`year` int(4) NOT NULL,
`week` int(2) NOT NULL,
`family` varchar(30) NOT NULL,
`itemFk` int(11) NOT NULL DEFAULT 0,
`itemTypeFk` smallint(5) unsigned DEFAULT NULL,
`saleTotal` decimal(16,0) DEFAULT NULL,
`saleWaste` decimal(16,0) DEFAULT NULL,
`rate` decimal(5,1) DEFAULT NULL,
PRIMARY KEY (`buyer`,`year`,`week`,`family`,`itemFk`),
KEY `waste_itemType_id` (`itemTypeFk`),
KEY `waste_item_id` (`itemFk`),
CONSTRAINT `waste_itemType_id` FOREIGN KEY (`itemTypeFk`) REFERENCES `vn`.`itemType` (`id`),
CONSTRAINT `waste_item_id` FOREIGN KEY (`itemFk`) REFERENCES `vn`.`item` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `workerLabourDataByMonth`
--
DROP TABLE IF EXISTS `workerLabourDataByMonth`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerLabourDataByMonth` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(25) NOT NULL,
`month` int(2) NOT NULL,
`year` int(4) NOT NULL,
`total` int(5) NOT NULL COMMENT 'Número de empleados',
`permanent` int(5) NOT NULL COMMENT 'Número de empleados fijos',
PRIMARY KEY (`id`),
KEY `workerLabourDataByMonth_graph_idx` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `workerProductivity`
--
DROP TABLE IF EXISTS `workerProductivity`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerProductivity` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dated` date NOT NULL,
`warehouseFk` smallint(6) unsigned NOT NULL,
`workerFk` int(10) unsigned NOT NULL,
`volume` decimal(10,6) NOT NULL,
`seconds` int(11) NOT NULL,
`actionFk` int(11) DEFAULT NULL,
`stateFk` tinyint(3) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `workerProductivity_warehouseFk_idx` (`warehouseFk`),
KEY `workerProductivity_workerFk_idx` (`workerFk`),
KEY `workerProductivity_roleFk_idx` (`actionFk`),
KEY `workerProductivity_FK_1` (`stateFk`),
CONSTRAINT `workerProductivity_FK_1` FOREIGN KEY (`stateFk`) REFERENCES `vn`.`state` (`id`) ON UPDATE CASCADE,
CONSTRAINT `workerProductivity_warehouseFk` FOREIGN KEY (`warehouseFk`) REFERENCES `vn`.`warehouse` (`id`) ON UPDATE CASCADE,
CONSTRAINT `workerProductivity_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `workerProductivityConfig`
--
DROP TABLE IF EXISTS `workerProductivityConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerProductivityConfig` (
`id` int(10) unsigned NOT NULL,
`minSeconsPackager` int(11) DEFAULT NULL,
`minSeconsItemPicker` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `workerProductivityConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping events for database 'bs'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `clientDied_recalc` */;
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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `clientDied_recalc` ON SCHEDULE EVERY 1 DAY STARTS '2023-06-01 03:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN
DECLARE vDone INT DEFAULT FALSE;
DECLARE vCountryFk INT;
DECLARE vDays INT;
DECLARE cur CURSOR FOR
SELECT countryFk, days
FROM clientDiedPeriod;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN cur;
read_loop: LOOP
SET vDone = FALSE;
FETCH cur INTO vCountryFk, vDays;
IF vDone THEN
LEAVE read_loop;
END IF;
CALL clientDied_recalc(vDays, (SELECT code FROM vn.country WHERE id = vCountryFk));
END LOOP;
CLOSE cur;
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 `inventoryDiscrepancy_launch` */;;
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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `inventoryDiscrepancy_launch` ON SCHEDULE EVERY 15 MINUTE STARTS '2023-07-18 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL bs.inventoryDiscrepancyDetail_replace() */ ;;
/*!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 `nightTask_launchAll` */;;
DELIMITER ;;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
/*!50003 SET character_set_client = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `nightTask_launchAll` ON SCHEDULE EVERY 1 DAY STARTS '2022-02-08 04:14:00' ON COMPLETION PRESERVE ENABLE DO CALL bs.nightTask_launchAll */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
/*!50003 SET character_set_results = @saved_cs_results */ ;;
/*!50003 SET collation_connection = @saved_col_connection */ ;;
DELIMITER ;
/*!50106 SET TIME_ZONE= @save_time_zone */ ;
--
-- Dumping routines for database 'bs'
--
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `tramo` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `tramo`(vDateTime DATETIME) RETURNS varchar(20) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
NO SQL
BEGIN
DECLARE vTramo VARCHAR(20);
DECLARE vHour INT;
SET vHour = HOUR(vDateTime) ;
SET vTramo =
CASE
WHEN vHour BETWEEN 0 AND 14 THEN 'Mañana'
WHEN vHour BETWEEN 15 AND 24 THEN 'Tarde'
END ;
RETURN vTramo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `campaignComparative` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `campaignComparative`(vDateFrom DATE, vDateTo DATE)
BEGIN
SELECT
workerName,
id,
name,
CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount,
CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount
FROM (
(SELECT
CONCAT(w.firstname, ' ', w.lastName) AS workerName,
c.id,
c.name,
SUM(v.importe) AS previousAmmount,
0 currentAmmount
FROM bs.ventas v
INNER JOIN vn.`client` c ON v.Id_Cliente = c.id
INNER JOIN vn.worker w ON c.salesPersonFk = w.id
WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR)
AND DATE_ADD(vDateTo, INTERVAL - 1 YEAR)
GROUP BY w.id, v.Id_Cliente)
UNION ALL
(SELECT
CONCAT(w.firstname, ' ', w.lastName) AS workerName,
c.id,
c.name,
0 AS previousAmmount,
SUM(s.quantity * s.price) AS currentAmmount
FROM vn.sale s
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.client c ON c.id = t.clientFk
JOIN vn.worker w ON c.salesPersonFk = w.id
WHERE t.shipped BETWEEN vDateFrom
AND vDateTo
GROUP BY w.id, c.id)
) comparative
GROUP BY workerName, id
HAVING (previousAmmount <> 0 OR currentAmmount <> 0)
ORDER BY workerName, id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `carteras_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `carteras_add`()
BEGIN
/**
* Inserta en la tabla @bs.carteras las ventas desde el año pasado
* agrupadas por trabajador, año y mes
*/
DECLARE vYear INT DEFAULT YEAR(util.VN_CURDATE()) - 1;
DELETE FROM bs.carteras WHERE Año >= vYear;
CALL util.time_generate(
MAKEDATE(vYear, 1),
(SELECT MAX(fecha) FROM ventas)
);
INSERT INTO carteras(Año, Mes , CodigoTrabajador, Peso)
SELECT t.`year`, t.`month`, w.code, SUM(v.importe)
FROM tmp.time t
JOIN ventas v on t.dated = v.fecha
JOIN vn.client c on c.id = v.Id_Cliente
JOIN vn.worker w ON w.id = c.salesPersonFk
GROUP BY w.code, t.`year`, t.`month`;
DROP TEMPORARY TABLE tmp.time;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`()
BEGIN
DECLARE vOneYearAgo DATE DEFAULT util.VN_CURDATE() - INTERVAL 1 YEAR;
DECLARE vTwoYearAgo DATE DEFAULT util.VN_CURDATE() - INTERVAL 2 YEAR;
DECLARE vThreeYearAgo DATE DEFAULT util.VN_CURDATE() - INTERVAL 3 YEAR;
DECLARE vFourYearsAgo DATE DEFAULT util.VN_CURDATE() - INTERVAL 4 YEAR;
DECLARE vEighteenMonths DATE DEFAULT util.VN_CURDATE() - INTERVAL 18 MONTH;
DELETE FROM clientNewBorn
WHERE lastShipped < vOneYearAgo;
DELETE FROM ventas
WHERE fecha < vFourYearsAgo;
DELETE FROM payMethodClient
WHERE dated < vOneYearAgo;
DELETE FROM payMethodClientEvolution
WHERE dated < vFourYearsAgo;
DELETE FROM salesByclientSalesPerson
WHERE dated < vFourYearsAgo;
DELETE FROM m3
WHERE fecha < vTwoYearAgo;
DELETE FROM salesByItemTypeDay
WHERE dated < vThreeYearAgo;
DELETE FROM waste
WHERE MAKEDATE(`year`, 1) + INTERVAL (`week` - 1) WEEK + INTERVAL 1 DAY < vEighteenMonths;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `clientDied_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clientDied_recalc`(
vDays INT,
vCountryCode VARCHAR(2)
)
BEGIN
/**
* Recalcula los clientes inactivos y hace insert en la tabla clientDied
* estableciendo hasta 3 avisos en función del periodo y el código de país.
*
* @param vDays El número de días a considerar para la inactividad del cliente
* @param vCountryCode El código del país para filtrar los clientes
*/
DECLARE vFirstPeriod , vSecondPeriod, vThridPeriod DATE;
SET vFirstPeriod = util.VN_CURDATE() - INTERVAL vDays DAY;
SET vSecondPeriod = util.VN_CURDATE() - INTERVAL vDays * 2 DAY;
SET vThridPeriod = util.VN_CURDATE() - INTERVAL vDays * 3 DAY;
DELETE cd.* FROM clientDied cd
JOIN (
SELECT c.id FROM vn.client c
JOIN vn.country co ON co.id = c.countryFk
WHERE co.code = vCountryCode
) sub ON sub.id = cd.clientFk;
INSERT INTO clientDied (clientFk, lastInvoiced, warning)
SELECT c.id,
sub.lastShipped,
CASE
WHEN lastShipped < vThridPeriod OR lastShipped IS NULL THEN 'third'
WHEN lastShipped < vSecondPeriod THEN 'second'
WHEN lastShipped < vFirstPeriod THEN 'first'
END
FROM vn.client c
JOIN vn.country co ON co .id = c.countryFk
JOIN vn.worker w ON w.id = c.salesPersonFk
JOIN vn.worker b ON b.id = w.bossFk
JOIN vn.workerMana wm ON wm.workerFk = c.salesPersonFk
LEFT JOIN (
SELECT c.id, DATE(MAX(t.shipped)) lastShipped
FROM vn.client c
LEFT JOIN vn.ticket t ON t.clientFk = c.id
LEFT JOIN vn.country co ON co.id = c.countryFk
WHERE co.code = vCountryCode
AND (t.shipped <= util.VN_CURDATE() OR t.shipped IS NULL)
GROUP BY c.id
) sub ON sub.id = c.id
LEFT JOIN vn.clientObservation cob ON cob.clientFk = c.id
AND cob.created > vThridPeriod
WHERE (sub.lastShipped < vFirstPeriod OR sub.lastShipped IS NULL)
AND c.created < vThridPeriod
AND co.code = vCountryCode
AND cob.`text` IS NULL
AND c.id NOT IN (
SELECT DISTINCT clientFk
FROM vn.ticket
WHERE refFk IS NULL
AND shipped >= vFirstPeriod
)
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `clientNewBorn_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clientNewBorn_recalc`()
BLOCK1: BEGIN
DECLARE vClientFk INT;
DECLARE vShipped DATE;
DECLARE vPreviousShipped DATE;
DECLARE vDone boolean;
DECLARE cur cursor for
SELECT clientFk, firstShipped
FROM bs.clientNewBorn;
DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE;
SET vDone := FALSE;
DELETE FROM bs.clientNewBorn WHERE isModified = FALSE;
INSERT INTO clientNewBorn(clientFk, firstShipped, lastShipped)
SELECT c.id, MAX(t.shipped), MAX(t.shipped)
FROM vn.client c
JOIN vn.ticket t on t.clientFk = c.id
LEFT JOIN clientNewBorn cb on cb.clientFk = c.id
WHERE t.shipped BETWEEN TIMESTAMPADD(YEAR, -1, util.VN_CURDATE()) AND util.VN_CURDATE() AND cb.isModified is null
GROUP BY c.id;
OPEN cur;
LOOP1: LOOP
SET vDone := FALSE;
FETCH cur INTO vClientFk, vShipped;
IF vDone THEN
CLOSE cur;
LEAVE LOOP1;
END IF;
BLOCK2: BEGIN
DECLARE vCurrentShipped DATE;
DECLARE vDone2 boolean;
DECLARE cur2 CURSOR FOR
SELECT shipped
FROM vn.ticket
WHERE clientFk = vClientFk AND shipped <= util.VN_CURDATE()
ORDER BY shipped DESC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone2 = TRUE;
SET vDone2 := FALSE;
OPEN cur2;
SET vPreviousShipped := vShipped;
LOOP2: LOOP
SET vDone2 := FALSE;
FETCH cur2 INTO vCurrentShipped;
IF DATEDIFF(vPreviousShipped,vCurrentShipped) > 365 THEN
UPDATE bs.clientNewBorn
SET firstShipped = vPreviousShipped
WHERE clientFk= vClientFk;
CLOSE cur2;
LEAVE LOOP2;
END IF;
SET vPreviousShipped := vCurrentShipped;
IF vDone2 THEN
UPDATE bs.clientNewBorn
SET firstShipped = vCurrentShipped
WHERE clientFk= vClientFk;
CLOSE cur2;
LEAVE LOOP2;
END IF;
END LOOP LOOP2;
END BLOCK2;
END LOOP LOOP1;
UPDATE bs.clientNewBorn cnb
LEFT JOIN (SELECT DISTINCT t.clientFk
FROM vn.ticket t
JOIN vn.productionConfig pc
WHERE t.shipped BETWEEN util.VN_CURDATE() + INTERVAL -(`notBuyingMonths`) MONTH
AND util.VN_CURDATE() + INTERVAL -(`pc`.`rookieDays`) DAY) notRookie ON notRookie.clientFk = cnb.clientFk
SET cnb.isRookie = ISNULL(notRookie.clientFk);
END BLOCK1 ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `compradores_evolution_add` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `compradores_evolution_add`()
BEGIN
/**
* Inserta en la tabla compradores_evolution las ventas acumuladas en los ultimos 365 dias
*
*/
DECLARE vDated DATE;
DECLARE vCount INT DEFAULT 1;
SELECT MAX(fecha) + INTERVAL 1 DAY INTO vDated
FROM compradores_evolution;
IF vDated IS NULL THEN
SELECT MIN(dated) INTO vDated
FROM sale;
INSERT INTO compradores_evolution(
Id_Trabajador,
fecha,
importe)
SELECT it.workerFk,
vDated,
SUM(s.amount)
FROM sale s
JOIN vn.itemType it ON it.id = s.typeFk
WHERE s.dated = vDated
GROUP BY it.workerFk;
SET vDated = vDated + INTERVAL 1 DAY;
END IF;
WHILE vDated < util.VN_CURDATE() DO
SET vCount = vCount + 1;
REPLACE compradores_evolution(
Id_Trabajador,
fecha,
importe)
SELECT Id_Trabajador,
vDated,
SUM(importe)
FROM(
SELECT Id_Trabajador, importe
FROM compradores_evolution
JOIN (
SELECT DISTINCT it.workerFk
FROM vn.itemType it
)sub2 ON sub2.workerFk = Id_Trabajador
WHERE fecha = vDated - INTERVAL 1 DAY
UNION ALL
SELECT it.workerFk, s.amount * IF(s.dated < vDated, -1, 1)
FROM sale s
JOIN vn.itemType it ON it.id = s.typeFk
JOIN vn.itemCategory ic ON ic.id = it.categoryFk
WHERE s.dated IN (vDated, vDated - INTERVAL 1 YEAR)
AND ic.merchandise
)sub
GROUP BY Id_Trabajador;
SET vDated = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `fondo_evolution_add` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `fondo_evolution_add`()
BEGIN
/**
* Inserta en la tabla fondo_maniobra los saldos acumulados en los ultimos 365 dias
*/
DECLARE datFEC DATE DEFAULT '2015-01-01';
SELECT TIMESTAMPADD(DAY,1,MAX(fecha))
INTO datFEC
FROM bs.fondo_maniobra;
WHILE datFEC < util.VN_CURDATE() DO
IF DAY(datFEC) MOD 28 = 0 THEN -- esto solo sirve para no aburrirse mientras esperamos...
SELECT datFEC;
END IF;
REPLACE bs.fondo_maniobra(Fecha, clientes_facturas, clientes_cobros,proveedores_facturas,proveedores_pagos, fondo)
SELECT datFEC AS Fecha, Facturas, Cobros,Recibidas,Pagos, Facturas + Cobros + Recibidas + Pagos
FROM (
SELECT SUM(io.amount) AS Facturas
FROM vn.invoiceOut io
JOIN vn.client c ON io.clientFk = c.id
WHERE c.isRelevant
AND io.companyFk <> 1381
AND io.issued BETWEEN '2011-01-01' AND datFEC
) fac
JOIN (
SELECT - SUM(r.amountPaid) AS Cobros
FROM vn.receipt r
JOIN vn.client c ON r.clientFk = c.id
WHERE c.isRelevant
AND r.companyFk <> 1381
AND r.payed BETWEEN '2011-01-01' AND datFEC
) cob
JOIN (
SELECT - SUM(id.amount) AS Recibidas
FROM vn.invoiceIn ii
JOIN vn.invoiceInDueDay id ON ii.id = id.invoiceInFk
WHERE ii.companyFk <> 1381
AND ii.issued BETWEEN '2015-01-01' AND datFEC
) rec
JOIN (
SELECT SUM(p.amount) AS Pagos
FROM vn.payment p
WHERE p.companyFk <>1381
AND p.received BETWEEN '2015-01-01' AND datFEC
) pag;
UPDATE bs.fondo_maniobra
JOIN (
SELECT AVG(fondo) AS media
FROM bs.fondo_maniobra
WHERE fecha <= datFEC
) sub
SET fondo_medio = media WHERE fecha = datFEC;
SET datFEC = TIMESTAMPADD(DAY,1,datFEC);
END WHILE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `fruitsEvolution` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `fruitsEvolution`()
BEGIN
select Id_Cliente,
Cliente, count(semana) as semanas, (w.code IS NOT NULL) isWorker
from (
select distinct v.Id_Cliente, c.name as Cliente, week(fecha, 3) as semana
from bs.ventas v
join vn.itemType it ON it.id = v.tipo_id
join vn.client c ON c.id = v.Id_Cliente
where it.categoryFk = 12
and v.fecha > '2020-01-01') sub
left join vn.worker w ON w.id = sub.Id_Cliente
group by Id_Cliente;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `indicatorsUpdate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `indicatorsUpdate`(vDated DATE)
BEGIN
DECLARE oneYearBefore DATE DEFAULT TIMESTAMPADD(YEAR,-1, vDated);
DECLARE twoMonthsBefore DATE DEFAULT TIMESTAMPADD(DAY,-60, vDated);
DECLARE oneMonthBefore DATE DEFAULT TIMESTAMPADD(DAY,-30, vDated);
DECLARE vWeek INT;
REPLACE indicators(updated)
VALUES(vDated);
-- Ventas totales del ultimo año
UPDATE indicators
SET lastYearSales =
(SELECT SUM(importe + recargo)
FROM ventas v
JOIN vn.company c ON c.id = v.empresa_id
JOIN vn.companyGroup cg ON cg.id = c.companyGroupFk
WHERE fecha BETWEEN oneYearBefore AND vDated
AND cg.code = 'Verdnatura'
)
WHERE updated = vDated;
-- Greuge total acumulado
UPDATE indicators
SET totalGreuge =
(SELECT SUM(amount)
FROM vn.greuge
WHERE shipped <= vDated
)
WHERE updated = vDated;
-- Tasa de morosidad con respecto a las ventas del último mes
UPDATE indicators
SET latePaymentRate =
(SELECT SUM(amount)
FROM bi.defaulters
WHERE date = vDated AND amount > 0)
/
(SELECT SUM(importe + recargo)
FROM ventas
WHERE fecha BETWEEN oneMonthBefore AND vDated)
WHERE updated = vDated;
-- Número de trabajadores activos
UPDATE indicators
SET countEmployee =
(SELECT CAST(SUM(ct.hoursWeek) / 40 AS DECIMAL (10, 2))
FROM vn.business b
JOIN vn.calendarType ct ON ct.id = b.calendarTypeFk
WHERE vDated BETWEEN b.started AND IFNULL(b.ended, vDated)
AND b.companyCodeFk = 'VNL'
)
WHERE updated = vDated;
-- Maná medio acumulado por comercial
UPDATE indicators
SET averageMana =
(SELECT AVG(amount)
FROM vn.workerMana
)
WHERE updated = vDated;
-- Número de clientes que han comprado en los últimos 30 dias
UPDATE indicators
SET lastMonthActiveClients =
(SELECT COUNT(DISTINCT t.clientFk)
FROM vn.ticket t
WHERE t.shipped BETWEEN oneMonthBefore AND vDated
)
WHERE updated = vDated;
-- Número de clientes que no han comprado en los últimos 30 dias, pero compraron en los 30 anteriores
UPDATE indicators
SET lastMonthLostClients =
(SELECT COUNT(lm.clientFk)
FROM
(SELECT DISTINCT t.clientFk
FROM vn.ticket t
WHERE t.shipped BETWEEN oneMonthBefore AND vDated
) cm
RIGHT JOIN
(SELECT DISTINCT t.clientFk
FROM vn.ticket t
WHERE t.shipped >= twoMonthsBefore
AND t.shipped < oneMonthBefore
) lm ON lm.clientFk = cm.clientFk
WHERE cm.clientFk IS NULL
)
WHERE updated = vDated;
-- Número de clientes que han comprado en los últimos 30 dias, pero no compraron en los 30 anteriores
UPDATE indicators
SET lastMonthNewClients =
(SELECT COUNT(cm.clientFk)
FROM
(SELECT DISTINCT t.clientFk
FROM vn.ticket t
WHERE t.shipped BETWEEN oneMonthBefore AND vDated
) cm
LEFT JOIN
(SELECT DISTINCT t.clientFk
FROM vn.ticket t
WHERE t.shipped >= twoMonthsBefore
AND t.shipped < oneMonthBefore
) lm ON lm.clientFk = cm.clientFk
WHERE lm.clientFk IS NULL
)
WHERE updated = vDated;
-- Porcentaje de autopedidos sobre los pedidos totales
UPDATE indicators
SET lastMonthWebBuyingRate =
(SELECT (SUM(source_app != '') - SUM(source_app = 'TPV')) / SUM(source_app != '')
FROM hedera.`order`
WHERE date_send BETWEEN oneMonthBefore AND vDated
)
WHERE updated = vDated;
-- Cálculo de las ventas agrupado por semanas
SELECT week INTO vWeek
FROM vn.time
WHERE dated = vDated;
TRUNCATE salesByWeek;
INSERT INTO salesByWeek (week, year, sales)
SELECT t.week, t.year, SUM(v.importe + v.recargo) sales
FROM ventas v
LEFT JOIN vn.time t ON t.dated = fecha
GROUP BY t.week, t.year
ORDER BY t.week, t.year;
-- Indicador Ventas semana actual
UPDATE indicators i
JOIN salesByWeek s ON s.week= vWeek
AND s.year = YEAR(vDated)
SET i.thisWeekSales = s.sales
WHERE updated = vDated;
-- Indicador ventas semana actual en el año pasado
UPDATE indicators i
JOIN salesByWeek s ON s.week = vWeek
AND s.year = YEAR(vDated)-1
SET i.lastYearWeekSales = s.sales
WHERE updated = vDated;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `indicatorsUpdateLauncher` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `indicatorsUpdateLauncher`()
BEGIN
DECLARE vDated DATE;
SELECT IFNULL(TIMESTAMPADD(DAY,1,MAX(updated)), '2018-04-01')
INTO vDated
FROM bs.indicators;
WHILE vDated < util.VN_CURDATE() DO
CALL indicatorsUpdate(vDated);
SELECT TIMESTAMPADD(DAY,1,MAX(updated))
INTO vDated
FROM bs.indicators;
END WHILE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `inventoryDiscrepancyDetail_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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `inventoryDiscrepancyDetail_replace`()
BEGIN
/**
* Replace all records in table inventoryDiscrepancyDetail and insert new
* records into inventoryDiscrepancy for all inventory warehouses.
*/
DECLARE vDone INT DEFAULT FALSE;
DECLARE vCalc INT;
DECLARE vWarehouseFk INT;
DECLARE cWarehouses CURSOR FOR
SELECT id
FROM vn.warehouse
WHERE isInventory;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
TRUNCATE TABLE inventoryDiscrepancyDetail;
OPEN cWarehouses;
read_loop: LOOP
SET vDone = FALSE;
FETCH cWarehouses INTO vWarehouseFk;
IF vDone THEN
LEAVE read_loop;
END IF;
CALL cache.visible_refresh(vCalc, FALSE, vWarehouseFk);
CREATE OR REPLACE TEMPORARY TABLE tVisible
SELECT itemFk, SUM(visible) totalVisible
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 sc ON sc.id = p.sectorFk
WHERE sc.warehouseFk = vWarehouseFk
GROUP BY itemFk;
INSERT INTO inventoryDiscrepancyDetail(
warehouseFk,
itemFk,
theorical,
visible,
notPicked,
alert)
SELECT vWarehouseFk warehouseFk,
v.item_id itemFk,
v.visible,
tv.totalVisible,
s.notPicked,
CASE
WHEN s.notPicked > IFNULL(tv.totalVisible, 0) THEN 0
WHEN v.visible > IFNULL((tv.totalVisible * 2), 0) THEN 1
WHEN v.visible > tv.totalVisible THEN 2
ELSE 3
END alert
FROM cache.visible v
LEFT JOIN tVisible tv ON tv.itemFk = v.item_id
JOIN (
SELECT s.itemFk, SUM(s.quantity) notPicked
FROM vn.sale s
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.ticketState ts ON ts.ticketFk = t.id
JOIN vn.alertLevel al ON al.id = ts.alertLevel
WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
AND s.isPicked = FALSE
AND al.code = 'FREE'
AND t.warehouseFk = vWarehouseFk
GROUP BY s.itemFk
HAVING notPicked
) s ON s.itemFk = v.item_id
WHERE v.calc_id = vCalc
AND NOT v.visible <=> tv.totalVisible;
END LOOP;
CLOSE cWarehouses;
INSERT INTO inventoryDiscrepancy(
warehouseFk,
alert,
quantity)
SELECT warehouseFk,
alert,
COUNT(*)
FROM inventoryDiscrepancyDetail
GROUP BY warehouseFk, alert;
DROP TEMPORARY TABLE IF EXISTS tVisible;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `m3Add` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `m3Add`()
BEGIN
DECLARE datSTART DATE;
DECLARE datEND DATE;
SELECT TIMESTAMPADD(WEEK, -1,MAX(fecha)) INTO datSTART
FROM bs.m3;
SET datEND = TIMESTAMPADD(DAY,-1,util.VN_CURDATE());
DELETE FROM bs.m3
WHERE fecha >= datSTART;
INSERT INTO bs.m3 (fecha, provinceFk, warehouseFk, m3, year, month, week, day, dayName, euros)
SELECT v.fecha, a.provinceFk, t.warehouseFk, sum(s.quantity * ic.cm3delivery) / 1000000 AS m3,
tm.year, tm.month, tm.week, tm.day, dayname(v.fecha), sum(importe)
FROM vn.ticket t
JOIN vn.sale s ON s.ticketFk = t.id
JOIN vn.item i ON i.id = s.itemFk
JOIN vn.itemType it ON it.id = i.typeFk
JOIN bs.ventas v ON v.Id_Movimiento = s.id -- Filtra solo por ventas "buenas"
JOIN vn.time tm ON tm.dated = v.fecha
JOIN vn.itemCost ic ON ic.itemFk = s.itemFk AND ic.warehouseFk = t.warehouseFk
JOIN vn.address a ON a.id = t.addressFk
WHERE v.fecha BETWEEN datSTART AND datEND
AND s.quantity > 0 -- evita abonos
AND t.companyFk = 442 -- Verdnatura
GROUP BY t.warehouseFk, v.fecha, a.provinceFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `manaCustomerUpdate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `manaCustomerUpdate`()
BEGIN
DECLARE vToDated DATE;
DECLARE vFromDated DATE;
DECLARE vForDeleteDated DATE;
DECLARE vManaId INT;
DECLARE vManaAutoId INT;
DECLARE vClaimManaId INT;
DECLARE vManaBankId INT;
DECLARE vManaGreugeTypeId INT;
DECLARE vManaFromDays INT;
DECLARE vManaToDays INT;
SELECT id INTO vManaId
FROM vn.component WHERE code = 'mana';
SELECT id INTO vManaAutoId
FROM vn.component WHERE code = 'autoMana';
SELECT id INTO vClaimManaId
FROM vn.component WHERE code = 'manaClaim';
SELECT id INTO vManaBankId
FROM vn.accounting WHERE code = 'mana';
SELECT id INTO vManaGreugeTypeId
FROM vn.greugeType WHERE code = 'mana';
SELECT manaFromDays, manaToDays
INTO vManaFromDays, vManaToDays
FROM vn.salespersonConfig;
SELECT MAX(dated) INTO vFromDated
FROM vn.clientManaCache;
DELETE FROM vn.clientManaCache
WHERE dated = vFromDated;
SELECT MAX(dated) INTO vFromDated
FROM vn.clientManaCache;
IF vFromDated IS NULL THEN
SELECT manaDateFrom
INTO vFromDated
FROM vn.salespersonConfig;
END IF;
WHILE vFromDated + INTERVAL vManaToDays DAY < util.VN_CURDATE() DO
SELECT vFromDated + INTERVAL vManaToDays DAY,
vFromDated - INTERVAL vManaFromDays DAY
INTO vToDated,
vForDeleteDated;
DELETE FROM vn.clientManaCache
WHERE dated <= vForDeleteDated;
INSERT INTO vn.clientManaCache(clientFk, mana, dated)
SELECT Id_Cliente,
SUM(mana),
vToDated
FROM (
SELECT a.clientFk Id_Cliente, s.quantity * sc.value mana
FROM vn.ticket t
JOIN vn.address a ON a.id = t.addressFk
JOIN vn.sale s ON s.ticketFk = t.id
JOIN vn.saleComponent sc ON sc.saleFk = s.id
WHERE sc.componentFk IN (vManaAutoId, vManaId, vClaimManaId)
AND t.shipped > vFromDated
AND DATE(t.shipped) <= vToDated
UNION ALL
SELECT clientFk, - amountPaid
FROM vn.receipt
WHERE bankFk = vManaBankId
AND payed > vFromDated
AND payed <= vToDated
UNION ALL
SELECT clientFk, amount
FROM vn.greuge
WHERE greugeTypeFk = vManaGreugeTypeId
AND shipped > vFromDated
AND shipped <= vToDated
UNION ALL
SELECT clientFk, mana
FROM vn.clientManaCache
WHERE dated = vFromDated
) sub
GROUP BY Id_Cliente
HAVING Id_Cliente;
SET vFromDated = vToDated;
END WHILE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `manaSpellers_actualize` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `manaSpellers_actualize`()
BEGIN
/**
* Recalcula el valor del campo con el modificador de precio
* para el componente de maná automático.
*/
UPDATE vn.workerMana wm
JOIN (
SELECT c.lastSalesPersonFk,
FLOOR(SUM(s.amount) / 12) amount
FROM salesByclientSalesPerson s
JOIN vn.client c ON c.id = s.clientFk
WHERE s.dated BETWEEN util.VN_CURDATE() - INTERVAL 1 YEAR AND util.VN_CURDATE()
GROUP BY c.lastSalesPersonFk
)avgPortfolioWeight ON avgPortfolioWeight.lastSalesPersonFk = wm.workerFk
JOIN vn.salespersonConfig spc
SET wm.pricesModifierRate =
IFNULL(
GREATEST(
spc.manaMinRate,
LEAST(
spc.manaMaxRate,
ROUND( - wm.amount / avgPortfolioWeight.amount, 3)
)
)
,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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `nightTask_launchAll` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `nightTask_launchAll`()
BEGIN
/**
* Runs all nightly tasks.
*/
DECLARE vDone BOOL;
DECLARE vError VARCHAR(255);
DECLARE vErrorCode VARCHAR(255);
DECLARE vSchema VARCHAR(255);
DECLARE vProcedure VARCHAR(255);
DECLARE vLogMail VARCHAR(255);
DECLARE vNightTaskFk INT;
DECLARE vQueue CURSOR FOR
SELECT id, `schema`, `procedure`
FROM nightTask
WHERE finished <= util.VN_CURDATE()
OR finished IS NULL
ORDER BY `order`;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
SET max_sp_recursion_depth = 3;
SELECT logMail INTO vLogMail
FROM nightTaskConfig LIMIT 1;
OPEN vQueue;
l: LOOP
SET vDone = FALSE;
FETCH vQueue INTO vNightTaskFk, vSchema, vProcedure;
IF vDone THEN
LEAVE l;
END IF;
UPDATE nightTask
SET `started` = util.VN_NOW(),
`finished` = NULL,
`error` = NULL,
`errorCode` = NULL
WHERE id = vNightTaskFk;
SET vError = NULL;
CALL nightTask_launchTask(
vSchema,
vProcedure,
vError,
vErrorCode
);
IF vError IS NOT NULL THEN
IF vLogMail IS NOT NULL THEN
CALL vn.mail_insert(
vLogMail,
NULL,
CONCAT('Nightly task failed (', vSchema, '.', vProcedure, ')'),
CONCAT(
'[', vErrorCode, '] ', vError, CHAR(13, 10), -- Line break
'See ', SCHEMA(), '.nightTask table for more info.'
)
);
END IF;
UPDATE nightTask
SET `error` = vError,
`errorCode` = vErrorCode
WHERE id = vNightTaskFk;
ELSE
UPDATE nightTask
SET finished = util.VN_NOW(),
lastFinished = util.VN_NOW()
WHERE id = vNightTaskFk;
END IF;
END LOOP;
CLOSE vQueue;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `nightTask_launchTask` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `nightTask_launchTask`(
vSchema VARCHAR(255),
vProcedure VARCHAR(255),
OUT vError VARCHAR(255),
OUT vErrorCode VARCHAR(255)
)
BEGIN
/**
* Runs an specific procedure from nightly tasks, if an error
* occurs, instead of throw it, #vError and #vErrorCode variables
* are setted.
*
* @param vSchema The procedure schema
* @param vProcedure The procedure name
* @param vError The error message, if any
* @param vErrorCode The error code, if any
*/
DECLARE EXIT HANDLER FOR SQLEXCEPTION
GET DIAGNOSTICS CONDITION 1
vError = MESSAGE_TEXT,
vErrorCode = RETURNED_SQLSTATE;
CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`'));
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `payMethodClientAdd` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `payMethodClientAdd`()
BEGIN
INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk)
SELECT util.VN_CURDATE(), c.payMethodFk, c.id
FROM vn.client c
JOIN vn.payMethod p ON c.payMethodFk = p.id;
TRUNCATE `bs`.`payMethodClientEvolution` ;
INSERT INTO `bs`.`payMethodClientEvolution` (dated, payMethodName, amountClient, amount, equalizationTax)
SELECT p.dated, pm.name, COUNT(p.clientFk), SUM(sub.importe) , SUM(sub.recargo)
FROM bs.payMethodClient p
JOIN (SELECT SUM(v.importe) AS importe, SUM(v.recargo) as recargo, v.fecha, v.Id_cliente
FROM bs.ventas v
WHERE v.fecha>= (SELECT MIN(dated) FROM bs. payMethodClient)
GROUP BY v.Id_cliente, v.fecha) sub ON sub.fecha = p.dated AND sub.Id_cliente = p.ClientFk
JOIN vn.payMethod pm ON p.payMethodFk = pm.id
GROUP BY dated,payMethodFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `saleGraphic` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `saleGraphic`(IN vItemFk INT, IN vTypeFk INT, IN vCategoryFk INT, IN vFromDate DATE,
IN vToDate DATE, IN vProducerFk INT)
BEGIN
DECLARE vFromDateLastYear DATE;
DECLARE vToDateLastYear DATE;
DECLARE vFromDateTwoYearsAgo DATE;
DECLARE vToDateTwoYearsAgo DATE;
SET vItemFk = IFNULL(vItemFk,0);
SET vTypeFk = IFNULL(vTypeFk, 0);
SET vCategoryFk = IFNULL(vCategoryFk,0);
SET vFromDate = IFNULL(vFromDate,util.VN_CURDATE());
SET vToDate = IFNULL(vToDate,util.VN_CURDATE());
SET vProducerFk = IFNULL(vProducerFk,0);
SET vFromDateLastYear = TIMESTAMPADD(YEAR,-1,vFromDate);
SET vToDateLastYear = TIMESTAMPADD(YEAR,-1,vToDate);
SET vFromDateTwoYearsAgo = TIMESTAMPADD(YEAR,-2,vFromDate);
SET vToDateTwoYearsAgo = TIMESTAMPADD(YEAR,-2,vToDate);
SELECT s.quantity, CAST(v.importe AS DECIMAL(10,0)) importe, v.fecha
FROM bs.ventas v
JOIN vn.sale s ON s.id = v.Id_Movimiento
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
WHERE vItemFk IN (i.id, 0)
AND vTypeFk IN (i.typeFk, 0)
AND vCategoryFk IN (it.categoryFk, 0)
AND vProducerFk IN (i.producerFk, 0)
AND (v.fecha BETWEEN vFromDate AND vToDate
OR v.fecha BETWEEN vFromDateLastYear AND vToDateLastYear
OR v.fecha BETWEEN vFromDateTwoYearsAgo AND vToDateTwoYearsAgo
);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `salePersonEvolutionAdd` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `salePersonEvolutionAdd`(IN vDateStart DATETIME)
BEGIN
DELETE FROM bs.salePersonEvolution
WHERE dated <= DATE_SUB(util.VN_CURDATE(), INTERVAL 1 YEAR);
INSERT INTO bs.salePersonEvolution (dated, amount, equalizationTax, salesPersonFk)
SELECT fecha dated,
CAST(SUM(importe) AS DECIMAL(10,2) ) amount,
CAST(SUM(recargo) AS DECIMAL(10,2) ) equalizationTax ,
IFNULL(salesPersonFk,0) salesPersonFk
FROM bs.ventas v
JOIN vn.client c ON v.Id_Cliente = c.id
JOIN vn.company co ON co.id = v.empresa_id
WHERE co.code = "VNL" AND fecha >= vDateStart
GROUP BY v.fecha,c.salesPersonFk
ORDER BY salesPersonFk,dated ASC;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `salesByclientSalesPerson_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `salesByclientSalesPerson_add`(vDatedFrom DATE)
BEGIN
/**
* Agrupa las ventas por cliente/comercial/fecha en la tabla bs.salesByclientSalesPerson
* El asociación cliente/comercial/fecha, se mantiene correcta en el tiempo
*
* @param vDatedFrom el cálculo se realizará desde la fecha introducida hasta ayer
*/
IF vDatedFrom IS NULL THEN
SET vDatedFrom = util.VN_CURDATE() - INTERVAL 1 MONTH;
END IF;
UPDATE salesByclientSalesPerson
SET amount = 0,
equalizationTax = 0,
amountNewBorn = 0
WHERE dated BETWEEN vDatedFrom AND util.yesterday();
INSERT INTO salesByclientSalesPerson(
dated,
salesPersonFk,
clientFk,
amount,
equalizationTax)
SELECT s.dated,
c.salesPersonFk,
s.clientFk,
SUM(s.amount),
SUM(s.surcharge)
FROM sale s
JOIN vn.client c on s.clientFk = c.id
WHERE s.dated BETWEEN vDatedFrom AND util.yesterday()
GROUP BY s.dated, c.salesPersonFk, s.clientFk
ON DUPLICATE KEY UPDATE amount= VALUES(amount),
equalizationTax= VALUES(equalizationTax);
UPDATE salesByclientSalesPerson s
JOIN vn.newBornSales n ON n.dated = s.dated AND
n.clientFk = s.clientFk
SET s.amountNewBorn = n.amount
WHERE n.dated BETWEEN vDatedFrom AND 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `salesByItemTypeDay_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `salesByItemTypeDay_add`(
vDateStart DATE,
vDateEnd DATE
)
BEGIN
/**
* Almacena datos relativos a las ventas de artículos
* agrupados por reino, familia y día
*
* @param vDateStart
* @param vDateEnd
*/
DELETE FROM salesByItemTypeDay
WHERE dated BETWEEN vDateStart AND vDateEnd;
INSERT INTO salesByItemTypeDay (itemTypeFk, dated, `references`, stems)
SELECT it.id itemTypeFk,
bs.dated,
COUNT(DISTINCT(i.id)) `references`,
SUM(i.stems * s.quantity) stems
FROM sale bs
JOIN vn.itemType it ON it.id = bs.typeFk
JOIN vn.itemCategory ic ON ic.id = it.categoryFk
JOIN vn.sale s ON s.id = bs.saleFk
JOIN vn.item i ON i.id = s.itemFk
JOIN vn.ticket t ON t.id = s.ticketFk
WHERE ic.merchandise
AND t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd)
GROUP BY it.id, bs.dated;
INSERT INTO salesByItemTypeDay (itemTypeFk, dated, trash, faults)
SELECT it.id itemTypeFk,
DATE(t.shipped) dated,
SUM(IF(c.name = 'FALTAS', i.stems * s.quantity, 0)) trash,
SUM(IF(c.name = 'BASURA', IFNULL(i.stems, 1) * s.quantity, 0)) faults
FROM vn.sale s
JOIN vn.ticket t ON t.id = s.ticketFk
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.client c ON c.id = t.clientFk
WHERE c.name IN ('BASURA', 'FALTAS')
AND t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd)
GROUP BY it.id, dated
ON DUPLICATE KEY UPDATE
trash = VALUES(trash),
faults = VALUES(faults);
INSERT INTO salesByItemTypeDay (itemTypeFk, dated, accepted, claimed)
SELECT it.id itemTypeFk,
DATE(t.shipped) dated,
SUM(
(cb.quantity * s.price * (100 - s.discount) / 100) *
((cc.maxResponsibility - c.responsibility ) / 4 )
) accepted,
SUM(cb.quantity * s.price * (100 - s.discount) / 100) claimed
FROM vn.claim c
JOIN vn.claimBeginning cb ON cb.claimFk = c.id
JOIN vn.sale s ON s.id = cb.saleFk
JOIN vn.ticket t ON t.id = s.ticketFk
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.claimConfig cc
WHERE ic.merchandise
AND t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd)
GROUP BY it.id, dated
ON DUPLICATE KEY UPDATE
accepted = VALUES(accepted),
claimed = VALUES(claimed);
INSERT INTO salesByItemTypeDay (itemTypeFk, dated, sale, buy)
SELECT itemTypeFk,
dated,
CAST(SUM(sale) AS DECIMAL(10,2)) sale,
CAST(SUM(buy) AS DECIMAL(10,2)) buy
FROM (
SELECT it.id itemTypeFk,
bs.dated,
SUM(amount) sale,
0 buy
FROM sale bs
JOIN vn.itemType it ON it.id = bs.typeFk
JOIN vn.itemCategory ic ON ic.id = it.categoryFk
JOIN vn.client c ON c.id = bs.clientFk
JOIN vn.sale s ON s.id = bs.saleFk
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.item i ON i.id = s.itemFk
WHERE ic.merchandise
AND t.shipped BETWEEN vDateStart AND vDateEnd
GROUP BY it.id, bs.dated
UNION ALL
SELECT it.id,
t.landed,
0,
SUM(b.buyingValue * b.quantity)
FROM vn.entry e
JOIN vn.travel t ON t.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 vn.itemCategory ic ON ic.id = it.categoryFk
WHERE ic.merchandise
AND t.landed BETWEEN vDateStart AND vDateEnd
GROUP BY it.id, t.landed
) sub
GROUP BY itemTypeFk, dated
ON DUPLICATE KEY UPDATE
sale = VALUES(sale),
buy = VALUES(buy);
INSERT INTO salesByItemTypeDay (itemTypeFk, dated, costComponent, marginComponent)
SELECT it.id itemTypeFk,
DATE(t.shipped) dated,
SUM(s.quantity * IF(c.code = 'purchaseValue', sc.value, 0)) costComponent,
SUM(s.quantity * IF(ct.isMargin, sc.value, 0)) marginComponent
FROM vn.ticket t
JOIN vn.sale s ON t.id = s.ticketFk
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.saleComponent sc ON sc.saleFk = s.id
STRAIGHT_JOIN vn.component c ON c.id = sc.componentFk
JOIN vn.componentType ct ON ct.id = c.typeFk
WHERE t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd)
GROUP BY it.id, dated
ON DUPLICATE KEY UPDATE
costComponent = VALUES(costComponent),
marginComponent = VALUES(marginComponent);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `salesByItemTypeDay_addLauncher` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `salesByItemTypeDay_addLauncher`()
BEGIN
CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE());
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `salesPersonEvolution_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `salesPersonEvolution_add`()
BEGIN
/**
* Calcula los datos para los gráficos de evolución agrupado por salesPersonFk y día.
* Recalcula automáticamente los 3 últimos meses para comprobar si hay algún cambio.
*/
DECLARE vDated DATE;
DECLARE vCont INT DEFAULT 1;
SELECT MAX(dated) - INTERVAL 3 MONTH INTO vDated
FROM salesPersonEvolution;
DELETE FROM salesPersonEvolution
WHERE dated >= vDated;
IF ISNULL(vDated) THEN
SELECT MIN(dated) INTO vDated
FROM salesByclientSalesPerson;
INSERT INTO salesPersonEvolution(
salesPersonFk,
dated,
amount,
equalizationTax,
amountNewBorn
)
SELECT salesPersonFk,
dated,
amount,
equalizationTax,
amountNewBorn
FROM salesByclientSalesPerson
WHERE dated = vDated
GROUP BY salesPersonFk;
SET vDated = vDated + INTERVAL 1 DAY;
END IF;
WHILE vDated < util.VN_CURDATE() DO
SET vCont = vCont + 1;
REPLACE salesPersonEvolution(salesPersonFk, dated, amount)
SELECT salesPersonFk, vDated, amount
FROM(SELECT salesPersonFk, SUM(amount) amount
FROM(SELECT salesPersonFk, amount
FROM salesPersonEvolution
WHERE dated = vDated - INTERVAL 1 DAY
UNION ALL
SELECT salesPersonFk, amount
FROM salesByclientSalesPerson
WHERE dated = vDated
UNION ALL
SELECT salesPersonFk, - amount
FROM salesByclientSalesPerson
WHERE dated = vDated - INTERVAL 1 YEAR
)sub
GROUP BY salesPersonFk
)sub
GROUP BY salesPersonFk;
SET vDated = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sales_addLauncher` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sales_addLauncher`()
BEGIN
/**
* Añade las ventas a la tabla bs.sale que se realizaron desde hace un mes hasta hoy
*
*/
DECLARE vCurDate DATE DEFAULT util.VN_CURDATE();
CALL sale_add(vCurDate - INTERVAL 1 MONTH, vCurDate);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sale_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_add`(
IN vStarted DATE,
IN vEnded DATE)
BEGIN
/**
* Añade las ventas que se realizaron entre 2 fechas a la tabla bs.sale
*
* @param vStarted Fecha de inicio
* @param vEnded Fecha de fin
*
*/
DECLARE vLoopDate DATE;
DECLARE vLoopDateTime DATETIME;
IF vStarted < (util.VN_CURDATE() - INTERVAL 5 YEAR) OR vStarted > vEnded THEN
CALL util.throw('Wrong date');
END IF;
SET vLoopDate = vStarted;
DELETE FROM sale
WHERE dated BETWEEN vStarted AND vEnded;
WHILE vLoopDate <= vEnded DO
SET vLoopDateTime = util.dayEnd(vLoopDate);
REPLACE sale(
saleFk,
amount,
surcharge,
dated,
typeFk,
clientFk,
companyFk,
margin
)WITH calculatedSales AS(
SELECT s.id saleFk,
SUM(IF(ct.isBase, s.quantity * sc.value, 0)) amount,
SUM(IF(ct.isBase, 0, s.quantity * sc.value)) surcharge,
s.total pvp,
DATE(t.shipped) dated,
i.typeFk,
t.clientFk,
t.companyFk,
SUM(IF(ct.isMargin, s.quantity * sc.value, 0 )) marginComponents
FROM vn.ticket t
STRAIGHT_JOIN vn.sale s ON s.ticketFk = t.id
JOIN vn.item i ON i.id = s.itemFk
JOIN vn.itemType it ON it.id = i.typeFk
JOIN vn.itemCategory ic ON ic.id = it.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
WHERE t.shipped BETWEEN vLoopDate AND vLoopDateTime
AND s.quantity <> 0
AND ic.merchandise
GROUP BY s.id
)SELECT saleFk,
amount,
surcharge,
dated,
typeFk,
clientFk,
companyFk,
marginComponents + amount + surcharge - pvp
FROM calculatedSales;
SET vLoopDate = vLoopDate + 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `vendedores_add_launcher` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `vendedores_add_launcher`()
BEGIN
CALL bs.salesByclientSalesPerson_add(util.VN_CURDATE()- INTERVAL 45 DAY);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_add` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_add`(IN vYear INT, IN vMonth INT)
BEGIN
/**
* Reemplaza las ventas contables del último año.
* Es el origen de datos para el balance de Entradas
*
* @param vYear Año a reemplazar
* @param vMonth Mes a reemplazar
*
**/
DECLARE TIPO_PATRIMONIAL INT DEFAULT 188;
DELETE FROM bs.ventas_contables
WHERE year = vYear
AND month = vMonth;
DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list;
CREATE TEMPORARY TABLE tmp.ticket_list
(PRIMARY KEY (id))
ENGINE = MEMORY
SELECT t.id
FROM vn.ticket t
JOIN vn.invoiceOut io ON io.`ref` = t.refFk
WHERE year(io.issued) = vYear
AND month(io.issued) = vMonth;
INSERT INTO bs.ventas_contables(year
, month
, venta
, grupo
, reino_id
, tipo_id
, empresa_id
, gasto)
SELECT vYear
, vMonth
, round(sum(s.quantity * s.price * (100 - s.discount)/100))
, IF(
co.companyGroupFk = co2.companyGroupFk
,1
,IF(co2.companyGroupFk,2,0)
) as grupo
, it.categoryFk
, i.typeFk
, t.companyFk
, i.expenseFk
+ IF(co.companyGroupFk = co2.companyGroupFk
,1
,IF(co2.companyGroupFk,2,0)
) * 100000
+ it.categoryFk * 1000 as Gasto
FROM vn.sale s
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.address a on a.id = t.addressFk
JOIN vn.client c on c.id = a.clientFk
JOIN tmp.ticket_list tt on tt.id = t.id
JOIN vn.item i on s.itemFk = i.id
JOIN vn.company co on co.id = t.companyFk
LEFT JOIN vn.company co2 on co2.clientFk = c.id
JOIN vn.itemType it on it.id = i.typeFk
WHERE s.quantity <> 0
AND s.price <> 0
AND s.discount <> 100
AND i.typeFk <> TIPO_PATRIMONIAL
GROUP BY grupo, it.categoryFk, i.typeFk, t.companyFk, Gasto;
INSERT INTO bs.ventas_contables(year
, month
, venta
, grupo
, reino_id
, tipo_id
, empresa_id
, gasto)
SELECT vYear
, vMonth
, sum(ts.quantity * ts.price)
, IF(
c.companyGroupFk = c2.companyGroupFk
,1
,IF(c2.companyGroupFk, 2, 0)
) as grupo
, NULL
, NULL
, t.companyFk
, 7050000000
FROM vn.ticketService ts
JOIN vn.ticket t ON ts.ticketFk = t.id
JOIN vn.address a on a.id = t.addressFk
JOIN vn.client cl on cl.id = a.clientFk
JOIN tmp.ticket_list tt on tt.id = t.id
JOIN vn.company c on c.id = t.companyFk
LEFT JOIN vn.company c2 on c2.clientFk = cl.id
GROUP BY grupo, t.companyFk ;
DROP TEMPORARY TABLE tmp.ticket_list;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_add_launcher` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_add_launcher`()
BEGIN
/**
* Reemplaza las ventas contables del último año.
* Es el origen de datos para el balance de Entradas
*
**/
CALL bs.ventas_contables_add(YEAR(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())), MONTH(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())));
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `waste_addSales` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `waste_addSales`()
BEGIN
DECLARE vWeek INT;
DECLARE vYear INT;
SELECT week, year
INTO vWeek, vYear
FROM vn.time
WHERE dated = util.VN_CURDATE();
REPLACE bs.waste
SELECT *, 100 * mermas / total as porcentaje
FROM (
SELECT buyer,
year,
week,
family,
itemFk,
itemTypeFk,
floor(sum(value)) as total,
floor(sum(IF(typeFk = 'loses', value, 0))) as mermas
FROM vn.saleValue
where year = vYear and week = vWeek
GROUP BY family, itemFk
) sub
ORDER BY mermas 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerLabour_getData` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerLabour_getData`()
BEGIN
/**
* Carga los datos de la plantilla de trabajadores, altas y bajas en la tabla workerLabourDataByMonth para facilitar el cálculo del gráfico en grafana.
* Se carga el día 21 de cada mes, elimina los registros del último año y los vuelve a calcular
*/
DECLARE vFristDay DATE;
DECLARE vLastDay DATE;
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vDateStarted DATE;
DECLARE vDateEnded DATE;
DECLARE vCursor CURSOR FOR
SELECT util.firstDayOfMonth(t.dated), LAST_DAY(t.dated)
FROM vn.time t
WHERE t.dated BETWEEN vDateStarted AND vDateEnded
GROUP BY year,month;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
IF DAY(util.VN_CURDATE()) = 21 THEN
SELECT util.firstDayOfMonth(DATE_SUB(util.VN_CURDATE(), INTERVAL 12 MONTH)),
LAST_DAY(DATE_SUB(util.VN_CURDATE(), INTERVAL 1 MONTH))
INTO vDateStarted,
vDateEnded;
DELETE FROM workerLabourDataByMonth
WHERE CONCAT(`year`, '-',`month`, '-01') BETWEEN vDateStarted AND vDateEnded;
OPEN vCursor;
l: LOOP
SET vDone = FALSE;
FETCH vCursor INTO vFristDay, vLastDay;
IF vDone THEN
LEAVE l;
END IF;
-- Altas periodo
INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
SELECT 'hiring', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
FROM vn.business b
JOIN vn.workCenter wc ON wc.id = b.workCenterFk
JOIN vn.worker w ON w.id = b.workerFk
LEFT JOIN vn.workerBusinessType wbt ON wbt.id = b.workerBusinessTypeFk
LEFT JOIN (SELECT b.id, b.workerFk
FROM vn.business b
LEFT JOIN (SELECT ended, workerFk FROM vn.business) wl
ON wl.ended = DATE_SUB(b.started, INTERVAL 1 DAY) AND wl.workerFk = b.workerFk
WHERE b.started BETWEEN vFristDay AND vLastDay AND wl.ended
)sub ON sub.workerFk = b.workerFk
WHERE wc.payrollCenterFk IS NOT NULL
AND b.workCenterFk IS NOT NULL
AND b.started BETWEEN vFristDay AND vLastDay
AND sub.workerFk IS NULL
AND NOT w.isFreelance;
-- Bajas periodo
INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
SELECT 'layoffs', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
FROM vn.business b
JOIN vn.worker w ON w.id = b.workerFk
JOIN vn.workCenter wc ON wc.id = b.workCenterFk
LEFT JOIN vn.workerBusinessType wbt ON wbt.id = b.workerBusinessTypeFk
LEFT JOIN (SELECT started, workerFk FROM vn.business) wl ON wl.started >= b.ended
AND wl.workerFk = b.workerFk
WHERE wc.payrollCenterFk IS NOT NULL
AND b.ended BETWEEN vFristDay AND vLastDay
AND wl.started IS NULL
AND NOT w.isFreelance;
-- Anterior al periodo
SET vLastDay = LAST_DAY(DATE_SUB(vFristDay, INTERVAL 1 DAY));
INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
SELECT 'staff', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
FROM vn.business b
JOIN vn.worker w ON w.id = b.workerFk
JOIN vn.workCenter wc ON wc.id = b.workCenterFk
LEFT JOIN vn.workerBusinessType wbt ON wbt.id = b.workerBusinessTypeFk
WHERE wc.payrollCenterFk IS NOT NULL
AND vLastDay BETWEEN started AND IFNULL(ended, vLastDay)
AND NOT w.isFreelance;
-- Discapacidad
INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent)
SELECT 'disabled', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent)
FROM vn.business b
JOIN vn.worker w ON w.id = b.workerFk
JOIN vn.workCenter wc ON wc.id = b.workCenterFk
LEFT JOIN vn.workerBusinessType wbt ON wbt.id = b.workerBusinessTypeFk
WHERE wc.payrollCenterFk IS NOT NULL
AND vLastDay BETWEEN started AND IFNULL(ended, vLastDay)
AND w.isDisable
AND NOT w.isFreelance;
END LOOP;
CLOSE vCursor;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerProductivity_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerProductivity_add`()
BEGIN
DECLARE vDateFrom DATE;
SELECT DATE_SUB(util.VN_CURDATE(),INTERVAL 30 DAY) INTO vDateFrom;
DELETE FROM workerProductivity
WHERE dated >= vDateFrom;
-- SACADORES Y ARTIFICIAL
INSERT INTO workerProductivity(dated, wareHouseFk, workerFk, volume, seconds, stateFk)
SELECT sub.dated,
sub.warehouseFk,
sub.workerFk,
SUM(sub.volume),
SUM(sub.seconds),
sub.stateFk
FROM(SELECT t.warehouseFk warehouseFk,
st.workerFk,
DATE(t.shipped) dated,
SUM((ic.cm3delivery * s.quantity)/1000000) volume,
TIME_TO_SEC(TIMEDIFF( MAX(st.created),MIN(st.created))) + wc.minSeconsItemPicker seconds,
s2.id stateFk
FROM vn.saleTracking st
LEFT JOIN vn.salesPreviousPreparated sp ON sp.saleFk = st.saleFk
JOIN vn.sale s ON s.id = st.saleFk
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.itemCost ic ON ic.warehouseFk = t.warehouseFk AND ic.itemFk = s.itemFk
JOIN vn.worker w ON w.id = st.workerFk
JOIN vn.state s2 ON s2.id = st.stateFk
LEFT JOIN vn.workerDepartment wd ON wd.workerFk = st.workerFk
JOIN workerProductivityConfig wc ON TRUE
WHERE t.shipped >= vDateFrom
AND ISNULL(sp.saleFk)
AND (s2.code IN ('OK PREVIOUS', 'PREVIOUS_PREPARATION', 'PREPARED', 'OK'))
GROUP BY t.id, t.warehouseFk, st.workerFk
) sub
GROUP BY sub.warehouseFk, sub.workerFk, sub.dated;
-- ENCAJADORES
INSERT INTO workerProductivity(dated, wareHouseFk, workerFk, volume, seconds, stateFk)
SELECT sub2.shipped,
sub2.warehouseFk,
sub2.workerFK,
SUM(sub2.volume),
SUM(sub2.seconds),
s2.id stateFk
FROM (SELECT t.warehouseFk,
SUM(s.volume) volume,
sub.workerFk,
DATE(t.shipped) shipped,
sub.seconds + w.minSeconsPackager seconds,
s.saleFk
FROM vn.saleVolume s
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN(SELECT e.workerFk, e.ticketFk,TIME_TO_SEC(TIMEDIFF( MAX(e.created), MIN(e.created))) seconds
FROM vn.expedition e
JOIN vn.ticket t ON t.id = e.ticketFk
WHERE e.workerFk IS NOT NULL AND
t.shipped >= vDateFrom
GROUP BY e.ticketFk
)sub ON sub.ticketFk = t.id
JOIN workerProductivityConfig w ON TRUE
GROUP BY s.ticketFk, t.warehouseFk
)sub2
JOIN vn.state s2 ON s2.code IN ('PACKING','PACKED')
GROUP BY sub2.warehouseFk,sub2.workerFk, sub2.shipped;
-- REVISADORES
INSERT INTO workerProductivity(dated, wareHouseFk, workerFk, volume, seconds, stateFk)
SELECT sub2.shipped,
sub2.warehouseFk,
sub2.workerFK,
SUM(sub2.volume),
SUM(sub2.seconds),
sub2.stateFk
FROM (SELECT t.warehouseFk,
SUM(s.volume) volume,
sub.workerFk,
DATE(t.shipped) shipped,
sub.seconds + w.minSeconsPackager seconds,
sub.stateFk
FROM vn.saleVolume s
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN(SELECT st.workerFk, t.id ticketFk,TIME_TO_SEC(TIMEDIFF( MAX(st.created), MIN(st.created))) seconds, s2.id stateFk
FROM vn.saleTracking st
JOIN vn.state s2 ON s2.id = st.stateFk
JOIN vn.sale s ON s.id = st.saleFk
JOIN vn.ticket t ON s.ticketFk = t.id
WHERE s2.code = 'CHECKED'
AND t.shipped >= vDateFrom
GROUP BY t.id
)sub ON sub.ticketFk = t.id
JOIN workerProductivityConfig w ON TRUE
GROUP BY s.ticketFk, t.warehouseFk
)sub2
GROUP BY sub2.warehouseFk,sub2.workerFk, sub2.shipped;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_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 utf8mb3 COLLATE utf8mb3_unicode_ci */;
USE `cache`;
--
-- Table structure for table `addressFriendship`
--
DROP TABLE IF EXISTS `addressFriendship`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `addressFriendship` (
`addressFk1` int(11) NOT NULL DEFAULT 0,
`addressFk2` int(11) NOT NULL DEFAULT 0,
`friendship` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`addressFk1`,`addressFk2`),
KEY `addressFriendship_fk2_idx` (`addressFk2`),
CONSTRAINT `addressFriendship_fk1` FOREIGN KEY (`addressFk1`) REFERENCES `vn`.`address` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `addressFriendship_fk2` FOREIGN KEY (`addressFk2`) REFERENCES `vn`.`address` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `availableNoRaids`
--
DROP TABLE IF EXISTS `availableNoRaids`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `availableNoRaids` (
`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`),
KEY `calc_id_4` (`calc_id`) USING BTREE
) ENGINE=MEMORY DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`lifetime` time NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`params` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '',
`last_refresh` datetime DEFAULT NULL,
`expires` datetime DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`connection_id` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `cache_name` (`cache_id`,`params`),
KEY `cache_id` (`cache_id`),
KEY `cacheName` (`cacheName`),
KEY `expires` (`expires`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `cache_valid`
--
DROP TABLE IF EXISTS `cache_valid`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cache_valid` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`valid` tinyint(3) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MEMORY DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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(11) 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,
CONSTRAINT `last_buy_FK_1` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `zoneAgencyFriendship`
--
DROP TABLE IF EXISTS `zoneAgencyFriendship`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneAgencyFriendship` (
`agencyModeFk` int(11) NOT NULL,
`zoneFk` int(11) NOT NULL,
`friendship` bigint(21) NOT NULL DEFAULT 0,
PRIMARY KEY (`agencyModeFk`,`zoneFk`),
KEY `zoneAgencyFriendship_fk1_idx` (`zoneFk`),
CONSTRAINT `zoneAgencyFriendship` FOREIGN KEY (`agencyModeFk`) REFERENCES `vn`.`agencyMode` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `zoneAgencyFriendship_fk1` FOREIGN KEY (`zoneFk`) REFERENCES `vn`.`zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `cacheCalc_clean` ON SCHEDULE EVERY 30 MINUTE STARTS '2022-01-28 09:29:18' 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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `cache_clean` ON SCHEDULE EVERY 5 MINUTE STARTS '2022-01-28 09:29:18' 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `addressFriendship_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `addressFriendship_Update`()
BEGIN
REPLACE cache.addressFriendship
SELECT addressFk1, addressFk2, count(*) friendship
FROM
(
SELECT t.routeFk, t.zoneFk, t.addressFk addressFk1, t2.addressFk addressFk2
FROM vn.ticket t
JOIN vn.ticket t2 USING(routeFk, zoneFk)
WHERE t.shipped >= TIMESTAMPADD(MONTH,-3,util.VN_CURDATE())
AND t2.shipped >= TIMESTAMPADD(MONTH,-3,util.VN_CURDATE())
AND t.addressFk != t2.addressFk) sub
GROUP BY addressFk1, addressFk2;
REPLACE cache.zoneAgencyFriendship
SELECT r.agencyModeFk, t.zoneFk, count(*) friendship
FROM vn.route r
JOIN vn.ticket t ON t.routeFk = r.id
WHERE t.shipped >= TIMESTAMPADD(MONTH,-3,util.VN_CURDATE())
AND r.agencyModeFk
AND t.routeFk
AND t.zoneFk
GROUP BY agencyModeFk, zoneFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `availableNoRaids_refresh` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `availableNoRaids_refresh`(OUT `vCalc` INT, IN `vRefresh` INT, IN `vWarehouse` INT, IN `vDated` 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 vDated < util.VN_CURDATE() THEN
LEAVE proc;
END IF;
SET vParams = CONCAT_WS('/', vWarehouse, vDated);
CALL vn.item_getStock (vWarehouse, vDated, NULL);
CALL cache_calc_start (vCalc, vRefresh, 'availableNoRaids', vParams);
IF !vRefresh THEN
LEAVE proc;
END IF;
-- Calcula algunos parametros necesarios
SET vStartDate = TIMESTAMP(vDated, '00:00:00');
SET vEndDate = TIMESTAMP(TIMESTAMPADD(DAY, 4, vDated), '23:59:59');
SELECT inventoried INTO vInventoryDate FROM vn.config;
SELECT SUBTIME(util.VN_NOW(), reserveTime) INTO vReserveDate
FROM hedera.orderConfig;
-- Calcula el ultimo dia de vida para cada producto
DROP TEMPORARY TABLE IF EXISTS tItemRange;
CREATE TEMPORARY TABLE tItemRange
(PRIMARY KEY (itemFk))
ENGINE = MEMORY
SELECT c.itemFk, IF(it.life IS NULL, NULL,
TIMESTAMP(TIMESTAMPADD(DAY, it.life, c.landing), '23:59:59')) AS ended
FROM (
SELECT b.itemFk, 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
JOIN vn.supplier s ON s.id = e.supplierFk
WHERE t.landed BETWEEN vInventoryDate AND vStartDate
AND t.warehouseInFk = vWarehouse
AND s.name != 'INVENTARIO'
AND NOT e.isRaid
GROUP BY b.itemFk
) c
JOIN vn.item i ON i.id = c.itemFk
JOIN vn.itemType it ON it.id = i.typeFk
HAVING ended >= vStartDate OR ended IS NULL;
-- Calcula el ATP
DELETE FROM availableNoRaids WHERE calc_id = vCalc;
DROP TEMPORARY TABLE IF EXISTS tmp.itemCalc;
CREATE TEMPORARY TABLE tmp.itemCalc
(INDEX (itemFk, warehouseFk))
SELECT itemFk, vWarehouse warehouseFk, DATE(dated) dated, SUM(quantity) quantity
FROM (
SELECT i.itemFk, i.shipped dated, i.quantity
FROM vn.itemTicketOut i
JOIN tItemRange ir ON ir.itemFk = i.itemFk
WHERE i.shipped >= vStartDate
AND (ir.ended IS NULL OR i.shipped <= ir.ended)
AND i.warehouseFk = vWarehouse
UNION ALL
SELECT i.itemFk, i.landed, i.quantity
FROM vn.itemEntryIn i
JOIN tItemRange ir ON ir.itemFk = i.itemFk
WHERE i.landed >= vStartDate
AND (ir.ended IS NULL OR i.landed <= ir.ended)
AND i.warehouseInFk = vWarehouse
AND i.isVirtualStock = FALSE
UNION ALL
SELECT i.itemFk, i.shipped, i.quantity
FROM vn.itemEntryOut i
JOIN tItemRange ir ON ir.itemFk = i.itemFk
WHERE i.shipped >= vStartDate
AND (ir.ended IS NULL OR i.shipped <= ir.ended)
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 tItemRange ir ON ir.itemFk = r.item_id
WHERE r.shipment >= vStartDate
AND (ir.ended IS NULL OR r.shipment <= ir.ended)
AND r.warehouse_id = vWarehouse
AND r.created >= vReserveDate
AND NOT o.confirmed
) t
GROUP BY itemFk, dated;
CALL vn.item_getAtp(vDated);
INSERT INTO availableNoRaids (calc_id, item_id, available)
SELECT vCalc, sub.itemFk, SUM(sub.quantity)
FROM (
SELECT il.itemFk, stock quantity
FROM tmp.itemList il
JOIN tItemRange ir ON ir.itemFk = il.itemFk
UNION ALL
SELECT itemFk, quantity
FROM tmp.itemAtp
)sub
GROUP BY sub.itemFk;
DROP TEMPORARY TABLE tmp.itemCalc, tItemRange;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `available_clean` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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;
DELETE a
FROM availableNoRaids 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `available_refresh`(OUT `vCalc` INT, IN `vRefresh` INT, IN `vWarehouse` INT, IN `vDated` DATE)
proc: BEGIN
DECLARE vStartDate DATE;
DECLARE vReserveDate DATETIME;
DECLARE vParams CHAR(100);
DECLARE vInventoryDate DATE;
DECLARE vLifeScope DATE;
DECLARE vWarehouseFkInventory INT;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
CALL cache_calc_unlock (vCalc);
RESIGNAL;
END;
IF vDated < util.VN_CURDATE() THEN
LEAVE proc;
END IF;
CALL vn.item_getStock(vWarehouse, vDated, NULL);
SET vParams = CONCAT_WS('/', vWarehouse, vDated);
CALL cache_calc_start (vCalc, vRefresh, 'available', vParams);
IF !vRefresh THEN
LEAVE proc;
END IF;
-- Calcula algunos parámetros necesarios
SET vStartDate = TIMESTAMP(vDated, '00:00:00');
SELECT inventoried INTO vInventoryDate FROM vn.config;
SELECT DATE_SUB(vStartDate, INTERVAL MAX(life) DAY) INTO vLifeScope FROM vn.itemType;
SELECT SUBTIME(util.VN_NOW(), reserveTime) INTO vReserveDate
FROM hedera.orderConfig;
SELECT w.id INTO vWarehouseFkInventory
FROM vn.warehouse w
WHERE w.code = 'inv';
-- Calcula el ultimo dia de vida para cada producto
DROP TEMPORARY TABLE IF EXISTS itemRange;
CREATE TEMPORARY TABLE itemRange
(PRIMARY KEY (itemFk))
ENGINE = MEMORY
SELECT i.id itemFk,
util.dayEnd(DATE_ADD(c.maxLanded, INTERVAL it.life DAY)) ended, it.life
FROM vn.item i
LEFT JOIN (
SELECT b.itemFk, MAX(t.landed) maxLanded
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
JOIN vn.item i ON i.id = b.itemFk
JOIN vn.itemType it ON it.id = i.typeFk
WHERE t.landed BETWEEN vLifeScope AND vStartDate
AND t.warehouseInFk = vWarehouse
AND t.warehouseOutFk <> vWarehouseFkInventory
AND it.life
AND NOT e.isExcludedFromAvailable
GROUP BY b.itemFk
) c ON i.id = c.itemFk
JOIN vn.itemType it ON it.id = i.typeFk
HAVING ended >= vStartDate OR life IS NULL;
-- Calcula el ATP
DELETE FROM available WHERE calc_id = vCalc;
DROP TEMPORARY TABLE IF EXISTS tmp.itemCalc;
CREATE TEMPORARY TABLE tmp.itemCalc
(INDEX (itemFk,warehouseFk))
ENGINE = MEMORY
SELECT itemFk, vWarehouse warehouseFk, DATE(dated) dated, SUM(quantity) quantity
FROM (SELECT i.itemFk, i.shipped dated, i.quantity
FROM vn.itemTicketOut i
JOIN itemRange ir ON ir.itemFk = i.itemFk
WHERE i.shipped >= vStartDate
AND (ir.ended IS NULL OR i.shipped <= ir.ended)
AND i.warehouseFk = vWarehouse
UNION ALL
SELECT i.itemFk, i.landed, i.quantity
FROM vn.itemEntryIn i
JOIN itemRange ir ON ir.itemFk = i.itemFk
LEFT JOIN edi.warehouseFloramondo wf ON wf.entryFk = i.entryFk
WHERE i.landed >= vStartDate
AND (ir.ended IS NULL OR i.landed <= ir.ended)
AND i.warehouseInFk = vWarehouse
AND ISNULL(wf.entryFk)
UNION ALL
SELECT i.itemFk, i.shipped, i.quantity
FROM vn.itemEntryOut i
JOIN itemRange ir ON ir.itemFk = i.itemFk
WHERE i.shipped >= vStartDate
AND (ir.ended IS NULL OR i.shipped <= ir.ended)
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 itemRange ir ON ir.itemFk = r.item_id
WHERE r.shipment >= vStartDate
AND (ir.ended IS NULL OR r.shipment <= ir.ended)
AND r.warehouse_id = vWarehouse
AND r.created >= vReserveDate
AND NOT o.confirmed
) t
GROUP BY itemFk, dated;
CALL vn.item_getAtp(vDated);
INSERT INTO available (calc_id, item_id, available)
SELECT vCalc, sub.itemFk, SUM(sub.quantity)
FROM (
SELECT ir.itemFk, stock quantity
FROM tmp.itemList il
JOIN itemRange ir ON ir.itemFk = il.itemFk
UNION ALL
SELECT itemFk, quantity
FROM tmp.itemAtp
)sub
GROUP BY sub.itemFk;
DROP TEMPORARY TABLE tmp.itemCalc, itemRange;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 vLastRefresh 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, ca.last_refresh
INTO v_cache_id, v_calc, v_expires, vLastRefresh
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 AND vLastRefresh >= CURDATE()
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cache_clean` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`()
BEGIN
DELETE FROM cache.departure_limit WHERE Fecha < util.VN_CURDATE() - INTERVAL 1 MONTH;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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(IFNULL(lhp.m3,0),IFNULL(dp.minSpeed,0))) AS Horas
, util.VN_CURDATE()+(Departure + vLoadingDelay -(Sum(pb.m3)/(GREATEST(IFNULL(lhp.m3,0),IFNULL(minSpeed,0))))/24) AS InicioPreparacion
FROM tmp.production_buffer pb
LEFT JOIN vn.lastHourProduction lhp ON lhp.warehouseFk = pb.warehouse_id
LEFT JOIN cache.departure_limit dp ON dp.warehouse_id = pb.warehouse_id AND dp.fecha = util.VN_CURDATE()
WHERE pb.Fecha = util.VN_CURDATE()
AND pb.graphCategory > 1
AND IFNULL(Departure,0) > 0
GROUP BY Departure
ORDER BY Departure DESC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
SET myTime = HOUR(util.VN_NOW()) + MINUTE(util.VN_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 = util.VN_CURDATE();
REPLACE cache.departure_limit(warehouse_id, fecha, hora, minSpeed)
VALUES (vWarehouseId, util.VN_CURDATE(), departureLimit, 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 vn.buyUltimate().
*
* @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 = util.VN_CURDATE(); -- TIMESTAMPADD(DAY, -1, util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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álculo 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 vCURDATE 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 = vn.getInventoryDate();
SET vCURDATE = util.VN_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 < vCURDATE
UNION ALL
SELECT itemFk ASitem_id, warehouseInFk AS warehouse_id, quantity AS amount
FROM vn.itemEntryIn
WHERE landed >= v_date_inv AND landed < vCURDATE 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 < vCURDATE
) 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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);
CREATE OR REPLACE TEMPORARY TABLE tmp.itemVisible
(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 tmp.itemVisible;
CALL cache_calc_end (v_calc);
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 */ ;
--
-- Current Database: `dipole`
--
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `dipole` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */;
USE `dipole`;
--
-- Temporary table structure for view `expeditionControl`
--
DROP TABLE IF EXISTS `expeditionControl`;
/*!50001 DROP VIEW IF EXISTS `expeditionControl`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `expeditionControl` AS SELECT
1 AS `fecha`,
1 AS `total`,
1 AS `leidas` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `expedition_PrintOut`
--
DROP TABLE IF EXISTS `expedition_PrintOut`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expedition_PrintOut` (
`expeditionFk` int(11) NOT NULL,
`ticketFk` int(11) NOT NULL,
`addressFk` int(11) NOT NULL,
`street` varchar(42) NOT NULL DEFAULT ' ',
`postalCode` varchar(10) NOT NULL DEFAULT ' ',
`city` varchar(100) NOT NULL DEFAULT ' ',
`shopName` varchar(100) NOT NULL DEFAULT ' ',
`isPrinted` int(11) NOT NULL DEFAULT 0,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`printerFk` int(10) unsigned NOT NULL DEFAULT 0,
`routeFk` int(11) NOT NULL DEFAULT 0,
`parkingCode` varchar(8) NOT NULL DEFAULT ' ',
`truckName` varchar(25) NOT NULL DEFAULT ' ',
`clientFk` int(11) NOT NULL,
`phone` varchar(15) DEFAULT NULL,
`province` varchar(20) NOT NULL,
`agency` varchar(100) DEFAULT NULL,
`m3` decimal(10,3) DEFAULT 0.000,
`workerCode` varchar(25) DEFAULT NULL,
`itemFk` int(11) DEFAULT NULL,
`quantity` int(11) DEFAULT NULL,
`longName` varchar(30) DEFAULT NULL,
`shelvingFk` varchar(5) DEFAULT NULL,
`comments` varchar(100) DEFAULT NULL,
PRIMARY KEY (`expeditionFk`),
KEY `expedition_PrintOut_FK` (`printerFk`),
CONSTRAINT `expedition_PrintOut_FK` FOREIGN KEY (`printerFk`) REFERENCES `printer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='listado de etiquetas a imprimir';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `expedition_Read`
--
DROP TABLE IF EXISTS `expedition_Read`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expedition_Read` (
`expeditionFk` int(11) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`readingPointFk` int(11) DEFAULT NULL,
PRIMARY KEY (`expeditionFk`),
KEY `expedition_Read_FK` (`readingPointFk`),
CONSTRAINT `expedition_Read_FK` FOREIGN KEY (`readingPointFk`) REFERENCES `readingPoint` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `printer`
--
DROP TABLE IF EXISTS `printer`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `printer` (
`id` int(10) unsigned NOT NULL,
`description` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `vnPrinter_FK` FOREIGN KEY (`id`) REFERENCES `vn`.`printer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `readingPoint`
--
DROP TABLE IF EXISTS `readingPoint`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `readingPoint` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(100) NOT NULL,
`IsCeluveyorDoor` tinyint(1) NOT NULL COMMENT 'define si esta la antena en la entrada del celuveyor y ha de generar un movimiento',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping events for database 'dipole'
--
--
-- Dumping routines for database 'dipole'
--
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`()
BEGIN
DECLARE vFromDated DATE;
SET vFromDated = TIMESTAMPADD(WEEK, -2, util.VN_CURDATE());
DELETE FROM dipole.expedition_PrintOut
WHERE created < vFromDated;
DELETE FROM dipole.expedition_Read
WHERE created < vFromDated;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_add`(vExpeditionFk INT, vPrinterFk INT, vIsPrinted BOOLEAN)
BEGIN
/** Insert records to print agency stickers and to inform sorter with new box
*
* param vExpeditionFk Id for vn.expedition
* param vPrinterFk Id for dipole.printer
* param vIsPrinted Value for field dipole.expedition_PrintOut.isPrinted
*/
INSERT INTO dipole.expedition_PrintOut(expeditionFk,
ticketFk,
addressFk,
street,
postalCode,
city,
shopName,
printerFk,
routeFk,
parkingCode,
truckName,
clientFk,
phone,
province,
agency,
workerCode,
isPrinted)
SELECT e.id,
e.ticketFk,
t.addressFk ,
LEFT(a.street, 100),
a.postalCode ,
LEFT (CONCAT(IFNULL(rm.beachFk,''),' ',a.city), 13),
a.nickname,
vPrinterFk,
IFNULL(right(`t`.`routeFk`, 3),0),
if (@vVolume := vn.ticketTotalVolume(t.id) > 1.5, @vVolume, IFNULL( rm.beachFk, 0)),
LEFT(IFNULL(et.description ,replace(`z`.`name`, 'ZONA ', 'Z')),14) truckName,
t.clientFk ,
ifnull(c.mobile, ifnull(a.mobile, ifnull(c.phone, a.phone))),
LEFT(p.name, 20),
NULL,
w.code,
vIsPrinted
FROM vn.expedition e
JOIN vn.ticket t ON t.id = e.ticketFk
JOIN vn.address a ON a.id = t.addressFk
JOIN vn.province p ON p.id = a.provinceFk
LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk
LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk
LEFT JOIN vn.beach b ON b.code = rm.beachFk
LEFT JOIN vn.`zone`z ON z.id = t.zoneFk
JOIN vn.agencyMode am ON t.agencyModeFk = am.id
JOIN vn.client c ON t.clientFk = c.id
JOIN vn.agency ag ON ag.id = am.agencyFk
JOIN vn.printer pr ON pr.id = vPrinterFk
JOIN vn.worker w ON w.id = e.workerFk
WHERE e.id = vExpeditionFk;
INSERT INTO srt.expedition (id,
width,
`length`,
height,
stateFk)
SELECT e.id,
p.width * 10,
p.`depth` * 10,
p.height * 10,
es.id
FROM vn.expedition e
LEFT JOIN vn.packaging p ON p.id = e.packagingFk
JOIN srt.expeditionState es ON es.description = 'PRINTED'
WHERE e.id = vExpeditionFk; -- En esa tabla las medidas van en milímetros
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_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 utf8mb3 COLLATE utf8mb3_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) DEFAULT NULL,
`Location` varchar(255) DEFAULT NULL,
`Price` decimal(10,2) DEFAULT NULL,
`BasisQuantitiy` int(11) DEFAULT NULL,
`BasisQuantityType` varchar(255) DEFAULT NULL,
`MinimumQuantity` int(11) DEFAULT NULL,
`MinimumQuantityType` varchar(255) DEFAULT NULL,
`MaximumQuantity Integer` int(11) DEFAULT NULL,
`MaximumQuantityType` varchar(255) 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=utf8mb3 COLLATE=utf8mb3_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,
`name` varchar(45) DEFAULT NULL,
`isEktSender` tinyint(4) NOT NULL DEFAULT 0,
`MessageID` int(11) NOT NULL,
`dateTimeTry` timestamp NULL DEFAULT NULL,
`isVmpBA` tinyint(4) DEFAULT NULL COMMENT 'Basic authentication',
`vmpVersion` int(11) DEFAULT NULL,
`vmpUrl` varchar(255) DEFAULT NULL,
`loginName` varchar(150) DEFAULT NULL,
`loginPassword` varchar(150) DEFAULT NULL,
`refreshRate` int(11) DEFAULT NULL,
`eanBuyer` varchar(15) DEFAULT NULL,
`eanSupplier` varchar(15) DEFAULT NULL,
`eanAgent` varchar(15) DEFAULT NULL,
`dateTimeLastSync` timestamp NULL DEFAULT NULL,
`closedFrom` int(11) DEFAULT NULL,
`closedTo` int(11) DEFAULT NULL,
`totalRefreshHours` int(11) DEFAULT NULL COMMENT 'Numero > 4 para no saturar, no repetir para que no solapen las actualizaciones',
`UseSupplierEmbalageCode` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'vmp you want to see their embalage code',
`firstSupplyResponseId` int(11) DEFAULT NULL,
`ApiId` int(11) DEFAULT NULL,
`ApiKey` varchar(100) DEFAULT NULL,
`isBlocked` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'product source not allowed',
`isVNHSupplier` tinyint(1) DEFAULT 0 COMMENT 'The account belongs to VNH',
PRIMARY KEY (`VMPID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`x_size` mediumint(8) unsigned NOT NULL COMMENT 'mm',
`y_size` mediumint(8) unsigned NOT NULL COMMENT 'mm',
`z_size` mediumint(8) unsigned NOT NULL COMMENT 'mm',
`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=utf8mb3 COLLATE=utf8mb3_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) 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=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='/tmp/floricode/VBN020101/FB090916.txt';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `clientFHAdminNumber`
--
DROP TABLE IF EXISTS `clientFHAdminNumber`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientFHAdminNumber` (
`fhAdminNumber` int(11) NOT NULL,
`clientFk` int(11) NOT NULL,
PRIMARY KEY (`clientFk`),
KEY `clientFHAdminNumber_fk_idx` (`fhAdminNumber`),
CONSTRAINT `clientFHAdminNumber_fk` FOREIGN KEY (`fhAdminNumber`) REFERENCES `vn`.`company` (`fhAdminNumber`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!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) DEFAULT NULL,
`Location` varchar(255) 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,
`updated` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`ID`),
UNIQUE KEY `deliveryInformation_UN` (`Location`,`LatestDeliveryDateTime`,`FirstOrderDateTime`,`LatestOrderDateTime`,`supplyResponseID`,`DeliveryType`),
KEY `fgbSupplyResponse_idx` (`supplyResponseID`),
KEY `fgbSupplyResponse_idx2` (`FirstOrderDateTime`),
KEY `fgbSupplyResponse_idx3` (`LatestOrderDateTime`) USING BTREE,
KEY `deliveryInformation_updated_IDX` (`updated`) USING BTREE,
CONSTRAINT `fgbSupplyResponse` FOREIGN KEY (`supplyResponseID`) REFERENCES `supplyResponse` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `di`
--
DROP TABLE IF EXISTS `di`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `di` (
`ID` int(11) NOT NULL DEFAULT 0,
`Location` varchar(255) DEFAULT NULL,
`LatestDeliveryDateTime` datetime DEFAULT NULL,
`FirstOrderDateTime` datetime DEFAULT NULL,
`LatestOrderDateTime` datetime DEFAULT NULL,
`supplyResponseID` int(11) DEFAULT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `di_UN` (`Location`,`LatestDeliveryDateTime`,`FirstOrderDateTime`,`LatestOrderDateTime`,`supplyResponseID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 COMMENT 'Id',
`barcode` char(25) DEFAULT NULL COMMENT 'Generated auction barcode',
`entryYear` smallint(5) unsigned NOT NULL COMMENT 'Transaction year',
`batchNumber` bigint(20) unsigned DEFAULT NULL COMMENT 'RFF+BT',
`deliveryNumber` bigint(20) unsigned DEFAULT NULL COMMENT 'RFF+AAJ',
`vendorOrderNumber` bigint(20) unsigned DEFAULT NULL COMMENT 'RFF+VN',
`fec` date DEFAULT NULL COMMENT 'DTM+97',
`hor` time DEFAULT NULL COMMENT 'UNB',
`now` timestamp NULL DEFAULT current_timestamp() COMMENT 'Creation time',
`ptj` bigint(20) unsigned DEFAULT NULL COMMENT 'NAD+BY',
`ref` int(11) NOT NULL COMMENT 'LIN',
`item` varchar(50) DEFAULT NULL COMMENT 'IMD+S99',
`pac` int(11) DEFAULT 0 COMMENT 'QTY+52',
`qty` int(10) NOT NULL COMMENT 'QTY+66',
`ori` varchar(3) DEFAULT 'NL' COMMENT 'IMD+S62',
`cat` varchar(2) DEFAULT NULL COMMENT 'IMD+S98',
`agj` int(11) DEFAULT NULL COMMENT 'RFF+AGJ',
`kop` int(11) DEFAULT NULL COMMENT 'RFF+ADZ',
`ptd` varchar(6) DEFAULT NULL COMMENT 'RFF+ACE',
`sub` mediumint(8) unsigned DEFAULT NULL COMMENT 'RFF+CTS',
`pro` mediumint(8) unsigned NOT NULL COMMENT 'NAD+MF',
`pri` double NOT NULL COMMENT 'PRI+INV',
`package` int(10) unsigned DEFAULT NULL COMMENT 'PAC',
`auction` smallint(5) unsigned DEFAULT NULL COMMENT 'NAD+FLA',
`klo` smallint(5) unsigned DEFAULT NULL COMMENT 'RFF+FAC',
`k1` smallint(5) unsigned DEFAULT NULL COMMENT 'IMD+K01',
`k2` smallint(5) unsigned DEFAULT NULL COMMENT 'IMD+K02',
`k3` tinyint(3) unsigned DEFAULT NULL COMMENT 'IMD+P01',
`k4` tinyint(3) unsigned DEFAULT NULL COMMENT 'IMD+P02',
`s1` varchar(3) DEFAULT NULL,
`s2` varchar(3) DEFAULT NULL,
`s3` varchar(3) DEFAULT NULL,
`s4` varchar(4) DEFAULT NULL,
`s5` varchar(3) DEFAULT NULL,
`s6` varchar(3) DEFAULT NULL,
`ok` tinyint(4) NOT NULL DEFAULT 0,
`trolleyFk` int(11) DEFAULT NULL,
`putOrderFk` bigint(20) DEFAULT NULL COMMENT 'RFF+ON',
`scanned` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Whether it''s been scanned',
`cps` varchar(7) DEFAULT NULL COMMENT 'Código alfanumérico de Floriday',
`dp` bigint(20) unsigned DEFAULT NULL COMMENT 'NAD+DP',
`sender` bigint(20) unsigned DEFAULT NULL COMMENT 'NAD+SE',
PRIMARY KEY (`id`) USING BTREE,
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`),
KEY `ekt_batchNumber` (`batchNumber`) USING BTREE,
KEY `ekt_vendorOrderNumber` (`vendorOrderNumber`) USING BTREE,
KEY `ekt_sub_IDX` (`sub`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ektConfig`
--
DROP TABLE IF EXISTS `ektConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ektConfig` (
`usefulAuctionLeftSegmentLength` int(11) NOT NULL DEFAULT 13 COMMENT 'Segmento aprovechable del codigo de barras de Floricode',
`standardBarcodeLength` int(11) NOT NULL DEFAULT 20 COMMENT 'Longitud del código de barras standard de Floricode',
`floridayBarcodeLength` int(11) NOT NULL DEFAULT 6,
`floramondoBarcodeLength` int(11) NOT NULL DEFAULT 13 COMMENT 'Longitud del código de los albaranes múltiples de Floramondo',
`defaultKlo` int(11) NOT NULL DEFAULT 99 COMMENT 'Reloj por defecto',
`ektRecentScopeDays` int(11) NOT NULL DEFAULT 7
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ektK1`
--
DROP TABLE IF EXISTS `ektK1`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ektK1` (
`id` smallint(6) unsigned NOT NULL,
`description` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Características negativas de los articulos de subasta';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `ektK2`
--
DROP TABLE IF EXISTS `ektK2`;
/*!50001 DROP VIEW IF EXISTS `ektK2`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ektK2` AS SELECT
1 AS `id`,
1 AS `description` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `ektK3`
--
DROP TABLE IF EXISTS `ektK3`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ektK3` (
`id` smallint(6) unsigned NOT NULL,
`description` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Características fitosanitarias de los articulos de subasta';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ektK4`
--
DROP TABLE IF EXISTS `ektK4`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ektK4` (
`id` smallint(6) unsigned NOT NULL,
`description` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Características calidad de los articulos de subasta';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `ektRecent`
--
DROP TABLE IF EXISTS `ektRecent`;
/*!50001 DROP VIEW IF EXISTS `ektRecent`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ektRecent` AS SELECT
1 AS `id`,
1 AS `barcode`,
1 AS `entryYear`,
1 AS `batchNumber`,
1 AS `deliveryNumber`,
1 AS `vendorOrderNumber`,
1 AS `fec`,
1 AS `hor`,
1 AS `now`,
1 AS `ptj`,
1 AS `ref`,
1 AS `item`,
1 AS `pac`,
1 AS `qty`,
1 AS `ori`,
1 AS `cat`,
1 AS `agj`,
1 AS `kop`,
1 AS `ptd`,
1 AS `sub`,
1 AS `pro`,
1 AS `pri`,
1 AS `package`,
1 AS `auction`,
1 AS `klo`,
1 AS `k1`,
1 AS `k2`,
1 AS `k3`,
1 AS `k4`,
1 AS `s1`,
1 AS `s2`,
1 AS `s3`,
1 AS `s4`,
1 AS `s5`,
1 AS `s6`,
1 AS `ok`,
1 AS `trolleyFk`,
1 AS `putOrderFk`,
1 AS `scanned`,
1 AS `cps`,
1 AS `dp`,
1 AS `sender`,
1 AS `usefulAuctionLeftSegmentLength`,
1 AS `standardBarcodeLength`,
1 AS `floridayBarcodeLength`,
1 AS `floramondoBarcodeLength`,
1 AS `defaultKlo`,
1 AS `ektRecentScopeDays` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `errorList`
--
DROP TABLE IF EXISTS `errorList`;
/*!50001 DROP VIEW IF EXISTS `errorList`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `errorList` AS SELECT
1 AS `id`,
1 AS `name`,
1 AS `longName`,
1 AS `quantity`,
1 AS `stock`,
1 AS `error`,
1 AS `deliveryInformationID`,
1 AS `supplyResponseID`,
1 AS `OrderTradeLineDateTime`,
1 AS `EndUserPartyGLN` */;
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`logMail` varchar(150) 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,
CONSTRAINT `exchangeConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`feature_value` varchar(3) 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`),
KEY `feature_ix1` (`feature_value`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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` (
`name` varchar(25) NOT NULL,
`checksum` text DEFAULT NULL,
`keyValue` tinyint(1) NOT NULL DEFAULT 1,
PRIMARY KEY (`name`),
UNIQUE KEY `fileConfig_name_uindex` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `floraHollandConfig`
--
DROP TABLE IF EXISTS `floraHollandConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `floraHollandConfig` (
`defaultAdminNumber` int(11) NOT NULL DEFAULT 66011,
`floramondoMargin` decimal(10,2) NOT NULL DEFAULT 0.17
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`host` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`user` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`password` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `ftpConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`entry_date` date DEFAULT NULL,
`expiry_date` date DEFAULT NULL,
`change_date_time` datetime DEFAULT NULL,
`isHazard` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`genus_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`type` varchar(3) DEFAULT NULL COMMENT 'edi.type',
`value` varchar(3) DEFAULT NULL COMMENT 'edi.value',
PRIMARY KEY (`supplyResponse`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`environment` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`host` varchar(150) NOT NULL DEFAULT 'localhost',
`user` varchar(45) DEFAULT NULL,
`pass` varchar(45) DEFAULT NULL,
`cleanPeriod` varchar(15) DEFAULT NULL COMMENT 'How long the old mails are preserved',
`successFolder` varchar(150) DEFAULT NULL,
`errorFolder` varchar(150) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `imapConfig_environment` (`environment`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`name` varchar(100) 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=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='/tmp/floricode/florecompc2/FP130916.txt';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `item_defaultType`
--
DROP TABLE IF EXISTS `item_defaultType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `item_defaultType` (
`item_id` int(11) NOT NULL,
`itemTypeFk` int(11) NOT NULL,
`bucket_id` int(11) DEFAULT NULL,
PRIMARY KEY (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='guarda las excepciones de los item holandeses para asignarles nuestros cubos y nuestros tipos';
/*!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) 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=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='/tmp/floricode/florecompc2/FY130916.txt';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `item_free`
--
DROP TABLE IF EXISTS `item_free`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `item_free` (
`id` int(11) NOT NULL,
`token` int(11) DEFAULT NULL COMMENT 'campo para asegurar que solo el usuario coge uno de los valores',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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) 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=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='/tmp/floricode/florecompc2/FO130916.txt';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `item_groupToOffer`
--
DROP TABLE IF EXISTS `item_groupToOffer`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `item_groupToOffer` (
`group_code` int(11) unsigned NOT NULL,
`itemTypeFk` smallint(5) unsigned NOT NULL,
`intrastatFk` int(8) unsigned zerofill NOT NULL,
`originFk` tinyint(2) unsigned NOT NULL DEFAULT 17,
`expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT '7001000000',
PRIMARY KEY (`group_code`),
KEY `item_groupToOffer_fk2_idx` (`itemTypeFk`),
KEY `item_groupToOffer_fk3_idx` (`intrastatFk`),
KEY `item_groupToOffer_fk4_idx` (`originFk`),
KEY `item_groupToOffer_expense_FK` (`expenseFk`),
CONSTRAINT `item_groupToOffer_expense_FK` FOREIGN KEY (`expenseFk`) REFERENCES `vn`.`expense` (`id`) ON UPDATE CASCADE,
CONSTRAINT `item_groupToOffer_fk2` FOREIGN KEY (`itemTypeFk`) REFERENCES `vn`.`itemType` (`id`),
CONSTRAINT `item_groupToOffer_fk3` FOREIGN KEY (`intrastatFk`) REFERENCES `vn`.`intrastat` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `item_groupToOffer_fk4` FOREIGN KEY (`originFk`) REFERENCES `vn`.`origin` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='se ofreceran para ser comprados';
/*!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,
`item` tinyint(3) NOT NULL DEFAULT 0,
PRIMARY KEY (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!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(11) NOT NULL AUTO_INCREMENT,
`tableName` varchar(100) NOT NULL,
`fieldName` varchar(100) DEFAULT NULL,
`fieldValue` varchar(100) DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`messageId` varchar(100) DEFAULT NULL,
`nExchanges` int(10) unsigned NOT NULL,
`error` varchar(255) DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`source` text DEFAULT NULL,
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`kop` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `mail` (`mail`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`name` varchar(45) NOT NULL,
`supplierFk` int(11) NOT NULL DEFAULT 1433,
`isOffered` tinyint(2) NOT NULL DEFAULT 0,
`MaxLatestDeliveryHour` int(11) DEFAULT NULL COMMENT 'Maxima hora para tener en cuenta la oferta',
`isLatestOrderDateTimeRelevant` tinyint(2) DEFAULT 0 COMMENT 'Se tiene en cuenta para calcular el próximo travel posible',
`isEarlyBird` tinyint(4) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY `marketPlaceisOfferedIdx` (`isOffered`),
KEY `marketPlaceMaxLatestIdx` (`MaxLatestDeliveryHour`),
KEY `marketPlace_isLatestOrderDateTimeRelevant_IDX` (`isLatestOrderDateTimeRelevant`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `offerList`
--
DROP TABLE IF EXISTS `offerList`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `offerList` (
`supplier` varchar(100) NOT NULL,
`total` int(11) DEFAULT NULL COMMENT 'Total de oferta',
`filter` int(11) DEFAULT NULL COMMENT 'Total en edi.supplyOffer',
`vnh` int(11) DEFAULT NULL COMMENT 'Total en la entrada de VNH',
`algemesi` int(11) DEFAULT NULL COMMENT 'Total en la entrada de Algemesi',
PRIMARY KEY (`supplier`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lista de las ofertas para mostrar en grafana';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `offerRefreshConfig`
--
DROP TABLE IF EXISTS `offerRefreshConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `offerRefreshConfig` (
`id` int(10) unsigned NOT NULL,
`dayRange` int(10) unsigned DEFAULT NULL COMMENT 'range of days to update the photos of an article in seconds',
PRIMARY KEY (`id`),
CONSTRAINT `offerRefreshConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`name` varchar(5) NOT NULL,
`subname` varchar(5) DEFAULT NULL,
`position` tinyint(3) unsigned NOT NULL DEFAULT 1,
`type` enum('INTEGER','DOUBLE','STRING','DATE','TIME') NOT NULL,
`required` tinyint(3) unsigned NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
UNIQUE KEY `code` (`code`),
UNIQUE KEY `name` (`name`,`subname`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`EndUserPartyGLN` varchar(13) DEFAULT NULL COMMENT 'The grower can use this reference in his EKT in the NAD (MA) segment.',
`OrderStatus` int(11) DEFAULT 0 COMMENT '1 pending\n2 confirmed\n3 canceled',
`isOrderProcessed` tinyint(4) DEFAULT NULL,
`error` varchar(255) DEFAULT NULL,
`barcode` varchar(25) DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`FHAdminNumber` int(11) DEFAULT 66011,
`saleFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `orderTradelineItemID_UNIQUE` (`orderTradelineItemID`),
KEY `deliveryInformationID_idx` (`deliveryInformationID`),
KEY `supplyResponseID_idx` (`supplyResponseID`),
KEY `putOrder_FK` (`saleFk`),
CONSTRAINT `putOrder_FK` FOREIGN KEY (`saleFk`) REFERENCES `vn`.`sale` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `specie`
--
DROP TABLE IF EXISTS `specie`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `specie` (
`specie_id` mediumint(8) unsigned NOT NULL,
`genus_id` mediumint(8) unsigned NOT NULL,
`latin_species_name` varchar(100) 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=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`company_name` varchar(70) NOT NULL,
`entry_date` date NOT NULL,
`expiry_date` date NOT NULL,
`change_date_time` datetime NOT NULL,
`isAllowedDirectSales` tinyint(1) NOT NULL DEFAULT 0,
`isBanned` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`supplier_id`),
UNIQUE KEY `supplier_UN` (`glnAddressCode`),
KEY `glnaddressCodeidx` (`glnAddressCode`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='/tmp/floricode/FEC010104/CC090916.txt';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `supplyOffer`
--
DROP TABLE IF EXISTS `supplyOffer`;
/*!50001 DROP VIEW IF EXISTS `supplyOffer`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `supplyOffer` AS SELECT
1 AS `vmpID`,
1 AS `diId`,
1 AS `srId`,
1 AS `Item_ArticleCode`,
1 AS `product_name`,
1 AS `company_name`,
1 AS `Price`,
1 AS `Quality`,
1 AS `s1`,
1 AS `s2`,
1 AS `s3`,
1 AS `s4`,
1 AS `s5`,
1 AS `s6`,
1 AS `NumberOfUnits`,
1 AS `EmbalageCode`,
1 AS `LatestDeliveryDateTime`,
1 AS `EarliestDespatchDateTime`,
1 AS `FirstOrderDateTime`,
1 AS `LatestOrderDateTime`,
1 AS `NumberOfItemsPerCask`,
1 AS `NumberOfLayersPerTrolley`,
1 AS `MinimumNumberToOrder`,
1 AS `MaximumNumberToOrder`,
1 AS `IncrementalOrderableQuantity`,
1 AS `PackingPrice`,
1 AS `MarketPlaceID`,
1 AS `PictureReference`,
1 AS `supplyResponseUpdated`,
1 AS `group_id`,
1 AS `marketPlace`,
1 AS `DeliveryPrice`,
1 AS `ChargeAmount`,
1 AS `MinimumQuantity`,
1 AS `MaximumQuantity`,
1 AS `OrderUnit`,
1 AS `IncrementalOrderUnit`,
1 AS `isEarlyBird`,
1 AS `isVNHSupplier`,
1 AS `expenseFk`,
1 AS `intrastatFk`,
1 AS `originFk`,
1 AS `itemTypeFk` */;
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) DEFAULT NULL,
`NewItem` tinyint(1) DEFAULT NULL,
`SendererID` varchar(255) DEFAULT NULL,
`ItemSupplierID` varchar(255) DEFAULT NULL,
`TransactionDate` datetime DEFAULT NULL,
`TransactionNumber` varchar(255) DEFAULT NULL,
`AuctionClockNumber` varchar(255) DEFAULT NULL,
`SupplierID` varchar(255) DEFAULT NULL,
`ItemDatesupplyResponsecol` datetime DEFAULT NULL,
`Item_ArticleCode` int(11) DEFAULT NULL,
`VBNOmschrijving` varchar(255) DEFAULT NULL,
`ExtraRemark` varchar(255) DEFAULT NULL,
`ArtCodeType` varchar(255) DEFAULT NULL,
`VBNGroupCode` varchar(255) DEFAULT NULL,
`VBNGroupDescription` varchar(255) DEFAULT NULL,
`TransactionTime` time DEFAULT NULL,
`CountryOfOrigin` varchar(255) 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) DEFAULT NULL,
`Price` decimal(10,2) DEFAULT NULL,
`Quality` varchar(255) DEFAULT NULL,
`s1` varchar(3) DEFAULT NULL,
`s2` varchar(3) DEFAULT NULL,
`s3` varchar(3) DEFAULT NULL,
`s4` varchar(3) DEFAULT NULL,
`s5` varchar(3) DEFAULT NULL,
`s6` varchar(3) DEFAULT NULL,
`ExaminiationCode1` varchar(255) DEFAULT NULL,
`ExaminiationCode2` varchar(255) DEFAULT NULL,
`OrderUnitType` varchar(255) DEFAULT NULL,
`EmbalageCode` int(11) DEFAULT NULL,
`PictureReference` varchar(255) DEFAULT NULL,
`AgentGLN` varchar(255) 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) 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) DEFAULT NULL,
`MarketFormCode` varchar(255) DEFAULT NULL COMMENT '"002" Standard Sales\n"005" Catalogue (optional)\n"001" Committed (optional)\n"003" Buffer (optional, Clock Pre Sales) ',
`FlowerColor` varchar(255) DEFAULT NULL,
`vmpID` int(11) DEFAULT NULL,
`widthMeasure` int(11) DEFAULT NULL COMMENT 'mm Embalage Width',
`lengthMeasure` int(11) DEFAULT NULL COMMENT 'mm Embalage Length',
`heightMeasure` int(11) DEFAULT NULL COMMENT 'mm Embalage Height',
`created` datetime NOT NULL DEFAULT current_timestamp(),
`EmbalageCodeSupplier` varchar(10) DEFAULT NULL,
`updated` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`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',
KEY `supplyResponse_Ix1` (`Item_ArticleCode`),
KEY `supplyResponseMarcketIdx` (`MarketPlaceID`),
KEY `supplyResponseNumberOfUnitsIdx` (`NumberOfUnits`),
KEY `supplyResponseEmbalageCodeIdx` (`EmbalageCode`),
KEY `supplyResponseputOrder_FK` (`vmpID`),
KEY `supplyResponse_updated_IDX` (`updated`) USING BTREE,
CONSTRAINT `supplyResponse_fk2` FOREIGN KEY (`MarketPlaceID`) REFERENCES `marketPlace` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `supplyResponseputOrder_FK` FOREIGN KEY (`vmpID`) REFERENCES `VMPSettings` (`VMPID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `supplyResponseLog`
--
DROP TABLE IF EXISTS `supplyResponseLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `supplyResponseLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`supplyResponseFk` int(11) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`NumberOfUnitsOld` int(11) DEFAULT NULL,
`NumberOfUnitsNew` int(11) DEFAULT NULL,
`lastVMPUpdate` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `supplyResponseLog_FK` (`supplyResponseFk`),
CONSTRAINT `supplyResponseLog_FK` FOREIGN KEY (`supplyResponseFk`) REFERENCES `supplyResponse` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Esta tabla la utiliza la empresa LOGIFLORA. No kkear.';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `tableConfig`
--
DROP TABLE IF EXISTS `tableConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tableConfig` (
`fileName` varchar(2) NOT NULL,
`toTable` varchar(15) NOT NULL,
`file` varchar(30) NOT NULL,
`updated` date DEFAULT NULL,
PRIMARY KEY (`fileName`),
UNIQUE KEY `to_table` (`toTable`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`type_group_id` tinyint(3) unsigned NOT NULL,
`description` varchar(100) 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=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`type_value` varchar(3) NOT NULL,
`type_description` varchar(70) 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=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='/tmp/floricode/florecompc2/FV130916.txt';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `warehouseFloramondo`
--
DROP TABLE IF EXISTS `warehouseFloramondo`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `warehouseFloramondo` (
`warehouseFk` smallint(6) unsigned NOT NULL,
`travellingDays` int(11) NOT NULL DEFAULT 1,
`entryFk` int(11) DEFAULT NULL,
`isFV` int(11) DEFAULT NULL COMMENT 'NULL indiferente\n0 no\n1 si\n',
`dayRange` int(11) NOT NULL DEFAULT 0 COMMENT 'dias de margen a futuro',
PRIMARY KEY (`warehouseFk`),
KEY `warehouseFloramondo_FK2_idx` (`entryFk`),
CONSTRAINT `warehouseFloramondo_FK2` FOREIGN KEY (`entryFk`) REFERENCES `vn`.`entry` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `warehouseFloramondo_fk` FOREIGN KEY (`warehouseFk`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping events for database 'edi'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `floramondo` */;
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 = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `floramondo` ON SCHEDULE EVERY 6 MINUTE STARTS '2022-01-28 09:52:45' ON COMPLETION NOT PRESERVE DISABLE DO CALL edi.floramondo_offerRefresh() */ ;;
/*!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 'edi'
--
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `imageName` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `imageName`(vPictureReference VARCHAR(255)) RETURNS varchar(255) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
DETERMINISTIC
BEGIN
SET vPictureReference = REPLACE(vPictureReference,'.','');
SET vPictureReference = REPLACE(vPictureReference,'/','');
SET vPictureReference = REPLACE(vPictureReference,'%','');
SET vPictureReference = REPLACE(vPictureReference,':','');
SET vPictureReference = REPLACE(vPictureReference,'?','');
SET vPictureReference = REPLACE(vPictureReference,'=','');
RETURN vPictureReference;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`()
BEGIN
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
DELETE FROM ekt
WHERE fec < (util.VN_CURDATE() - INTERVAL 4 YEAR);
DELETE IGNORE sr.*
FROM supplyResponse sr
LEFT JOIN deliveryInformation di ON sr.ID = di.supplyResponseID
WHERE di.LatestOrderDateTime < (util.VN_CURDATE() - INTERVAL 1 WEEK)
OR di.ID IS NULL;
DELETE FROM putOrder
WHERE created < (util.VN_CURDATE() - INTERVAL 1 MONTH);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `deliveryInformation_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `deliveryInformation_Delete`()
BEGIN
DECLARE vID INT;
DECLARE vGap INT DEFAULT 100;
DECLARE vTope INT;
SELECT MIN(ID), MAX(ID)
INTO vID, vTope
FROM edi.deliveryInformation;
WHILE vID <= vTope DO
SET vID = vID + vGap;
DELETE
FROM edi.deliveryInformation
WHERE ID < vID
AND EarliestDespatchDateTime IS NULL;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ekt_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_add`(vPutOrderFk INT)
BEGIN
/**
* Añade ekt para las ordenes de compra de proveedores que no envian el ekt por email
*
* @param vPutOrderFk PutOrderId de donde coger los datos
**/
INSERT INTO edi.ekt(entryYear,
deliveryNumber,
fec,
hor,
item,
pac,
qty,
ori,
cat,
pro,
pri,
package,
s1,
s2,
s3,
s4,
s5,
s6,
putOrderFk,
`ref`,
kop)
SELECT year(util.VN_CURDATE()) entryYear,
p.id deliveryNumber ,
DATE(di.LatestDeliveryDateTime) fec,
HOUR(di.LatestDeliveryDateTime) hor,
i.longName item,
sr.NumberOfItemsPerCask pac,
p.quantity qty,
o.code ori,
i.category cat,
mp.supplierFk pro,
sr.Price pri,
sr.EmbalageCode package,
i.value5 s1,
i.value6 s2,
i.value7 s3,
i.value8 s4,
i.value9 s5,
i.value10 s6,
p.id putOrderFk,
sr.Item_ArticleCode,
sr.vmpID
FROM edi.putOrder p
JOIN edi.supplyResponse sr ON sr.ID = p.supplyResponseID
JOIN edi.deliveryInformation di ON di.id = p.deliveryInformationID
JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID
JOIN vn.item i ON i.supplyResponseFk = sr.ID
JOIN vn.origin o ON o.id = i.originFk
WHERE p.id = vPutOrderFk;
CALL edi.ekt_load(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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_load`(IN `vSelf` INT)
proc:BEGIN
/**
* Carga los datos esenciales para el sistema EKT.
* Inserta compras y ventas si es necesario.
*
* @param vSelf Id de ekt
*/
DECLARE vRef INT;
DECLARE vBuy INT;
DECLARE vItem INT;
DECLARE vQty INT;
DECLARE vPackage INT;
DECLARE vPutOrderFk INT;
DECLARE vIsLot BOOLEAN;
DECLARE vEntryFk INT;
DECLARE vHasToChangePackagingFk BOOLEAN;
DECLARE vIsFloramondoDirect BOOLEAN;
DECLARE vTicketFk INT;
DECLARE vHasItemGroup BOOL;
DECLARE vDescription VARCHAR(255);
DECLARE vSaleFk INT;
DECLARE vDefaultEntry INT;
-- Carga los datos necesarios del EKT
SELECT e.ref, qty, package, putOrderFk MOD 1000000, i2.id , NOT ISNULL(eea.addressFk), NOT ISNULL(igto.group_code),
CONCAT(e.`ref`, ' ', e.item, ' ', e.sub, ' EktFk:', e.id)
INTO vRef, vQty, vPackage, vPutOrderFk, vItem, vIsFloramondoDirect, vHasItemGroup, vDescription
FROM ekt e
LEFT JOIN item i ON e.ref = i.id
LEFT JOIN putOrder po ON po.id = e.putOrderFk
LEFT JOIN vn.item i2 ON i2.supplyResponseFk = po.supplyResponseID
LEFT JOIN vn.ektEntryAssign eea ON eea.sub = e.sub
LEFT JOIN item_groupToOffer igto ON igto.group_code = i.group_id
WHERE e.id = vSelf
LIMIT 1;
IF NOT vHasItemGroup THEN
CALL vn.mail_insert('logistica@verdnatura.es', 'nocontestar@verdnatura.es', 'Nuevo grupo en Floramondo', vDescription);
CALL vn.mail_insert('pako@verdnatura.es', 'nocontestar@verdnatura.es', CONCAT('Nuevo grupo en Floramondo: ', vDescription), vDescription);
LEAVE proc;
END IF;
SELECT defaultEntry INTO vDefaultEntry
FROM vn.entryConfig;
-- Asigna la entrada
SELECT vn.ekt_getEntry(vSelf) INTO vEntryFk;
-- Inserta el cubo si no existe
IF vPackage = 800 THEN
SET vHasToChangePackagingFk = TRUE;
IF vItem THEN
SELECT vn.item_getPackage(vItem) INTO vPackage ;
ELSE
SET vPackage = 8000 + vQty;
INSERT IGNORE INTO vn.packaging(id, width, `depth`)
SELECT vPackage, vc.ccLength / vQty, vc.ccWidth
FROM vn.volumeConfig vc;
END IF;
ELSE
INSERT IGNORE INTO vn.packaging (id, width, depth, height)
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 vn.mail SET
`subject` = 'Cubo añadido',
`body` = CONCAT('Se ha añadido el cubo: ', vPackage),
`receiver` = 'ekt@verdnatura.es';
END IF;
END IF;
-- Si es una compra de Logiflora obtiene el articulo
IF vPutOrderFk THEN
SELECT i.id INTO vItem
FROM putOrder po
JOIN vn.item i ON i.supplyResponseFk = po.supplyResponseID
WHERE po.id = vPutOrderFk
LIMIT 1;
END IF;
INSERT IGNORE INTO item_track
SET item_id = vRef;
IF vItem IS NULL THEN
-- Intenta obtener el artículo en base a los atributos holandeses
SELECT b.id, IFNULL(b.itemOriginalFk ,b.itemFk) INTO vBuy, vItem
FROM ekt e
JOIN item_track t ON t.item_id = e.ref
LEFT JOIN ekt l ON l.ref = e.ref
LEFT JOIN vn.buy b ON b.ektFk = l.id
LEFT JOIN vn.item i ON i.id = b.itemFk
WHERE e.id = vSelf
AND l.id != vSelf
AND b.itemFk != vDefaultEntry
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.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.package, l.package = e.package, TRUE)
AND IF(t.item, l.item = e.item, TRUE)
AND i.isFloramondo = vIsFloramondoDirect
ORDER BY l.now DESC, b.id ASC
LIMIT 1;
END IF;
-- Si no encuentra el articulo lo crea en el caso de las compras directas en Floramondo
IF vItem IS NULL AND vIsFloramondoDirect THEN
CALL item_getNewByEkt(vSelf, vItem);
END IF;
INSERT INTO vn.buy (
entryFk,
ektFk,
buyingValue,
itemFk,
stickers,
packing,
`grouping`,
quantity,
groupingMode,
packagingFk,
weight)
SELECT vEntryFk,
vSelf,
(@t := IF(i.stems, i.stems, 1)) * e.pri / IFNULL(i.stemMultiplier, 1) buyingValue,
IFNULL(vItem, vDefaultEntry) itemFk,
e.qty stickers,
@pac := GREATEST(1, IFNULL(i.stemMultiplier, 1) * e.pac / @t) packing,
IFNULL(b.`grouping`, e.pac),
@pac * e.qty,
'packing',
IF(vHasToChangePackagingFk OR b.packagingFk IS NULL, vPackage, b.packagingFk),
(IFNULL(i.weightByPiece, 0) * @pac) / 1000
FROM ekt e
LEFT JOIN vn.buy b ON b.id = vBuy
LEFT JOIN vn.item i ON i.id = b.itemFk
LEFT JOIN vn.supplier s ON e.pro = s.id
WHERE e.id = vSelf
LIMIT 1;
CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc
SELECT buy.id
FROM vn.buy
WHERE ektFk = vSelf;
CALL vn.buy_recalcPrices();
-- Si es una compra de Logiflora hay que informar la tabla vn.saleBuy
IF vPutOrderFk THEN
REPLACE vn.saleBuy(saleFk, buyFk, workerFk)
SELECT po.saleFk, b.id, account.myUser_getId()
FROM putOrder po
JOIN vn.buy b ON b.ektFk = vSelf
WHERE po.id = vPutOrderFk;
END IF;
-- Si es una compra directa en Floramondo hay que añadirlo al ticket
IF vIsFloramondoDirect THEN
SELECT t.id INTO vTicketFk
FROM vn.ticket t
JOIN vn.ektEntryAssign eea ON eea.addressFk = t.addressFk
AND t.warehouseFk = eea.warehouseInFk
JOIN ekt e ON e.sub = eea.sub
AND e.id = vSelf
WHERE e.fec = t.shipped
LIMIT 1;
IF vTicketFk IS NULL THEN
SET @clientFk = NULL;
INSERT INTO vn.ticket (
clientFk,
shipped,
addressFk,
agencyModeFk,
nickname,
warehouseFk,
companyFk,
landed,
zoneFk,
zonePrice,
zoneBonus)
SELECT @clientFk := a.clientFk,
e.fec,
a.id,
a.agencyModeFk,
a.nickname,
eea.warehouseInFk,
c.id,
e.fec,
z.id,
z.price,
z.bonus
FROM ekt e
JOIN vn.ektEntryAssign eea ON eea.sub = e.sub
JOIN vn.address a ON a.id = eea.addressFk
JOIN vn.company c ON c.code = 'VNL'
JOIN vn.`zone` z ON z.code = 'FLORAMONDO'
WHERE e.id = vSelf
LIMIT 1;
SET vTicketFk = LAST_INSERT_ID();
IF @clientFk IS NULL THEN
CALL util.throw(CONCAT("Ticket creation failed: ", vSelf));
END IF;
END IF;
INSERT INTO vn.sale (itemFk, ticketFk, concept, quantity, price)
SELECT vItem, vTicketFk, e.item, e.qty * e.pac, e.pri * ( 1 + fhc.floramondoMargin )
FROM ekt e
JOIN floraHollandConfig fhc
WHERE e.id = vSelf;
SELECT LAST_INSERT_ID() INTO vSaleFk;
REPLACE vn.saleBuy(saleFk, buyFk, workerFk)
SELECT vSaleFk, b.id, account.myUser_getId()
FROM vn.buy b
WHERE b.ektFk = vSelf;
INSERT INTO vn.saleComponent(saleFk, componentFk, value)
SELECT vSaleFk, c.id, e.pri
FROM ekt e
JOIN vn.component c ON c.code = 'purchaseValue'
WHERE e.id = vSelf;
INSERT INTO vn.saleComponent(saleFk, componentFk, value)
SELECT vSaleFk, c.id, e.pri * fhc.floramondoMargin
FROM ekt e
JOIN floraHollandConfig fhc
JOIN vn.component c ON c.code = 'margin'
WHERE e.id = vSelf;
END IF;
DROP TEMPORARY TABLE tmp.buyRecalc;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ekt_loadNotBuy` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_loadNotBuy`()
BEGIN
/**
* Ejecuta ekt_load para aquellos ekt de hoy que no tienen vn.buy
*/
DECLARE vEktFk INTEGER;
DECLARE done BOOL;
DECLARE cursor1 CURSOR FOR
SELECT e.id
FROM edi.ekt e
LEFT JOIN vn.buy b ON b.ektFk = e.id
WHERE e.fec >= util.VN_CURDATE()
AND ISNULL(b.ektFk);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cursor1;
bucle: LOOP
FETCH cursor1 INTO vEktFk;
IF done THEN
LEAVE bucle;
END IF;
CALL edi.ekt_load(vEktFk);
END LOOP bucle;
CLOSE cursor1;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ekt_refresh` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_refresh`(
`vSelf` INT, vMailFk INT)
BEGIN
/**
* Updates a transaction, generates it's barcode.
*/
DECLARE vRewriteKop INT DEFAULT NULL;
DECLARE vTruncatePutOrder INT DEFAULT NULL;
DECLARE vBarcode CHAR(15) DEFAULT NULL;
DECLARE vKop INT;
DECLARE vPutOrderFk BIGINT;
SELECT kop, putOrderFk
INTO vKop, vPutOrderFk
FROM ekt
WHERE id = vSelf;
-- Generates the barcode
SELECT CONCAT(
LPAD(IFNULL(auction,0), 3, 0),
LPAD(IFNULL(klo, 99), 2, 0),
LPAD(DAYOFYEAR(fec), 3, 0),
COALESCE(agj, RIGHT(batchNumber,7), id))
INTO vBarcode
FROM ekt
WHERE id = vSelf;
-- 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);
-- Format order id
SET vTruncatePutOrder = vPutOrderFk MOD 1000000;
-- Refresh EKT
UPDATE ekt SET
barcode = vBarcode
,kop = vKop
,putOrderFk = vTruncatePutOrder
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ekt_scan` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_scan`(vBarcode VARCHAR(512))
BEGIN
/**
* Busca transaciones a partir de un codigo de barras, las marca como escaneadas
* y las devuelve.
* Ver https://wiki.verdnatura.es/index.php/Ekt#Algoritmos_de_lectura
*
* @param vBarcode Código de compra de una etiqueta de subasta
* @param vLabels Cantidad escaneada
* @table tmp.ekt(ektFk) Transacciones escaneadas
*/
DECLARE vIsFound BOOL;
DECLARE vUsefulAuctionLeftSegmentLength INT;
DECLARE vStandardBarcodeLength INT;
DECLARE vFloridayBarcodeLength INT;
DECLARE vFloramondoBarcodeLength INT;
DECLARE vAuction INT;
DECLARE vKlo INT;
DECLARE vFec DATE;
DECLARE vShortAgj INT;
DECLARE vLongAgj INT;
DECLARE vXtraLongAgj INT;
DECLARE vDefaultKlo INT;
SELECT
ec.usefulAuctionLeftSegmentLength,
ec.standardBarcodeLength,
ec.floridayBarcodeLength,
ec.floramondoBarcodeLength,
ec.defaultKlo
INTO
vUsefulAuctionLeftSegmentLength,
vStandardBarcodeLength,
vFloridayBarcodeLength,
vFloramondoBarcodeLength,
vDefaultKlo
FROM edi.ektConfig ec;
DROP TEMPORARY TABLE IF EXISTS tmp.ekt;
CREATE TEMPORARY TABLE tmp.ekt
ENGINE = MEMORY
SELECT id ektFk FROM ekt LIMIT 0;
CASE
WHEN LENGTH(vBarcode) <= vFloridayBarcodeLength THEN
INSERT INTO tmp.ekt
SELECT id
FROM edi.ektRecent e
WHERE e.cps = vBarcode
OR e.batchNumber = vBarcode;
WHEN LENGTH(vBarcode) = vFloramondoBarcodeLength THEN
INSERT INTO tmp.ekt
SELECT e.id
FROM edi.ektRecent e
WHERE e.pro = MID(vBarcode,2,6)
AND CAST(e.ptd AS SIGNED) = MID(vBarcode,8,5);
ELSE
SET vBarcode = LPAD(vBarcode,vStandardBarcodeLength,'0');
SET vAuction = MID(vBarcode, 1, 3);
SET vKlo = MID(vBarcode, 4, 2);
SET vFec = MAKEDATE(YEAR(util.VN_CURDATE()), MID(vBarcode, 6, 3));
SET vShortAgj = MID(vBarcode, 9, 5);
SET vLongAgj = MID(vBarcode, 9, 7);
SET vXtraLongAgj = MID(vBarcode, 9, 8);
-- Clásico de subasta
-- Trade standard
-- Trade que construye como la subasta
-- Trade como el anterior pero sin trade code
INSERT INTO tmp.ekt
SELECT id
FROM ekt
WHERE fec >= vFec - INTERVAL 1 DAY
AND ((
vKlo = vDefaultKlo
AND (klo = vKlo OR klo IS NULL OR klo = 0)
AND agj IN (vShortAgj, vLongAgj, vXtraLongAgj))
OR (klo = vKlo
AND auction = vAuction
AND agj = vShortAgj)
)
ORDER BY agj DESC, fec DESC
LIMIT 1;
SELECT COUNT(*) FROM tmp.ekt INTO vIsFound;
-- BatchNumber largo
IF NOT vIsFound THEN
INSERT INTO tmp.ekt
SELECT id
FROM edi.ektRecent e
WHERE e.batchNumber
= LEFT(vBarcode,vUsefulAuctionLeftSegmentLength)
AND e.batchNumber > 0;
SELECT COUNT(*) FROM tmp.ekt INTO vIsFound;
END IF;
-- Order Number
IF NOT vIsFound THEN
INSERT INTO tmp.ekt
SELECT id
FROM edi.ektRecent e
WHERE e.putOrderFk = vBarcode;
SELECT COUNT(*) FROM tmp.ekt INTO vIsFound;
END IF;
-- deliveryNumber incrustado
IF NOT vIsFound THEN
INSERT INTO tmp.ekt
SELECT id
FROM edi.ektRecent e
WHERE e.deliveryNumber
= MID(vBarcode, 4, 13)
AND e.deliveryNumber > 0;
SELECT COUNT(*) FROM tmp.ekt INTO vIsFound;
END IF;
END CASE;
IF vIsFound THEN
UPDATE ekt e
JOIN tmp.ekt t ON t.ektFk = e.id
SET e.scanned = 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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `floramondo_offerRefresh` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `floramondo_offerRefresh`()
proc: BEGIN
DECLARE vLanded DATETIME;
DECLARE vDone INT DEFAULT FALSE;
DECLARE vFreeId INT;
DECLARE vSupplyResponseFk INT;
DECLARE vLastInserted DATETIME;
DECLARE vIsAuctionDay BOOLEAN;
DECLARE vMaxNewItems INT DEFAULT 10000;
DECLARE vStartingTime DATETIME;
DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043';
DECLARE vDayRange INT;
DECLARE cur1 CURSOR FOR
SELECT id
FROM edi.item_free;
DECLARE cur2 CURSOR FOR
SELECT srId
FROM itemToInsert;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLSTATE '45000'
BEGIN
ROLLBACK;
RESIGNAL;
END;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
DO RELEASE_LOCK('edi.floramondo_offerRefresh');
SET @isTriggerDisabled = FALSE;
RESIGNAL;
END;
IF 'test' = (SELECT environment FROM util.config) THEN
LEAVE proc;
END IF;
IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN
LEAVE proc;
END IF;
SELECT dayRange INTO vDayRange
FROM offerRefreshConfig;
IF vDayRange IS NULL THEN
CALL util.throw("Variable vDayRange not declared");
END IF;
SET vStartingTime = util.VN_NOW();
TRUNCATE edi.offerList;
INSERT INTO edi.offerList(supplier, total)
SELECT v.name, COUNT(DISTINCT sr.ID) total
FROM edi.supplyResponse sr
JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
WHERE sr.NumberOfUnits > 0
AND sr.EmbalageCode != 999
GROUP BY sr.vmpID;
UPDATE edi.offerList o
JOIN (SELECT v.name, COUNT(*) total
FROM edi.supplyOffer sr
JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
GROUP BY sr.vmpID) sub ON o.supplier = sub.name
SET o.`filter` = sub.total;
-- Elimina de la lista de items libres aquellos que ya existen
DELETE itf.*
FROM edi.item_free itf
JOIN vn.item i ON i.id = itf.id;
CREATE OR REPLACE TEMPORARY TABLE tmp
(INDEX (`Item_ArticleCode`))
ENGINE = MEMORY
SELECT t.*
FROM (
SELECT *
FROM edi.supplyOffer
ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC,
NumberOfUnits DESC LIMIT 10000000000000000000) t
GROUP BY t.srId;
CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`),
INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`),
INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`))
ENGINE = MEMORY
SELECT so.*,
ev1.type_description s1Value,
ev2.type_description s2Value,
ev3.type_description s3Value,
ev4.type_description s4Value,
ev5.type_description s5Value,
ev6.type_description s6Value,
eif1.feature ef1,
eif2.feature ef2,
eif3.feature ef3,
eif4.feature ef4,
eif5.feature ef5,
eif6.feature ef6
FROM tmp so
LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode
AND eif1.presentation_order = 1
AND eif1.expiry_date IS NULL
LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode
AND eif2.presentation_order = 2
AND eif2.expiry_date IS NULL
LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode
AND eif3.presentation_order = 3
AND eif3.expiry_date IS NULL
LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode
AND eif4.presentation_order = 4
AND eif4.expiry_date IS NULL
LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode
AND eif5.presentation_order = 5
AND eif5.expiry_date IS NULL
LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode
AND eif6.presentation_order = 6
AND eif6.expiry_date IS NULL
LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature
AND so.s1 = ev1.type_value
LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature
AND so.s2 = ev2.type_value
LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature
AND so.s3 = ev3.type_value
LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature
AND so.s4 = ev4.type_value
LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature
AND so.s5 = ev5.type_value
LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature
AND so.s6 = ev6.type_value
ORDER BY Price;
DROP TEMPORARY TABLE tmp;
DELETE o
FROM edi.offer o
LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size'
LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size'
LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size'
LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size'
LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size'
LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size'
JOIN vn.floramondoConfig fc ON TRUE
WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize)
OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize)
OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize)
OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize)
OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize)
OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize);
START TRANSACTION;
-- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos
UPDATE IGNORE edi.offer o
JOIN vn.item i
ON i.name = o.product_name
AND i.subname <=> o.company_name
AND i.value5 <=> o.s1Value
AND i.value6 <=> o.s2Value
AND i.value7 <=> o.s3Value
AND i.value8 <=> o.s4Value
AND i.value9 <=> o.s5Value
AND i.value10 <=> o.s6Value
AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask
AND i.EmbalageCode <=> o.EmbalageCode
AND i.quality <=> o.Quality
JOIN vn.itemType it ON it.id = i.typeFk
LEFT JOIN vn.sale s ON s.itemFk = i.id
LEFT JOIN vn.ticket t ON t.id = s.ticketFk
AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK)
LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk
LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID
LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk
AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK)
SET i.supplyResponseFk = o.srID
WHERE (sr.ID IS NULL
OR sr.NumberOfUnits = 0
OR di.LatestOrderDateTime < util.VN_NOW()
OR di.ID IS NULL)
AND it.isInventory
AND t.id IS NULL
AND po.id IS NULL;
CREATE OR REPLACE TEMPORARY TABLE itemToInsert
ENGINE = MEMORY
SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk
FROM edi.offer o
LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId
WHERE i.id IS NULL
LIMIT vMaxNewItems;
-- Reciclado de nº de item
OPEN cur1;
OPEN cur2;
read_loop: LOOP
FETCH cur2 INTO vSupplyResponseFk;
FETCH cur1 INTO vFreeId;
IF vDone THEN
LEAVE read_loop;
END IF;
UPDATE itemToInsert
SET itemFk = vFreeId
WHERE srId = vSupplyResponseFk;
END LOOP;
CLOSE cur1;
CLOSE cur2;
-- Insertamos todos los items en Articles de la oferta
INSERT INTO vn.item(id,
`name`,
longName,
subName,
expenseFk,
typeFk,
intrastatFk,
originFk,
supplyResponseFk,
numberOfItemsPerCask,
embalageCode,
quality,
isFloramondo)
SELECT iti.itemFk,
iti.product_name,
iti.product_name,
iti.company_name,
iti.expenseFk,
iti.itemTypeFk,
iti.intrastatFk,
iti.originFk,
iti.`srId`,
iti.NumberOfItemsPerCask,
iti.EmbalageCode,
iti.Quality,
TRUE
FROM itemToInsert iti;
-- Inserta la foto de los articulos nuevos (prioridad alta)
INSERT IGNORE INTO vn.itemImageQueue(itemFk, url)
SELECT i.id, PictureReference
FROM itemToInsert ii
JOIN vn.item i ON i.supplyResponseFk = ii.srId
WHERE PictureReference IS NOT NULL
AND i.image IS NULL;
INSERT INTO edi.`log`(tableName, fieldName,fieldValue)
SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*)
FROM vn.itemImageQueue
WHERE attempts = 0;
-- Inserta si se añadiesen tags nuevos
INSERT IGNORE INTO vn.tag (name, ediTypeFk)
SELECT description, type_id FROM edi.type;
-- Desabilita el trigger para recalcular los tags al final
SET @isTriggerDisabled = TRUE;
-- Inserta los tags sólo en los articulos nuevos
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT i.id, t.id , ii.product_name, 1
FROM itemToInsert ii
JOIN vn.tag t ON t.`name` = 'Producto'
JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
WHERE NOT ii.product_name IS NULL;
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT i.id, t.id , ii.Quality, 3
FROM itemToInsert ii
JOIN vn.tag t ON t.`name` = 'Calidad'
JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
WHERE NOT ii.Quality IS NULL;
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT i.id, t.id , ii.company_name, 4
FROM itemToInsert ii
JOIN vn.tag t ON t.`name` = 'Productor'
JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
WHERE NOT ii.company_name IS NULL;
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT i.id, t.id , s1Value, 5
FROM itemToInsert ii
JOIN vn.tag t ON t.ediTypeFk = ii.ef1
JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
WHERE NOT s1Value IS NULL;
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT i.id, t.id , s2Value, 6
FROM itemToInsert ii
JOIN vn.tag t ON t.ediTypeFk = ii.ef2
JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
WHERE NOT s2Value IS NULL;
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT i.id, t.id , s3Value, 7
FROM itemToInsert ii
JOIN vn.tag t ON t.ediTypeFk = ii.ef3
JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
WHERE NOT s3Value IS NULL;
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT i.id, t.id , s4Value, 8
FROM itemToInsert ii
JOIN vn.tag t ON t.ediTypeFk = ii.ef4
JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
WHERE NOT s4Value IS NULL;
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT i.id, t.id , s5Value, 9
FROM itemToInsert ii
JOIN vn.tag t ON t.ediTypeFk = ii.ef5
JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
WHERE NOT s5Value IS NULL;
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT i.id, t.id , s6Value, 10
FROM itemToInsert ii
JOIN vn.tag t ON t.ediTypeFk = ii.ef6
JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
WHERE NOT s6Value IS NULL;
INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11
FROM itemToInsert ii
JOIN vn.item i ON i.supplyResponseFk = ii.`srId`
JOIN vn.tag t ON t.`name` = 'Color'
LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode
LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id
AND tp.`description` = 'Hoofdkleur 1'
LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value
LEFT JOIN vn.itemInk ik ON ik.longName = i.longName
WHERE ink.name IS NOT NULL
OR ik.color IS NOT NULL;
CREATE OR REPLACE TABLE tmp.item
(PRIMARY KEY (id))
SELECT i.id FROM vn.item i
JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`;
CALL vn.item_refreshTags();
DROP TABLE tmp.item;
SELECT MIN(LatestDeliveryDateTime) INTO vLanded
FROM edi.supplyResponse sr
JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID
JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID
JOIN vn.floramondoConfig fc
WHERE mp.isLatestOrderDateTimeRelevant
AND di.LatestOrderDateTime > IF(
fc.MaxLatestOrderHour > HOUR(util.VN_NOW()),
util.VN_CURDATE(),
util.VN_CURDATE() + INTERVAL 1 DAY);
UPDATE vn.floramondoConfig
SET nextLanded = vLanded
WHERE vLanded IS NOT NULL;
-- Elimina la oferta obsoleta
UPDATE vn.buy b
JOIN vn.entry e ON e.id = b.entryFk
JOIN vn.travel tr ON tr.id = e.travelFk
JOIN vn.agencyMode am ON am.id = tr.agencyModeFk
JOIN vn.item i ON i.id = b.itemFk
LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID
LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk
SET b.quantity = 0
WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW()
OR i.supplyResponseFk IS NULL
OR sr.NumberOfUnits = 0)
AND am.name = 'LOGIFLORA'
AND e.isRaid;
-- Localiza las entradas de cada almacen
UPDATE edi.warehouseFloramondo
SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk);
IF vLanded IS NOT NULL THEN
-- Actualiza la oferta existente
UPDATE vn.buy b
JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk
JOIN vn.item i ON i.id = b.itemFk
JOIN edi.offer o ON i.supplyResponseFk = o.`srId`
SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask,
b.buyingValue = o.price
WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask
OR b.buyingValue <> o.price);
-- Inserta el resto
SET vLastInserted := util.VN_NOW();
-- Inserta la oferta
INSERT INTO vn.buy (
entryFk,
itemFk,
quantity,
buyingValue,
stickers,
packing,
`grouping`,
groupingMode,
packagingFk,
deliveryFk)
SELECT wf.entryFk,
i.id,
o.NumberOfUnits * o.NumberOfItemsPerCask quantity,
o.Price,
o.NumberOfUnits etiquetas,
o.NumberOfItemsPerCask packing,
GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`,
'packing',
o.embalageCode,
o.diId
FROM edi.offer o
JOIN vn.item i ON i.supplyResponseFk = o.srId
JOIN edi.warehouseFloramondo wf
JOIN vn.packaging p ON p.id
LIKE o.embalageCode
LEFT JOIN vn.buy b ON b.itemFk = i.id
AND b.entryFk = wf.entryFk
WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL
INSERT INTO vn.itemCost(
itemFk,
warehouseFk,
cm3,
cm3delivery)
SELECT b.itemFk,
wf.warehouseFk,
@cm3 := vn.buy_getUnitVolume(b.id),
IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3)
FROM warehouseFloramondo wf
JOIN vn.volumeConfig vc
JOIN vn.buy b ON b.entryFk = wf.entryFk
JOIN vn.item i ON i.id = b.itemFk
LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk
AND ic.warehouseFk = wf.warehouseFk
WHERE (ic.cm3 IS NULL OR ic.cm3 = 0)
ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3);
CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc
SELECT b.id
FROM vn.buy b
JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk
WHERE b.created >= vLastInserted;
CALL vn.buy_recalcPrices();
UPDATE edi.offerList o
JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total
FROM vn.buy b
JOIN vn.item i ON i.id = b.itemFk
JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk
JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk
JOIN vn.warehouse w ON w.id = wf.warehouseFk
WHERE w.name = 'VNH'
AND b.quantity > 0
GROUP BY sr.vmpID) sub ON o.supplier = sub.name
SET o.vnh = sub.total;
UPDATE edi.offerList o
JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total
FROM vn.buy b
JOIN vn.item i ON i.id = b.itemFk
JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk
JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk
JOIN vn.warehouse w ON w.id = wf.warehouseFk
WHERE w.name = 'ALGEMESI'
AND b.quantity > 0
GROUP BY sr.vmpID) sub ON o.supplier = sub.name
SET o.algemesi = sub.total;
END IF;
DROP TEMPORARY TABLE
edi.offer,
itemToInsert;
SET @isTriggerDisabled = FALSE;
COMMIT;
-- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias
UPDATE vn.item i
SET typeFk = 121
WHERE i.longName LIKE 'Rosa Garden %'
AND typeFk = 17;
UPDATE vn.item i
SET typeFk = 156
WHERE i.longName LIKE 'Rosa ec %'
AND typeFk = 17;
-- Refresca las fotos de los items existentes que mostramos (prioridad baja)
INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority)
SELECT i.id, sr.PictureReference, 100
FROM edi.supplyResponse sr
JOIN vn.item i ON i.supplyResponseFk = sr.ID
JOIN edi.supplyOffer so ON so.srId = sr.ID
JOIN hedera.image i2 ON i2.name = i.image
AND i2.collectionFk = 'catalog'
WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange)
AND sr.NumberOfUnits;
INSERT INTO edi.`log`
SET tableName = 'floramondo_offerRefresh',
fieldName = 'Tiempo de proceso',
fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime);
DO RELEASE_LOCK('edi.floramondo_offerRefresh');
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_freeAdd` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_freeAdd`()
BEGIN
/**
* Rellena la tabla item_free con los id ausentes en vn.item
*
*/
DECLARE vMaxItem INT;
SELECT MAX(id)
INTO vMaxItem
FROM vn.item;
DROP TEMPORARY TABLE IF EXISTS tmp.itemBusy;
CREATE TEMPORARY TABLE tmp.itemBusy
(id INT PRIMARY KEY)
SELECT i.id
FROM vn.item i
WHERE i.isFloramondo
UNION ALL
SELECT ifr.id
FROM edi.item_free ifr;
INSERT INTO edi.item_free(id)
SELECT i.id
FROM vn.item i
LEFT JOIN tmp.itemBusy ib ON ib.id = i.id
WHERE i.isFloramondo AND ib.id is null;
DROP TEMPORARY TABLE IF EXISTS tmp.itemBusy;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_getNewByEkt` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getNewByEkt`(vEktFk INT, OUT vItemFk INT)
BEGIN
/**
* Devuelve un número nuevo de item a partir de un registro de la tabla edi.ekt
*
* @param vEktFk Identificador de la tabla edi.ekt
*/
START TRANSACTION;
SELECT MIN(id) id INTO vItemFk
FROM edi.item_free;
DELETE FROM edi.item_free
WHERE id = vItemFk;
COMMIT;
IF ISNULL(vItemFk) THEN
SELECT MAX(i.id) + 1
INTO vItemFk
FROM vn.item i;
END IF;
INSERT INTO vn.item(id,
`name`,
longName,
subName,
expenseFk,
typeFk,
intrastatFk,
originFk,
numberOfItemsPerCask,
embalageCode,
quality,
isFloramondo
)
SELECT vItemFk,
e.item,
e.item,
e.item,
igto.expenseFk,
igto.itemTypeFk,
igto.intrastatFk,
igto.originFk,
e.pac,
least(IF((e.package = 800),((e.package * 10) + e.pac), e.package), IFNULL(idt.bucket_id, '999')) packageFk,
e.cat,
TRUE
FROM edi.ekt e
JOIN edi.item i ON i.id = e.`ref`
JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id
LEFT JOIN edi.item_defaultType idt ON idt.item_id = e.`ref`
WHERE e.id = vEktFk;
SET @isTriggerDisabled = TRUE;
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT vItemFk, t.id , e.item , 1
FROM edi.ekt e
JOIN vn.tag t ON t.`name` = 'Producto'
WHERE e.id = vEktFk
AND NOT ISNULL(e.item);
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT vItemFk, t.id , e.cat , 3
FROM edi.ekt e
JOIN vn.tag t ON t.`name` = 'Calidad'
WHERE e.id = vEktFk
AND NOT ISNULL(e.cat);
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT vItemFk, t.id , s.company_name , 4
FROM edi.ekt e
JOIN edi.supplier s ON s.supplier_id = e.pro
JOIN vn.tag t ON t.`name` = 'Productor'
WHERE e.id = vEktFk
AND NOT ISNULL(s.company_name);
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT vItemFk, t.id , e.s1, 5
FROM edi.ekt e
LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
AND eif.presentation_order = 1
AND eif.expiry_date IS NULL
LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
AND e.s1 = ev.type_value
JOIN vn.tag t ON t.ediTypeFk = eif.feature
WHERE e.id = vEktFk
AND NOT ISNULL(e.s1);
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT vItemFk, t.id , e.s2, 6
FROM edi.ekt e
LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
AND eif.presentation_order = 2
AND eif.expiry_date IS NULL
LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
AND e.s2 = ev.type_value
JOIN vn.tag t ON t.ediTypeFk = eif.feature
WHERE e.id = vEktFk
AND NOT ISNULL(e.s2);
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT vItemFk, t.id , e.s3, 7
FROM edi.ekt e
LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
AND eif.presentation_order = 3
AND eif.expiry_date IS NULL
LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
AND e.s3 = ev.type_value
JOIN vn.tag t ON t.ediTypeFk = eif.feature
WHERE e.id = vEktFk
AND NOT ISNULL(e.s3);
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT vItemFk, t.id , e.s4, 8
FROM edi.ekt e
LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
AND eif.presentation_order = 4
AND eif.expiry_date IS NULL
LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
AND e.s4 = ev.type_value
JOIN vn.tag t ON t.ediTypeFk = eif.feature
WHERE e.id = vEktFk
AND NOT ISNULL(e.s4);
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT vItemFk, t.id , e.s5, 9
FROM edi.ekt e
LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
AND eif.presentation_order = 5
AND eif.expiry_date IS NULL
LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
AND e.s5 = ev.type_value
JOIN vn.tag t ON t.ediTypeFk = eif.feature
WHERE e.id = vEktFk
AND NOT ISNULL(e.s5);
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT vItemFk, t.id , e.s6, 10
FROM edi.ekt e
LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref`
AND eif.presentation_order = 6
AND eif.expiry_date IS NULL
LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature
AND e.s6 = ev.type_value
JOIN vn.tag t ON t.ediTypeFk = eif.feature
WHERE e.id = vEktFk
AND NOT ISNULL(e.s6);
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT vItemFk, t.id, IFNULL(ink.name, ik.color), 11
FROM edi.ekt e
JOIN vn.tag t ON t.`name` = 'Color'
LEFT JOIN edi.feature f ON f.item_id = e.`ref`
LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id AND tp.`description` = 'Hoofdkleur 1'
LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value
LEFT JOIN vn.itemInk ik ON ik.longName = e.item
WHERE e.id = vEktFk
AND ( ink.name IS NOT NULL
OR ik.color IS NOT NULL)
LIMIT 1;
DROP TABLE IF EXISTS tmp.item;
CREATE TABLE tmp.item
(PRIMARY KEY (id))
SELECT vItemFk id ;
CALL vn.item_refreshTags();
SET @isTriggerDisabled = FALSE;
INSERT IGNORE INTO vn.itemImageQueue(itemFk, url)
SELECT vItemFk, sr.PictureReference
FROM edi.ekt e
JOIN edi.supplyResponse sr ON e.ref = sr.Item_ArticleCode
WHERE e.id = vEktFk
AND NOT sr.PictureReference IS NULL
ORDER BY sr.created DESC
LIMIT 1;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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: `floranet`
--
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `floranet` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */;
USE `floranet`;
--
-- Table structure for table `addressPostCode`
--
DROP TABLE IF EXISTS `addressPostCode`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `addressPostCode` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`addressFk` int(11) NOT NULL,
`postCode` varchar(30) NOT NULL,
`hoursInAdvance` int(10) unsigned NOT NULL DEFAULT 24,
`dayOfWeek` int(10) unsigned NOT NULL,
`deliveryCost` decimal(10,2) NOT NULL DEFAULT 0.00,
PRIMARY KEY (`id`),
UNIQUE KEY `addressPostCode_unique` (`postCode`,`addressFk`,`dayOfWeek`),
KEY `addressPostCode_address_FK` (`addressFk`),
CONSTRAINT `addressPostCode_address_FK` FOREIGN KEY (`addressFk`) REFERENCES `vn`.`address` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='Client''s address registered for floranet network';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `builder`
--
DROP TABLE IF EXISTS `builder`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `builder` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`itemFk` int(11) NOT NULL,
`elementFk` int(11) NOT NULL,
`quantity` int(10) unsigned NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
KEY `builder_FK` (`itemFk`),
KEY `builder_FK_1` (`elementFk`),
CONSTRAINT `builder_FK` FOREIGN KEY (`itemFk`) REFERENCES `vn`.`item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `builder_FK_1` FOREIGN KEY (`elementFk`) REFERENCES `element` (`itemFk`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='Links handmade products with their elements';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `catalogue`
--
DROP TABLE IF EXISTS `catalogue`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `catalogue` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`price` decimal(10,2) NOT NULL,
`itemFk` int(11) NOT NULL,
`dated` date DEFAULT NULL,
`postalCode` varchar(12) DEFAULT NULL,
`type` varchar(50) DEFAULT NULL,
`image` varchar(255) DEFAULT NULL,
`description` text DEFAULT NULL,
`created` timestamp NULL DEFAULT current_timestamp(),
`payed` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `itemFk` (`itemFk`),
CONSTRAINT `catalogue_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `vn`.`item` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `element`
--
DROP TABLE IF EXISTS `element`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `element` (
`itemFk` int(11) NOT NULL,
`typeFk` smallint(5) unsigned DEFAULT NULL,
`size` int(11) DEFAULT NULL,
`inkFk` char(3) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`originFk` tinyint(2) unsigned DEFAULT NULL,
`name` varchar(30) DEFAULT NULL,
`quantity` int(11) NOT NULL DEFAULT 1,
PRIMARY KEY (`itemFk`),
KEY `element_FK` (`itemFk`),
KEY `element_FK_1` (`typeFk`),
KEY `element_FK_2` (`inkFk`),
KEY `element_FK_3` (`originFk`),
CONSTRAINT `element_FK` FOREIGN KEY (`itemFk`) REFERENCES `vn`.`item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `element_FK_1` FOREIGN KEY (`typeFk`) REFERENCES `vn`.`itemType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `element_FK_2` FOREIGN KEY (`inkFk`) REFERENCES `vn`.`ink` (`id`) ON UPDATE CASCADE,
CONSTRAINT `element_FK_3` FOREIGN KEY (`originFk`) REFERENCES `vn`.`origin` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='Filtro para localizar posibles items que coincidan con la descripción';
/*!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(11) NOT NULL AUTO_INCREMENT,
`catalogueFk` int(11) DEFAULT NULL,
`customerName` varchar(100) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
`customerPhone` varchar(15) DEFAULT NULL,
`message` varchar(255) DEFAULT NULL,
`deliveryName` varchar(100) DEFAULT NULL,
`address` varchar(200) DEFAULT NULL,
`deliveryPhone` varchar(100) DEFAULT NULL,
`isPaid` tinyint(1) NOT NULL DEFAULT 0,
`payed` datetime DEFAULT NULL,
`created` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
UNIQUE KEY `catalogueFk` (`catalogueFk`),
CONSTRAINT `order_ibfk_1` FOREIGN KEY (`catalogueFk`) REFERENCES `catalogue` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping events for database 'floranet'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `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 = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `clean` ON SCHEDULE EVERY 1 DAY STARTS '2024-01-01 23:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN
DELETE
FROM `order`
WHERE created < CURDATE()
AND isPaid = FALSE;
DELETE c.*
FROM catalogue c
LEFT JOIN `order` o ON o.catalogueFk = c.id
WHERE c.created < CURDATE()
AND o.id IS NULL;
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 */ ;;
DELIMITER ;
/*!50106 SET TIME_ZONE= @save_time_zone */ ;
--
-- Dumping routines for database 'floranet'
--
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `catalogue_findById` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `catalogue_findById`(vSelf INT)
READS SQL DATA
BEGIN
/**
* Returns one recordset from catalogue
*
* @param vCatalogueFk Identifier de floranet.catalogue
*/
SELECT * FROM catalogue 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `catalogue_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `catalogue_get`(vLanded DATE, vPostalCode VARCHAR(15))
READS SQL DATA
proc:BEGIN
/**
* Returns list, price and all the stuff regarding the floranet items.
*
* @param vLanded Delivery date
* @param vPostalCode Delivery address postal code
*/
DECLARE vLastCatalogueFk INT;
DECLARE vLockName VARCHAR(20);
DECLARE vLockTime INT;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
DO RELEASE_LOCK(vLockName);
RESIGNAL;
END;
SET vLockName = 'catalogue_get';
SET vLockTime = 15;
IF NOT GET_LOCK(vLockName, vLockTime) THEN
LEAVE proc;
END IF;
SELECT MAX(id) INTO vLastCatalogueFk
FROM catalogue;
INSERT INTO catalogue(
name,
price,
itemFk,
dated,
postalCode,
`type`,
image,
description
)
SELECT i.name,
i.`size`,
i.id,
vLanded,
vPostalCode,
it.name,
CONCAT('https://cdn.verdnatura.es/image/catalog/1600x900/', i.image),
i.description
FROM vn.item i
JOIN vn.itemType it ON it.id = i.typeFk
WHERE it.code IN ('FNR','FNP');
SELECT *
FROM catalogue
WHERE id > IFNULL(vLastCatalogueFk,0);
DO RELEASE_LOCK(vLockName);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `contact_request` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `contact_request`(
vName VARCHAR(100),
vPhone VARCHAR(15),
vEmail VARCHAR(100),
vMessage TEXT)
READS SQL DATA
BEGIN
/**
* Set actions for contact request
*
* @param vPostalCode Delivery address postal 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `deliveryDate_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `deliveryDate_get`(vPostalCode VARCHAR(15))
READS SQL DATA
BEGIN
/**
* Returns available dates for this postalCode, in the next seven days.
*
* @param vPostalCode Delivery address postal code
*/
DECLARE vCurrentDayOfWeek INT;
SET vCurrentDayOfWeek = DAYOFWEEK(NOW());
SELECT DISTINCT nextDay
FROM (
SELECT CURDATE() + INTERVAL IF(
apc.dayOfWeek >= vCurrentDayOfWeek,
apc.dayOfWeek - vCurrentDayOfWeek,
7 - apc.dayOfWeek
) DAY nextDay,
NOW() + INTERVAL apc.hoursInAdvance - 12 HOUR minDeliveryTime
FROM addressPostCode apc
WHERE apc.postCode = vPostalCode
HAVING nextDay > minDeliveryTime) 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `order_confirm`(vCatalogueFk INT)
READS SQL DATA
BEGIN
/** Update order.isPaid field.
*
* @param vCatalogueFk floranet.catalogue.id
*
* @returns floranet.order.isPaid
*/
UPDATE `order`
SET isPaid = TRUE,
payed = NOW()
WHERE catalogueFk = vCatalogueFk;
SELECT isPaid
FROM `order`
WHERE catalogueFk = vCatalogueFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `order_put` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `order_put`(vJsonData JSON)
READS SQL DATA
BEGIN
/**
* Get and process an order.
*
* @param vJsonData The order data in json format
*/
INSERT INTO `order`
SET catalogueFk = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.products[0].id')),
customerName = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.customerName')),
email = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.email')),
customerPhone = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.customerPhone')),
message= JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.message')),
deliveryName = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.deliveryName')),
address = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.address')),
deliveryPhone = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.deliveryPhone'));
SELECT LAST_INSERT_ID() 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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sliders_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sliders_get`()
READS SQL DATA
BEGIN
/**
* Returns list of url for sliders.
*/
SELECT
CONCAT('https://cdn.verdnatura.es/image/catalog/1600x900/', i.image) url,
i.longName
FROM vn.item i
JOIN vn.itemType it ON it.id = i.typeFk
WHERE it.code IN ('FNR','FNP')
LIMIT 3;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
--
-- Current Database: `hedera`
--
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `hedera` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci 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=utf8mb3 COLLATE=utf8mb3_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) NOT NULL COMMENT 'Browser name in browscap',
`version` float NOT NULL COMMENT 'Minimal version',
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`defaultLang` char(2) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci 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) NOT NULL COMMENT 'The key used to encode/decode JWT tokens',
`defaultForm` varchar(50) DEFAULT NULL COMMENT 'Form loaded at web login',
`restUri` varchar(255) NOT NULL COMMENT 'The URI for rest service',
`testRestUri` varchar(255) NOT NULL COMMENT 'The URI for test rest service',
`guestUser` varchar(50) DEFAULT NULL COMMENT 'Guest user name',
`testDomain` varchar(255) DEFAULT NULL COMMENT 'The address for beta website',
`productionDomain` varchar(255) DEFAULT NULL COMMENT 'The address for production website',
`pdfsDir` varchar(255) NOT NULL COMMENT 'Directory where PDFs are allocated',
`dmsDir` varchar(255) DEFAULT NULL COMMENT 'Directory where documents are allocated',
PRIMARY KEY (`id`),
KEY `jwtkey_IX` (`jwtKey`) COMMENT 'Prueba de Ernesto 3.8.2020. MySQL se queja de no tener indices. Si, se que solo tiene un registro pero molesta para depurar otros.',
CONSTRAINT `config_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`name` varchar(255) NOT NULL,
`updated` bigint(20) unsigned DEFAULT NULL,
`nRefs` int(10) unsigned NOT NULL DEFAULT 0 COMMENT 'Number of references, don''t modify this column manually',
PRIMARY KEY (`id`),
UNIQUE KEY `collection` (`collectionFk`,`name`),
CONSTRAINT `image_ibfk_1` FOREIGN KEY (`collectionFk`) REFERENCES `imageCollection` (`name`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`desc` varchar(50) NOT NULL,
`maxWidth` int(10) unsigned NOT NULL,
`maxHeight` int(10) unsigned NOT NULL,
`model` varchar(255) DEFAULT NULL,
`property` varchar(255) DEFAULT NULL,
`schema` varchar(50) NOT NULL COMMENT 'Deprecated',
`table` varchar(50) NOT NULL COMMENT 'Deprecated',
`column` varchar(50) NOT NULL COMMENT 'Deprecated',
`readRoleFk` int(10) unsigned DEFAULT 1,
`writeRoleFk` int(10) unsigned DEFAULT 1,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
KEY `role_id_writeRoleFk` (`writeRoleFk`),
KEY `role_id_readRoleFk` (`readRoleFk`),
CONSTRAINT `role_id_readRoleFk` FOREIGN KEY (`readRoleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE,
CONSTRAINT `role_id_writeRoleFk` FOREIGN KEY (`writeRoleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `imageCollectionSize`
--
DROP TABLE IF EXISTS `imageCollectionSize`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `imageCollectionSize` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`collectionFk` int(10) unsigned NOT NULL,
`width` int(10) unsigned NOT NULL,
`height` int(10) unsigned NOT NULL,
`crop` tinyint(3) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY `image_schema_id` (`collectionFk`),
CONSTRAINT `imageCollectionSize_ibfk_1` FOREIGN KEY (`collectionFk`) REFERENCES `imageCollection` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`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`),
CONSTRAINT `imageConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci 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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`name` varchar(20) NOT NULL,
`orgName` varchar(255) NOT NULL,
`isActive` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`description` varchar(255) NOT NULL,
`link` varchar(255) NOT NULL,
`image` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `location`
--
DROP TABLE IF EXISTS `location`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `location` (
`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`lat` varchar(12) NOT NULL,
`lng` varchar(12) NOT NULL,
`title` varchar(50) NOT NULL,
`address` varchar(75) DEFAULT NULL,
`postcode` varchar(15) DEFAULT NULL,
`city` varchar(50) DEFAULT NULL,
`province` varchar(50) DEFAULT NULL,
`phone` varchar(20) DEFAULT NULL,
`language` char(2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`host` varchar(255) 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) NOT NULL COMMENT 'The sender mail address',
`senderName` varchar(75) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT 'The sender name',
`user` varchar(50) DEFAULT NULL COMMENT 'SMTP user',
`password` varchar(100) DEFAULT NULL COMMENT 'SMTP password, base64 encoded',
PRIMARY KEY (`id`),
CONSTRAINT `mailConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`path` varchar(50) DEFAULT NULL,
`roleFk` int(10) unsigned NOT NULL,
`parentFk` int(10) unsigned DEFAULT NULL,
`displayOrder` tinyint(4) unsigned NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
KEY `group_id` (`roleFk`),
KEY `parent` (`parentFk`),
CONSTRAINT `menu_ibfk_1` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`description` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `messageI18n`
--
DROP TABLE IF EXISTS `messageI18n`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `messageI18n` (
`code` char(35) NOT NULL,
`lang` char(2) NOT NULL,
`description` varchar(255) NOT NULL,
PRIMARY KEY (`code`,`lang`),
CONSTRAINT `messageI18nFk` FOREIGN KEY (`code`) REFERENCES `message` (`code`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `messageL10n`
--
DROP TABLE IF EXISTS `messageL10n`;
/*!50001 DROP VIEW IF EXISTS `messageL10n`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `messageL10n` AS SELECT
1 AS `code`,
1 AS `description` */;
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) NOT NULL,
`content` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `agencyModeFk` */;
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 `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 `sent`,
1 AS `clientFk`,
1 AS `deliveryMethodFk`,
1 AS `agencyModeFk`,
1 AS `addressFk`,
1 AS `companyFk`,
1 AS `notes`,
1 AS `sourceApp`,
1 AS `isConfirmed`,
1 AS `created`,
1 AS `firstRowStamp`,
1 AS `confirmed`,
1 AS `taxableBase`,
1 AS `tax`,
1 AS `total` */;
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 `orderFk`,
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 `myTicketService`
--
DROP TABLE IF EXISTS `myTicketService`;
/*!50001 DROP VIEW IF EXISTS `myTicketService`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `myTicketService` AS SELECT
1 AS `id`,
1 AS `description`,
1 AS `quantity`,
1 AS `price`,
1 AS `taxClassFk`,
1 AS `ticketFk`,
1 AS `ticketServiceTypeFk` */;
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) NOT NULL,
`text` text NOT NULL,
`image` varchar(100) 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) NOT NULL DEFAULT 'new',
PRIMARY KEY (`id`),
KEY `user` (`userFk`),
KEY `tag` (`tag`),
CONSTRAINT `news_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`account` (`id`) ON UPDATE CASCADE,
CONSTRAINT `news_ibfk_2` FOREIGN KEY (`tag`) REFERENCES `newsTag` (`name`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `newsTag`
--
DROP TABLE IF EXISTS `newsTag`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `newsTag` (
`name` varchar(15) NOT NULL,
`description` varchar(25) NOT NULL,
PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`source_app` set('WEB','ANDROID','IOS','SALIX','TPV','TABLET_VN','') 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,
`configured` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `address` (`address_id`),
KEY `delivery_method` (`delivery_method_id`),
KEY `agency` (`agency_id`),
KEY `customer_id` (`customer_id`),
KEY `company_id` (`company_id`),
KEY `id` (`id`,`customer_id`),
KEY `source_app` (`source_app`),
KEY `confirmed` (`confirmed`),
CONSTRAINT `order_ibfk_5` FOREIGN KEY (`address_id`) REFERENCES `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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `orderConfig`
--
DROP TABLE IF EXISTS `orderConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `orderConfig` (
`id` int(10) unsigned NOT NULL,
`employeeFk` int(10) unsigned NOT NULL,
`defaultAgencyFk` int(11) DEFAULT NULL,
`guestMethod` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`guestAgencyFk` int(11) NOT NULL,
`reserveTime` time NOT NULL,
`defaultCompanyFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `employeeFk` (`employeeFk`),
KEY `guestAgencyFk` (`guestAgencyFk`),
KEY `defaultCompanyFk` (`defaultCompanyFk`),
KEY `guestMethod` (`guestMethod`),
KEY `defaultAgencyFk` (`defaultAgencyFk`),
CONSTRAINT `orderConfigCompany_Fk` FOREIGN KEY (`defaultCompanyFk`) REFERENCES `vn`.`company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `orderConfig_ibfk_1` FOREIGN KEY (`employeeFk`) REFERENCES `vn`.`worker` (`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_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `orderRow`
--
DROP TABLE IF EXISTS `orderRow`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `orderRow` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`orderFk` int(10) unsigned NOT NULL DEFAULT 0,
`itemFk` int(11) NOT NULL DEFAULT 0,
`warehouseFk` int(11) DEFAULT NULL,
`shipment` date DEFAULT NULL,
`amount` smallint(6) unsigned NOT NULL DEFAULT 0,
`price` decimal(10,2) DEFAULT NULL,
`rate` smallint(5) unsigned DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`saleFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `item` (`itemFk`),
KEY `order_id` (`orderFk`),
KEY `created` (`created`),
KEY `warehouse_shipment` (`warehouseFk`,`shipment`),
KEY `orderRow_ibfk_4` (`saleFk`),
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,
CONSTRAINT `orderRow_ibfk_4` FOREIGN KEY (`saleFk`) REFERENCES `vn`.`sale` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`role` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `role` (`role`),
CONSTRAINT `restPriv_ibfk_1` FOREIGN KEY (`role`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) 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=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`namePrefix` varchar(50) 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`),
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`link` varchar(255) NOT NULL,
`icon` varchar(50) NOT NULL,
`priority` tinyint(3) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `priority` (`priority`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`votes` int(10) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY `survey` (`surveyFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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,
`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) unsigned NOT NULL,
`url` varchar(255) 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 utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT 'The bank web service URL for test environment',
`testKey` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT 'The bank secret key for test environment',
`merchantUrl` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `employee_id` (`employeeFk`),
CONSTRAINT `employee_id` FOREIGN KEY (`employeeFk`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `tpvConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`message` varchar(255) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`host` varchar(150) NOT NULL,
`user` varchar(50) NOT NULL,
`pass` varchar(50) NOT NULL,
`cleanPeriod` varchar(15) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`successFolder` varchar(150) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`errorFolder` varchar(150) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `tpvImapConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) 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) 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=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`status` enum('started','ok','ko') NOT NULL DEFAULT 'started',
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`merchantParameters` text DEFAULT NULL,
`signature` varchar(255) DEFAULT NULL,
`signatureVersion` varchar(50) DEFAULT NULL,
`responseError` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `merchant_id` (`merchantFk`),
KEY `receipt_id` (`receiptFk`),
KEY `user_id` (`clientFk`),
KEY `response` (`response`),
KEY `error_code` (`errorCode`),
KEY `tpvTransaction_status_IDX` (`status`,`receiptFk`) USING BTREE,
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`data` text DEFAULT NULL,
`userVisitFk` int(10) unsigned DEFAULT NULL,
UNIQUE KEY `ssid` (`ssid`),
KEY `userVisit` (`userVisitFk`),
KEY `lastUpdate` (`lastUpdate`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`browser` varchar(30) DEFAULT NULL,
`version` varchar(15) DEFAULT NULL,
`javascript` tinyint(3) unsigned DEFAULT NULL,
`cookies` tinyint(3) unsigned DEFAULT NULL,
`agent` varchar(255) 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping events for database 'hedera'
--
--
-- Dumping routines for database 'hedera'
--
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `myClient_getDebt`(vDate DATE) RETURNS decimal(10,2)
DETERMINISTIC
BEGIN
/**
* Calcula el saldo del cliente actual.
*
* @return Saldo del cliente
*/
RETURN vn.client_getDebt(account.myUser_getId(), 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `myUser_checkRestPriv`(vMethodPath VARCHAR(255)) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
/**
* Checks if the current user has permission to run a REST service.
*
* @param vMethodPath Route of the REST service
* @return %TRUE if it has permissions, otherwise %FALSE
*/
DECLARE vCount INT;
DECLARE vHasRole INT DEFAULT NULL;
SELECT COUNT(*) INTO vCount FROM restPriv
WHERE methodPath = vMethodPath;
IF vCount = 0 THEN
RETURN FALSE;
END IF;
SELECT COUNT(*) > 0
INTO vHasRole
FROM restPriv
WHERE methodPath = vMethodPath
AND (`role` IS NULL OR account.myUser_hasRoleId(`role`))
LIMIT 1;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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, FALSE);
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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` = util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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, FALSE);
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_getVisible` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 vn.getInventoryDate();
DECLARE EXIT HANDLER FOR 1114
BEGIN
GET DIAGNOSTICS CONDITION 1
@message = MESSAGE_TEXT;
CALL vn.mail_insert(
'cau@verdnatura.es',
NULL,
CONCAT('hedera.item_getVisible error: ', @message),
CONCAT(
'warehouse: ', IFNULL(vWarehouse, ''),
', Fecha:', IFNULL(vDate, ''),
', tipo: ', IFNULL(vType,''),
', prefijo: ', IFNULL(vPrefix,'')));
RESIGNAL;
END;
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 util.VN_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.ticketFk = t.id
WHERE t.shipped BETWEEN vDateInv AND util.VN_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.packagingFk, 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.packagingFk IS NOT NULL
ORDER BY t.warehouseInFk = vWarehouse DESC, t.landed DESC
LIMIT 10000000000000000000
) 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.packagingFk
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_addItem`(
vSelf INT,
vWarehouse INT,
vItem INT,
vAmount INT)
BEGIN
CALL myOrder_checkMine(vSelf);
CALL order_addItem(vSelf, vWarehouse, vItem, vAmount);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myOrder_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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_calcCatalogFromItem`(vSelf INT, vItem INT)
BEGIN
/**
* Gets the availability and prices for the given item
* using current user order parameters.
*
* @table tmp.item(itemFk)
* @return tmp.ticketCalculateItem
* @return tmp.ticketComponentPrice
* @return tmp.ticketComponent
* @return tmp.ticketLot
* @return tmp.zoneGetShipped
*/
CALL myOrder_checkMine(vSelf);
CALL order_calcCatalogFromItem(vSelf, 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myOrder_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_calcCatalogFull`(vSelf INT)
BEGIN
/**
* Gets the availability and prices for the given items
* using current user order parameters.
*
* @table tmp.item(itemFk)
* @return tmp.ticketCalculateItem
* @return tmp.ticketComponentPrice
* @return tmp.ticketComponent
* @return tmp.ticketLot
* @return tmp.zoneGetShipped
*/
CALL myOrder_checkMine(vSelf);
CALL order_calcCatalogFull(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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myOrder_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_checkConfig`(vSelf INT)
proc: 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
*/
CALL myOrder_checkMine(vSelf);
CALL order_checkConfig(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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myOrder_checkMine` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_checkMine`(vSelf INT)
proc: BEGIN
/**
* Check that order is owned by current user, otherwise throws an error.
*
* @param vSelf The order id
*/
DECLARE vIsMine BOOL;
SELECT COUNT(*) > 0 INTO vIsMine
FROM `order`
WHERE id = vSelf
AND customer_id = account.myUser_getId();
IF NOT vIsMine THEN
CALL util.throw('orderNotOwnedByUser');
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myOrder_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_configure`(
vSelf INT,
vDelivery DATE,
vDeliveryMethod VARCHAR(45),
vAgency INT,
vAddress INT)
BEGIN
/**
* Creates an order with passed parameters. If passed parameters are wrong
* it returns an error.
*
* @param vSelf The order id
* @param vDelivery Delivery date
* @param vDeliveryMethod Delivery method code
* @param vAgency Agency id
* @param vAddress Address id, @NULL for pickup
*/
CALL myOrder_checkMine(vSelf);
IF vAddress IS NOT NULL
AND NOT (SELECT COUNT(*) FROM myAddress WHERE id = vAddress) THEN
CALL util.throw('addressNotOwnedByUser');
END IF;
CALL order_configure(
vSelf,
vDelivery,
vDeliveryMethod,
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myOrder_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_configureForGuest`(OUT vSelf INT)
BEGIN
DECLARE vMethod VARCHAR(255);
DECLARE vAgency INT;
DECLARE vAddress INT;
DECLARE vDate DATE;
SELECT cf.guestMethod, cf.guestAgencyFk, cl.defaultAddressFk
INTO vMethod, vAgency, vAddress
FROM orderConfig cf
JOIN myClient cl
LIMIT 1;
SET vDate = TIMESTAMPADD(DAY, 1, util.VN_CURDATE());
IF WEEKDAY(vDate) BETWEEN 5 AND 6 THEN
SET vDate = TIMESTAMPADD(DAY, 7 - WEEKDAY(vDate), vDate);
END IF;
SELECT id INTO vSelf
FROM myOrder
WHERE NOT isConfirmed
ORDER BY id DESC
LIMIT 1;
IF vSelf IS NULL THEN
CALL myOrder_create(
vSelf,
vDate,
vMethod,
vAgency,
vAddress
);
ELSE
CALL myOrder_configure(
vSelf,
vDate,
vMethod,
vAgency,
vAddress
);
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_confirm`(vSelf INT)
BEGIN
CALL myOrder_checkMine(vSelf);
CALL order_checkConfig(vSelf);
CALL order_confirm(vSelf);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myOrder_create` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_create`(
OUT vSelf INT,
vDelivery DATE,
vDeliveryMethod VARCHAR(45),
vAgency INT,
vAddress INT)
proc: BEGIN
/**
* Creates a new order for the current user. If passed parameters are wrong
* it returns an error.
*
* @param vDelivery Delivery date
* @param vDeliveryMethod Delivery method code
* @param vAgency Agency id
* @param vAddress Address id, @NULL for pickup
*/
DECLARE vCompany INT;
SELECT defaultCompanyFk INTO vCompany
FROM orderConfig;
INSERT INTO `order`
SET customer_id = account.myUser_getId(),
source_app = 'WEB',
company_id = vCompany;
SET vSelf = LAST_INSERT_ID();
CALL myOrder_configure(
vSelf,
vDelivery,
vDeliveryMethod,
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_getAvailable`(vSelf INT)
BEGIN
/**
* Gets the available items list.
*
* @param vSelf The order id
* @table tmp.itemAvailable
*/
CALL myOrder_checkMine(vSelf);
CALL order_getAvailable(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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myOrder_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_getTax`(vSelf INT)
READS SQL DATA
BEGIN
/**
* Returns the taxes for the current client order.
*
* @treturn tmp.orderTax
*/
CALL myOrder_checkMine(vSelf);
DROP TEMPORARY TABLE IF EXISTS tmp.`order`;
CREATE TEMPORARY TABLE tmp.`order`
ENGINE = MEMORY
SELECT vSelf 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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;
IF vCompany IS NULL
THEN
SELECT defaultCompanyFk INTO vCompany
FROM orderConfig;
END IF;
INSERT INTO `order`
SET
customer_id = account.myUser_getId(),
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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;
IF vCompany IS NULL
THEN
SELECT defaultCompanyFk INTO vCompany
FROM orderConfig;
END IF;
INSERT INTO `order`
SET
customer_id = account.myUser_getId(),
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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.ticket_getTax(NULL);
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `myTicket_getServices` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myTicket_getServices`(vSelf INT)
BEGIN
/**
* Returns a current user ticket services.
*
* @param vSelf The ticket identifier
* @select The ticket services
*/
SELECT id, description, quantity, price
FROM myTicketService
WHERE ticketFk = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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, util.VN_CURDATE()), '%Y-%m-01'));
SET vTo = IFNULL(vTo, TIMESTAMPADD(YEAR, 1, util.VN_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(NULL);
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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.myUser_getId(), '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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myTpvTransaction_end`(
vSelf INT,
vStatus VARCHAR(12))
BEGIN
/**
* See tpvTransaction_start() for more info.
*
* @param vSelf Transaction indentifier
* @param vStatus The status, 'ok' o 'ko'
*/
DECLARE vIsOwned BOOL;
SELECT COUNT(*) > 0 INTO vIsOwned
FROM myTpvTransaction WHERE id = vSelf;
IF NOT vIsOwned THEN
CALL util.throw('transactionNotOwnedByUser');
END IF;
CALL tpvTransaction_end(vSelf, vStatus);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `myTpvTransaction_start`(
vAmount INT,
vCompany INT)
BEGIN
/**
* See tpvTransaction_start() for more info.
*
* @param vAmount Amount to pay in cents
* @param vCompany The company identifier
*/
CALL tpvTransaction_start(vAmount, vCompany, account.myUser_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `order_addItem` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 vMinQuantity 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;
CALL order_checkEditable(vSelf);
SELECT shipped INTO vShipment
FROM tmp.zoneGetShipped
WHERE warehouseFk = vWarehouse;
SELECT IFNULL(available, 0) INTO vAvailable
FROM tmp.ticketLot
WHERE warehouseFk = vWarehouse
AND itemFk = vItem;
IF vAmount > vAvailable THEN
CALL util.throw ('ORDER_ROW_UNAVAILABLE');
END IF;
SELECT IFNULL(minQuantity, 0) INTO vMinQuantity
FROM vn.item
WHERE id = vItem;
IF vAmount < LEAST(vMinQuantity, vAvailable) THEN
CALL util.throw ('quantityLessThanMin');
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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, FALSE);
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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, FALSE);
IF account.myUser_getName() = 'visitor' THEN
UPDATE tmp.ticketCalculateItem
SET price = NULL;
UPDATE tmp.ticketComponent
SET cost = 0;
UPDATE tmp.ticketComponentPrice
SET price = 0, priceKg = 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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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;
DECLARE vIsActive BOOL;
DECLARE vClientFk INT;
DECLARE vConfigured DATETIME;
CALL order_checkEditable(vSelf);
-- Obtiene los datos del pedido
SELECT d.code, o.date_send, o.agency_id, o.address_id, customer_id, configured
INTO vDeliveryMethod, vLanded, vAgencyMode, vAddress, vClientFk, vConfigured
FROM `order` o
JOIN vn.deliveryMethod d ON d.id = o.delivery_method_id
WHERE o.id = vSelf;
-- Comprueba que no ha caducado la configuración
IF vConfigured IS NULL OR vConfigured < TIMESTAMPADD(DAY, -1, util.VN_NOW()) THEN
CALL util.throw('orderOutdated');
END IF;
-- Comprueba que se ha seleccionado una dirección
IF vDeliveryMethod IN ('AGENCY', 'DELIVERY') AND vAddress IS NULL THEN
CALL util.throw ('ORDER_EMPTY_ADDRESS');
END IF;
-- Comprueba que el cliente esté activo
SELECT isActive INTO vIsActive
FROM vn.client
WHERE id = vClientFk;
IF NOT vIsActive THEN
CALL util.throw ('CLIENT_NOT_ACTIVE');
END IF;
-- Comprueba que la agencia es correcta
CALL vn.zone_getAgency(vAddress, vLanded);
SELECT COUNT(*) > 0 INTO vIsAvailable
FROM tmp.zoneGetAgency
WHERE agencyModeFk = vAgencyMode;
IF NOT 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `order_checkEditable` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `order_checkEditable`(vSelf INT)
BEGIN
/**
* Cheks if order is editable.
*
* @param vSelf The order id
*/
DECLARE vIsConfirmed BOOL;
SELECT confirmed INTO vIsConfirmed
FROM `order` WHERE id = vSelf;
IF vIsConfirmed THEN
CALL util.throw('orderConfirmed');
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `order_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `order_configure`(
vSelf INT,
vDelivery DATE,
vDeliveryMethod VARCHAR(45),
vAgency INT,
vAddress INT)
BEGIN
/**
* Creates an order with passed parameters. If passed parameters are wrong
* it returns an error.
*
* @param vSelf The order id
* @param vDelivery Delivery date
* @param vDeliveryMethod Delivery method code
* @param vAgency Agency id
* @param vAddress Address id, @NULL for pickup
*/
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;
CALL order_checkEditable(vSelf);
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;
UPDATE `order`
SET date_send = vDelivery,
delivery_method_id = vDeliveryMethodId,
agency_id = vAgency,
address_id = vAddress,
configured = util.VN_NOW()
WHERE
id = vSelf;
CALL order_update(vSelf);
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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
*/
DECLARE vUser INT DEFAULT account.myUser_getId();
CALL order_confirmWithUser(vSelf, 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `order_confirmWithUser`(vSelf INT, vUserId INT)
BEGIN
/**
* Confirms an order, creating each of its tickets on the corresponding
* date, store and user.
*
* @param vSelf The order identifier
* @param vUser The user identifier
*/
DECLARE vOk BOOL;
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vWarehouse INT;
DECLARE vShipment DATE;
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 vPriceFixed DECIMAL(10,2);
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 vCalc INT;
DECLARE vIsLogifloraItem BOOL;
DECLARE vOldQuantity INT;
DECLARE vNewQuantity INT;
DECLARE vIsTaxDataChecked BOOL;
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 = vSelf 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, i.isFloramondo
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 = vSelf
ORDER BY r.rate DESC;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
-- Carga los datos del pedido
SELECT o.date_send, o.address_id, o.note, a.clientFk,
o.company_id, o.agency_id, c.isTaxDataChecked
INTO vDelivery, vAddress, vNotes, vClientId,
vCompanyId, vAgencyModeId, vIsTaxDataChecked
FROM hedera.`order` o
JOIN vn.address a ON a.id = o.address_id
JOIN vn.client c ON c.id = a.clientFk
WHERE o.id = vSelf;
-- Verifica si el cliente tiene los datos comprobados
IF NOT vIsTaxDataChecked THEN
CALL util.throw ('clientNotVerified');
END IF;
-- Carga las fechas de salida de cada almacen
CALL vn.zone_getShipped (vDelivery, vAddress, vAgencyModeId, FALSE);
-- Trabajador que realiza la accion
IF vUserId IS NULL THEN
SELECT employeeFk INTO vUserId FROM orderConfig;
END IF;
START TRANSACTION;
CALL order_checkEditable(vSelf);
-- Check order is not empty
SELECT COUNT(*) > 0 INTO vOk
FROM order_row WHERE order_id = vSelf AND amount > 0;
IF NOT vOk THEN
CALL util.throw ('ORDER_EMPTY');
END IF;
-- Crea los tickets del pedido
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
WITH tPrevia AS
(SELECT DISTINCT s.ticketFk
FROM vn.sale s
JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
JOIN vn.ticket t ON t.id = s.ticketFk
WHERE t.shipped BETWEEN vShipment AND util.dayend(vShipment)
)
SELECT t.id INTO vTicket
FROM vn.ticket t
LEFT JOIN tPrevia tp ON tp.ticketFk = t.id
LEFT JOIN vn.ticketState tls on tls.ticketFk = t.id
JOIN hedera.`order` o
ON o.address_id = t.addressFk
AND vWarehouse = t.warehouseFk
AND o.date_send = t.landed
AND DATE(t.shipped) = vShipment
WHERE o.id = vSelf
AND t.refFk IS NULL
AND tp.ticketFk IS NULL
AND IFNULL(tls.alertLevel,0) = 0
LIMIT 1;
-- Crea el ticket en el caso de no existir uno adecuado
IF vTicket IS NULL
THEN
SET vShipment = IFNULL(vShipment, util.VN_CURDATE());
CALL vn.ticket_add(
vClientId,
vShipment,
vWarehouse,
vCompanyId,
vAddress,
vAgencyModeId,
NULL,
vDelivery,
vUserId,
TRUE,
vTicket
);
ELSE
INSERT INTO vn.ticketTracking
SET ticketFk = vTicket,
userFk = vUserId,
stateFk = TICKET_FREE;
END IF;
INSERT IGNORE INTO vn.orderTicket
SET orderFk = vSelf,
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, vIsLogifloraItem;
IF vDone THEN
LEAVE lRows;
END IF;
SET vSale = NULL;
SELECT s.id, s.quantity INTO vSale, vOldQuantity
FROM vn.sale s
WHERE ticketFk = vTicket
AND price = vPrice
AND itemFk = vItem
AND discount = 0
LIMIT 1;
IF vSale THEN
UPDATE vn.sale
SET quantity = quantity + vAmount,
originalQuantity = quantity
WHERE id = vSale;
SELECT s.quantity INTO vNewQuantity
FROM vn.sale s
WHERE id = vSale;
ELSE
-- Obtiene el coste
SELECT SUM(rc.`price`) valueSum INTO vPriceFixed
FROM orderRowComponent rc
JOIN vn.component c ON c.id = rc.componentFk
JOIN vn.componentType ct ON ct.id = c.typeFk AND ct.isBase
WHERE rc.rowFk = vRowId;
INSERT INTO vn.sale
SET itemFk = vItem,
ticketFk = vTicket,
concept = vConcept,
quantity = vAmount,
price = vPrice,
priceFixed = vPriceFixed,
isPriceFixed = TRUE;
SET vSale = LAST_INSERT_ID();
INSERT INTO vn.saleComponent
(saleFk, componentFk, `value`)
SELECT vSale, rc.componentFk, rc.price
FROM orderRowComponent rc
JOIN vn.component c ON c.id = rc.componentFk
WHERE rc.rowFk = vRowId
GROUP BY vSale, rc.componentFk;
END IF;
UPDATE order_row SET Id_Movimiento = vSale
WHERE id = vRowId;
-- Inserta en putOrder si la compra es de Floramondo
IF vIsLogifloraItem THEN
CALL cache.availableNoRaids_refresh(vCalc,FALSE,vWarehouse,vShipment);
SET @available := 0;
SELECT GREATEST(0,available) INTO @available
FROM cache.availableNoRaids
WHERE calc_id = vCalc
AND item_id = vItem;
UPDATE cache.availableNoRaids
SET available = GREATEST(0,available - vAmount)
WHERE item_id = vItem
AND calc_id = vCalc;
INSERT INTO edi.putOrder (
deliveryInformationID,
supplyResponseId,
quantity ,
EndUserPartyId,
EndUserPartyGLN,
FHAdminNumber,
saleFk
)
SELECT di.ID,
i.supplyResponseFk,
CEIL((vAmount - @available)/ sr.NumberOfItemsPerCask),
o.address_id ,
vClientId,
IFNULL(ca.fhAdminNumber, fhc.defaultAdminNumber),
vSale
FROM edi.deliveryInformation di
JOIN vn.item i ON i.supplyResponseFk = di.supplyResponseID
JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk
LEFT JOIN edi.clientFHAdminNumber ca ON ca.clientFk = vClientId
JOIN edi.floraHollandConfig fhc
JOIN hedera.`order` o ON o.id = vSelf
WHERE i.id = vItem
AND di.LatestOrderDateTime > util.VN_NOW()
AND vAmount > @available
LIMIT 1;
END IF;
END LOOP;
CLOSE cRows;
END LOOP;
CLOSE cDates;
UPDATE `order` SET confirmed = TRUE, confirm_date = util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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`;
DROP TEMPORARY TABLE 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `order_update` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 = util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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.myUser_getId();
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `tpvTransaction_confirm` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 already confirmed');
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `tpvTransaction_confirmFromExport` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `tpvTransaction_confirmFromExport`()
BEGIN
/**
* Confirms multiple transactions comming from Redsys "canales" exported CSV.
*
* @table tmp.transactions(id, isAuthorization, amount) The list of exported transactions
*/
DECLARE vDone BOOL;
DECLARE vTransactionId INT;
DECLARE vAmount INT;
DECLARE vConfirmedAmount INT;
DECLARE cur CURSOR FOR
SELECT * FROM tPendingTransactions;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
CREATE OR REPLACE TEMPORARY TABLE tPendingTransactions
ENGINE = MEMORY
SELECT t.id, t.amount, tt.amount confirmedAmount
FROM tmp.transactions t
JOIN hedera.tpvTransaction tt ON tt.id = t.id
WHERE t.isAuthorization
AND tt.response IS NULL;
OPEN cur;
l: LOOP
SET vDone = FALSE;
FETCH cur INTO vTransactionId, vAmount, vConfirmedAmount;
IF vDone THEN
LEAVE l;
END IF;
IF NOT (vAmount <=> vConfirmedAmount) THEN
CALL util.throw(CONCAT(
'Transaction ', vTransactionId ,', source amount "', vAmount ,
'" does not match confirmed amount "', vConfirmedAmount ,'"'
));
END IF;
CALL tpvTransaction_confirmById(vTransactionId);
END LOOP;
CLOSE cur;
SELECT id, amount FROM tPendingTransactions;
DROP TEMPORARY TABLE tPendingTransactions;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `tpvTransaction_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `tpvTransaction_end`(
vSelf INT,
vStatus VARCHAR(12))
BEGIN
/**
* Ends a transaction by setting its status to 'ok' or 'ko' depending on
* if this has been done correctly.
* This procedure must be called directly by the client when the transaction
* ends, it is only valid until the arrival of the definitive notification from
* the payment platform.
*
* @param vSelf Transaction indentifier
* @param vStatus The status, 'ok' o 'ko'
*/
IF vStatus IN ('ok', 'ko') THEN
UPDATE tpvTransaction 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `tpvTransaction_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `tpvTransaction_start`(
vAmount INT,
vCompany INT,
vUser INT)
BEGIN
/**
* Start a new transaction with the virtual TPV, generating an identifier
* of transaction and returning the parameters that should be sent to the
* payment platform.
*
* @param vAmount Amount to pay in cents
* @param vCompany The company identifier
* @select Parameters that will be sent to payment platform
*/
DECLARE vSelf CHAR(12);
DECLARE vMerchant INT;
DECLARE vUrl VARCHAR(255);
DECLARE vKey VARCHAR(50);
DECLARE vEnvironment VARCHAR(255);
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 environment INTO vEnvironment
FROM util.config;
IF vEnvironment = 'production' 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 tpvTransaction
SET merchantFk = vMerchant,
clientFk = vUser,
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `tpvTransaction_undo` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `tpvTransaction_undo`(vSelf INT)
p: 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.accounting 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `visitUser_new`(
vAccess INT
,vSsid VARCHAR(64)
)
BEGIN
DECLARE vUserVisit INT;
INSERT INTO visitUser SET
accessFk = vAccess,
userFk = account.myUser_getId();
SET vUserVisit = LAST_INSERT_ID();
UPDATE userSession SET userVisitFk = vUserVisit
WHERE ssid = vSsid;
DELETE FROM userSession
WHERE lastUpdate < TIMESTAMPADD(HOUR, -1, util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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: `pbx`
--
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `pbx` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_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) NOT NULL,
PRIMARY KEY (`phone`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Hangup input calls from this list';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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) NOT NULL DEFAULT '',
`src` varchar(80) NOT NULL DEFAULT '',
`dst` varchar(80) NOT NULL DEFAULT '',
`dcontext` varchar(80) NOT NULL DEFAULT '',
`channel` varchar(80) NOT NULL DEFAULT '',
`dst_channel` varchar(80) NOT NULL DEFAULT '',
`last_app` varchar(80) NOT NULL DEFAULT '',
`last_data` varchar(80) NOT NULL DEFAULT '',
`duration` int(11) NOT NULL DEFAULT 0,
`billsec` int(11) NOT NULL DEFAULT 0,
`disposition` varchar(45) NOT NULL DEFAULT '',
`ama_flags` int(11) NOT NULL DEFAULT 0,
`account_code` varchar(20) NOT NULL DEFAULT '',
`unique_id` varchar(32) NOT NULL DEFAULT '',
`user_field` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
KEY `calldate` (`call_date`),
KEY `dst` (`dst`),
KEY `accountcode` (`account_code`),
KEY `dstchannel` (`dst_channel`),
KEY `disposition` (`disposition`),
KEY `src` (`src`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`defaultPrefix` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `config_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`phone` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci 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=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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,
`music` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`context` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`takeCall` char(1) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`declineCall` char(1) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`timeout` int(11) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `followmeConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `holiday`
--
DROP TABLE IF EXISTS `holiday`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `holiday` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`country` char(2) NOT NULL,
`day` date NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `holiday_country_IDX` (`country`,`day`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `prefix`
--
DROP TABLE IF EXISTS `prefix`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `prefix` (
`country` char(2) NOT NULL COMMENT 'Country code',
`prefix` varchar(100) NOT NULL COMMENT 'Country prefix',
PRIMARY KEY (`country`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `queue`
--
DROP TABLE IF EXISTS `queue`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `queue` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`description` varchar(128) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`name` varchar(128) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`config` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
UNIQUE KEY `description` (`description`),
KEY `config` (`config`),
CONSTRAINT `queue_ibfk_1` FOREIGN KEY (`config`) REFERENCES `queueConfig` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queues';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`timeout` int(10) unsigned NOT NULL,
`retry` int(10) unsigned NOT NULL,
`weight` int(10) unsigned NOT NULL,
`maxLen` int(10) unsigned NOT NULL,
`ringInUse` tinyint(4) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`extension` varchar(128) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `queue` (`queue`,`extension`),
KEY `extension` (`extension`),
CONSTRAINT `queueMember_ibfk_1` FOREIGN KEY (`queue`) REFERENCES `queue` (`name`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `queueMember_ibfk_2` FOREIGN KEY (`extension`) REFERENCES `sip` (`extension`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`phone` varchar(128) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `queue` (`queue`,`phone`),
CONSTRAINT `queuePhone_ibfk_1` FOREIGN KEY (`queue`) REFERENCES `queue` (`name`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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,
`weekDays` set('mon','tue','wed','thu','fri','sat','sun') NOT NULL COMMENT '0 = Monday, 6 = Sunday',
`startTime` time NOT NULL,
`endTime` time NOT NULL,
`country` char(2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT 'The softphone extension',
`md5Secret` varchar(80) DEFAULT NULL COMMENT 'MD5 hash of extension and password',
`secret` varchar(80) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT 'Deprecated',
`caller_id` varchar(80) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci 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=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='SIP accounts';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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 `regexten`,
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 `directmedia`,
1 AS `insecure`,
1 AS `transport`,
1 AS `nat`,
1 AS `disallow`,
1 AS `allow`,
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,
`host` varchar(40) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`deny` varchar(95) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`permit` varchar(95) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`type` enum('user','peer','friend') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`context` varchar(80) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`incomingLimit` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`pickupGroup` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`directMedia` enum('yes','no') DEFAULT NULL,
`insecure` varchar(45) NOT NULL,
`transport` varchar(255) DEFAULT NULL,
`encryption` varchar(255) DEFAULT NULL,
`dtlsenable` varchar(255) DEFAULT NULL,
`dtlverify` varchar(255) DEFAULT NULL,
`dtlscertfile` varchar(255) DEFAULT NULL,
`dtlsprivatekey` varchar(255) DEFAULT NULL,
`dtlssetup` varchar(255) DEFAULT NULL,
`nat` varchar(255) DEFAULT NULL,
`disallow` varchar(100) DEFAULT 'all',
`allow` varchar(100) DEFAULT 'g729;ilbc;gsm;ulaw;alaw',
`qualify` enum('yes','no') DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `sipConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`regSeconds` bigint(20) unsigned DEFAULT NULL,
`port` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`defaultUser` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`userAgent` varchar(80) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`lastMs` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`fullContact` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`regServer` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci 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=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='SIP registrations';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping events for database 'pbx'
--
--
-- Dumping routines for database 'pbx'
--
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `phone_format`(vPhone VARCHAR(255)) RETURNS varchar(255) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `queue_isValid`(vQueue VARCHAR(255))
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sip_getExtension` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sip_getExtension`(vUserId INT(10))
BEGIN
/*
* Devuelve la extensión pbx del usuario
*
* @param vUserId Id del usuario
*
*/
SELECT extension
FROM sip s
WHERE s.user_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sip_isValid`(vExtension VARCHAR(255))
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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: `psico`
--
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `psico` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */;
USE `psico`;
--
-- Table structure for table `answer`
--
DROP TABLE IF EXISTS `answer`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `answer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`text` varchar(155) NOT NULL,
`questionFk` int(11) NOT NULL,
`correct` tinyint(1) NOT NULL DEFAULT 0,
`order` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `answer_fk1_idx` (`questionFk`),
CONSTRAINT `answer_fk1` FOREIGN KEY (`questionFk`) REFERENCES `question` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `exam`
--
DROP TABLE IF EXISTS `exam`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `exam` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`duration` int(11) NOT NULL COMMENT 'minutos de duracion de la prueba',
`fellowFk` int(11) NOT NULL,
`examTypeFk` int(11) NOT NULL,
`started` datetime DEFAULT NULL,
`finished` datetime DEFAULT NULL,
`questionsCount` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `exam_fk1_idx` (`fellowFk`),
KEY `exam_fk2_idx` (`examTypeFk`),
CONSTRAINT `exam_fk1` FOREIGN KEY (`fellowFk`) REFERENCES `fellow` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `exam_fk2` FOREIGN KEY (`examTypeFk`) REFERENCES `examType` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `examQuestion`
--
DROP TABLE IF EXISTS `examQuestion`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `examQuestion` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`examFk` int(11) NOT NULL,
`questionFk` int(11) NOT NULL,
`answerFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `examQuestion_fk1_idx` (`examFk`),
KEY `examQuestion_fk2_idx` (`questionFk`),
KEY `examQuestion_fk3_idx` (`answerFk`),
CONSTRAINT `examQuestion_fk1` FOREIGN KEY (`examFk`) REFERENCES `exam` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `examQuestion_fk2` FOREIGN KEY (`questionFk`) REFERENCES `question` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `examQuestion_fk3` FOREIGN KEY (`answerFk`) REFERENCES `answer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `examType`
--
DROP TABLE IF EXISTS `examType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `examType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `examView`
--
DROP TABLE IF EXISTS `examView`;
/*!50001 DROP VIEW IF EXISTS `examView`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `examView` AS SELECT
1 AS `text`,
1 AS `examFk`,
1 AS `questionFk`,
1 AS `answerFk`,
1 AS `id` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `fellow`
--
DROP TABLE IF EXISTS `fellow`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `fellow` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `question`
--
DROP TABLE IF EXISTS `question`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `question` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`text` varchar(155) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`randomOrder` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `questionType`
--
DROP TABLE IF EXISTS `questionType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `questionType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`examTypeFk` int(11) NOT NULL,
`questionFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `questionTypeFk1_idx` (`examTypeFk`),
KEY `questionTypeFk2_idx` (`questionFk`),
CONSTRAINT `questionTypeFk1` FOREIGN KEY (`examTypeFk`) REFERENCES `examType` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `questionTypeFk2` FOREIGN KEY (`questionFk`) REFERENCES `question` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `results`
--
DROP TABLE IF EXISTS `results`;
/*!50001 DROP VIEW IF EXISTS `results`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `results` AS SELECT
1 AS `examFk`,
1 AS `aciertos`,
1 AS `questionsCount`,
1 AS `minutos`,
1 AS `nota` */;
SET character_set_client = @saved_cs_client;
--
-- Dumping events for database 'psico'
--
--
-- Dumping routines for database 'psico'
--
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `answerSort` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `answerSort`()
BEGIN
UPDATE answer
SET `order` = RAND() * 999999;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `examNew` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `examNew`(vFellow VARCHAR(50), vType INT, vQuestionsNumber INT, OUT vExamFk INT)
BEGIN
DECLARE done BOOL DEFAULT FALSE;
DECLARE vFellowFk INT;
DECLARE vQuestionFk INT;
DECLARE rs CURSOR FOR
SELECT q.id
FROM psico.question q
LEFT JOIN psico.questionType qt ON q.id = qt.questionFk
WHERE qt.examTypeFk = vType
ORDER BY randomOrder;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
IF vQuestionsNumber = 0 THEN
SET vQuestionsNumber = 30;
END IF;
CALL psico.answerSort();
CALL psico.questionSort();
INSERT INTO psico.fellow(name) VALUES(vFellow);
SELECT MAX(id) INTO vFellowFk FROM psico.fellow;
INSERT INTO psico.exam(fellowFk, started, questionsCount,examTypeFk) VALUES(vFellowFk, util.VN_NOW(), vQuestionsNumber,vType);
SELECT MAX(id) INTO vExamFk FROM psico.exam;
OPEN rs;
FETCH rs INTO vQuestionFk;
WHILE NOT done AND vQuestionsNumber DO
INSERT INTO psico.examQuestion(examFk, questionFk)
VALUES (vExamFk, vQuestionFk);
FETCH rs INTO vQuestionFk;
SET vQuestionsNumber = vQuestionsNumber - 1;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `getExamQuestions` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `getExamQuestions`(vExamFk INT)
BEGIN
SELECT p.text,p.examFk,p.questionFk,p.answerFk,p.id ,a.text AS answerText,a.correct, a.id AS answerFk
FROM psico.examView as p
INNER JOIN psico.answer as a ON p.questionFk = a.questionFk
WHERE examFk = vExamFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `getExamType` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `getExamType`()
BEGIN
SELECT id,name
FROM psico.examType;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `questionSort` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `questionSort`()
BEGIN
UPDATE question
SET randomOrder = RAND() * 999999;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_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: `sage`
--
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `sage` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */;
USE `sage`;
--
-- Table structure for table `ClavesOperacion`
--
DROP TABLE IF EXISTS `ClavesOperacion`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ClavesOperacion` (
`ClaveOperacionFactura_` varchar(1) NOT NULL,
`Descripcion` varchar(250) NOT NULL,
PRIMARY KEY (`ClaveOperacionFactura_`),
UNIQUE KEY `ClaveOperacionFactura__UNIQUE` (`ClaveOperacionFactura_`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `Municipios`
--
DROP TABLE IF EXISTS `Municipios`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Municipios` (
`Codigo` varchar(7) NOT NULL,
`Municipio` varchar(25) NOT NULL,
`Tipo` tinyint(4) NOT NULL,
`Recargo` decimal(28,10) NOT NULL,
`Deleg.` varchar(5) NOT NULL,
`Provincia` tinyint(4) NOT NULL,
`Autonomia` smallint(6) NOT NULL,
`Nacion` tinyint(4) NOT NULL,
PRIMARY KEY (`Codigo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `Naciones`
--
DROP TABLE IF EXISTS `Naciones`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Naciones` (
`countryFk` mediumint(8) NOT NULL,
`CodigoNacion` smallint(6) NOT NULL DEFAULT 108,
`CodigoNacion347` smallint(6) NOT NULL DEFAULT 108,
`Nacion` varchar(25) NOT NULL DEFAULT '',
`SiglaNacion` varchar(2) NOT NULL DEFAULT 'ES',
`TipoCodigo` varchar(1) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'A',
`Longitud1` tinyint(4) NOT NULL DEFAULT 0,
`Longitud2` tinyint(4) NOT NULL DEFAULT 0,
`Longitud3` tinyint(4) NOT NULL DEFAULT 0,
`Longitud4` tinyint(4) NOT NULL DEFAULT 0,
`NacionCEE` smallint(6) NOT NULL DEFAULT 0,
`FechaCEE` datetime DEFAULT NULL,
`NacionISO` varchar(3) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '',
PRIMARY KEY (`countryFk`,`CodigoNacion`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `Provincias`
--
DROP TABLE IF EXISTS `Provincias`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Provincias` (
`provinceFk` smallint(6) NOT NULL,
`CodigoProvincia` varchar(5) NOT NULL DEFAULT '',
`CodigoMatricula` varchar(2) NOT NULL DEFAULT '',
`Provincia` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL DEFAULT '',
`RecargoProvincial` decimal(28,10) NOT NULL DEFAULT 0.0000000000,
PRIMARY KEY (`CodigoProvincia`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `TiposIva`
--
DROP TABLE IF EXISTS `TiposIva`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `TiposIva` (
`CodigoIva` smallint(6) NOT NULL DEFAULT 0,
`CodigoTerritorio` smallint(6) NOT NULL DEFAULT 0,
`Iva` varchar(30) NOT NULL DEFAULT '',
`BaseCorrectora` decimal(28,10) NOT NULL DEFAULT 0.0000000000,
`PorcentajeIva` decimal(28,10) NOT NULL DEFAULT 0.0000000000,
`RecargoEquivalencia` decimal(28,10) NOT NULL DEFAULT 0.0000000000,
`CuentaIvaSoportado` varchar(15) NOT NULL DEFAULT '',
`CuentaIvaRepercutido` varchar(15) NOT NULL DEFAULT '',
`CuentaRecargo` varchar(15) NOT NULL DEFAULT '',
`CuentaIvaNoDeducible` varchar(15) NOT NULL DEFAULT '',
`CuentaIvaSoportadoANT_` varchar(15) NOT NULL DEFAULT '',
`CuentaIvaRepercutidoANT_` varchar(15) NOT NULL DEFAULT '',
`CuentaRecargoANT_` varchar(15) NOT NULL DEFAULT '',
`CuentaIvaNoDeducibleANT_` varchar(15) NOT NULL DEFAULT '',
`IdTiposIva` varchar(50) NOT NULL DEFAULT '',
`CuentaIvaRepCaja` varchar(15) NOT NULL DEFAULT '',
`CuentaIVARepCajaPu` varchar(15) NOT NULL DEFAULT '',
`CuentaIVARepCajaVen` varchar(15) NOT NULL DEFAULT '',
`CuentaIvaSopCaja` varchar(15) NOT NULL DEFAULT '',
`CuentaIVASopCajaPu` varchar(15) NOT NULL DEFAULT '',
`CuentaIVASopCajaVen` varchar(15) NOT NULL DEFAULT '',
`CuentaIVARecCaja` varchar(15) NOT NULL DEFAULT '',
`CuentaIVARecCajaPu` varchar(15) NOT NULL DEFAULT '',
`CuentaIVARecCajaVen` varchar(15) NOT NULL DEFAULT '',
`IGICImplicito` smallint(6) NOT NULL DEFAULT 0,
PRIMARY KEY (`CodigoIva`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `TiposRetencion`
--
DROP TABLE IF EXISTS `TiposRetencion`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `TiposRetencion` (
`CodigoRetencion` smallint(6) NOT NULL DEFAULT 0,
`Retencion` varchar(50) NOT NULL DEFAULT '',
`PorcentajeRetencion` decimal(28,10) NOT NULL DEFAULT 0.0000000000,
`CuentaCargo` varchar(15) DEFAULT NULL,
`CuentaAbono` varchar(15) DEFAULT NULL,
`ClaveIrpf` varchar(2) DEFAULT NULL,
`CuentaCargoANT_` varchar(15) DEFAULT NULL,
`CuentaAbonoANT_` varchar(15) DEFAULT NULL,
`IdTipoRetencion` varchar(45) DEFAULT NULL,
PRIMARY KEY (`CodigoRetencion`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `TiposTransacciones`
--
DROP TABLE IF EXISTS `TiposTransacciones`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `TiposTransacciones` (
`CodigoTransaccion` tinyint(4) NOT NULL DEFAULT 0,
`Transaccion` varchar(50) NOT NULL DEFAULT '',
`TipoFactura` varchar(1) NOT NULL DEFAULT '',
`Autofactura` smallint(6) NOT NULL DEFAULT 0,
`ClaveOperacionDefecto` varchar(1) NOT NULL DEFAULT '',
PRIMARY KEY (`CodigoTransaccion`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `accountingEntryError`
--
DROP TABLE IF EXISTS `accountingEntryError`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `accountingEntryError` (
`accountingEntryFk` int(10) unsigned NOT NULL,
PRIMARY KEY (`accountingEntryFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Listado de asientos presentes en Sage para notificar su error';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `clientLastTwoMonths`
--
DROP TABLE IF EXISTS `clientLastTwoMonths`;
/*!50001 DROP VIEW IF EXISTS `clientLastTwoMonths`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `clientLastTwoMonths` AS SELECT
1 AS `clientFk`,
1 AS `companyFk` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `clientesProveedores`
--
DROP TABLE IF EXISTS `clientesProveedores`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientesProveedores` (
`CodigoEmpresa` smallint(6) NOT NULL,
`ClienteOProveedor` varchar(1) NOT NULL,
`CodigoClienteProveedor` int(11) NOT NULL,
`RazonSocial` varchar(40) NOT NULL,
`RazonSocial2` varchar(40) NOT NULL DEFAULT '',
`Nombre` varchar(35) NOT NULL,
`Domicilio` varchar(40) NOT NULL,
`Cargo1` varchar(15) NOT NULL DEFAULT '',
`Nombre1` varchar(30) NOT NULL DEFAULT '',
`Cargo2` varchar(15) NOT NULL DEFAULT '',
`Nombre2` varchar(30) NOT NULL DEFAULT '',
`CodigoCuenta` varchar(15) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`CifDni` varchar(13) NOT NULL,
`CifEuropeo` varchar(15) NOT NULL,
`CodigoSigla` varchar(2) NOT NULL DEFAULT '',
`ViaPublica` varchar(40) NOT NULL DEFAULT '',
`Numero1` varchar(4) NOT NULL DEFAULT '',
`Numero2` varchar(4) NOT NULL DEFAULT '',
`Escalera` varchar(2) NOT NULL DEFAULT '',
`Piso` varchar(2) NOT NULL DEFAULT '',
`Puerta` varchar(2) NOT NULL DEFAULT '',
`Letra` varchar(2) NOT NULL DEFAULT '',
`CodigoPostal` varchar(8) NOT NULL,
`CodigoMunicipio` varchar(7) NOT NULL DEFAULT '',
`Municipio` varchar(25) NOT NULL,
`ColaMunicipio` varchar(15) NOT NULL DEFAULT '',
`CodigoProvincia` varchar(5) NOT NULL,
`Provincia` varchar(20) NOT NULL,
`CodigoNacion` smallint(6) NOT NULL DEFAULT 0,
`Nacion` varchar(25) NOT NULL DEFAULT '',
`Telefono` varchar(15) NOT NULL,
`Telefono2` varchar(15) NOT NULL,
`Telefono3` varchar(15) NOT NULL DEFAULT '',
`Fax` varchar(15) NOT NULL DEFAULT '',
`CodigoTransaccion` tinyint(4) NOT NULL DEFAULT 0,
`CodigoRetencion` smallint(6) NOT NULL,
`Deducible` smallint(6) NOT NULL DEFAULT 0,
`CodigoIva` smallint(6) NOT NULL DEFAULT 0,
`Mediacion` smallint(6) NOT NULL DEFAULT 0,
`Exclusion347` smallint(6) NOT NULL DEFAULT 0,
`NumeroPlazos` tinyint(4) NOT NULL DEFAULT 1,
`DiasPrimerPlazo` smallint(6) NOT NULL DEFAULT 0,
`DiasEntrePlazos` smallint(6) NOT NULL DEFAULT 0,
`DiasFijos1` tinyint(4) NOT NULL DEFAULT 0,
`DiasFijos2` tinyint(4) NOT NULL DEFAULT 0,
`DiasFijos3` tinyint(4) NOT NULL DEFAULT 0,
`InicioNoPago` smallint(6) NOT NULL DEFAULT 0,
`FinNoPago` smallint(6) NOT NULL DEFAULT 0,
`ControlarFestivos` smallint(6) NOT NULL DEFAULT 0,
`DiasRetroceso` tinyint(4) NOT NULL DEFAULT 0,
`MesesComerciales` smallint(6) NOT NULL DEFAULT 0,
`RemesaHabitual` varchar(15) NOT NULL DEFAULT '',
`CodigoTipoEfecto` smallint(6) NOT NULL DEFAULT 0,
`Email1` varchar(250) NOT NULL,
`Email2` varchar(250) NOT NULL DEFAULT '',
`CodigoCategoriaCliente_` varchar(10) NOT NULL DEFAULT 'CLI',
`IdDelegacion` varchar(10) NOT NULL DEFAULT '',
`CodigoMotivoBajaClienteLc` varchar(3) NOT NULL DEFAULT '',
`CodigoDepartamento` varchar(10) NOT NULL DEFAULT '',
`CodigoCanal` varchar(10) NOT NULL DEFAULT '',
`CodigoBanco` varchar(6) NOT NULL DEFAULT '',
`CodigoAgencia` varchar(6) NOT NULL DEFAULT '',
`DC` varchar(2) NOT NULL DEFAULT '',
`CCC` varchar(15) NOT NULL DEFAULT '',
`IBAN` varchar(34) NOT NULL DEFAULT '',
`CodigoCondiciones` smallint(6) NOT NULL DEFAULT 0,
`StatusTraspasadoIME` tinyint(4) NOT NULL DEFAULT 0,
`TipoImportacionIME` tinyint(4) NOT NULL DEFAULT 2,
`TipoPlanCuentaIME` smallint(6) NOT NULL DEFAULT 2,
`Contrapartida` varchar(15) NOT NULL DEFAULT '',
`CodigoCuentaImpagado` varchar(15) NOT NULL DEFAULT '',
`CodigoCuentaEfecto` varchar(15) NOT NULL DEFAULT '',
`Comentarios` text NOT NULL DEFAULT '',
`CodigoTerritorio` smallint(6) NOT NULL DEFAULT 0,
`CodigoIdioma_` varchar(3) NOT NULL DEFAULT '',
`TarifaPrecio` smallint(6) NOT NULL DEFAULT 0,
`%Descuento` decimal(28,10) NOT NULL DEFAULT 0.0000000000,
`%Rappel` decimal(28,10) NOT NULL DEFAULT 0.0000000000,
`%ProntoPago` decimal(28,10) NOT NULL DEFAULT 0.0000000000,
`%Financiacion` decimal(28,10) NOT NULL DEFAULT 0.0000000000,
`CodigoComisionista` int(11) NOT NULL DEFAULT 0,
`TarifaDescuento` smallint(6) NOT NULL DEFAULT 0,
`SiglaNacion` varchar(2) NOT NULL DEFAULT '',
`MarcaMenorSinNif` smallint(6) NOT NULL DEFAULT 0,
`PersonaFisicaJuridica` varchar(1) NOT NULL,
`SiglaNacionRepresentante` varchar(2) NOT NULL DEFAULT '',
`CifDniRepresentante` varchar(13) NOT NULL DEFAULT '',
`NombreRepresentante` varchar(50) NOT NULL DEFAULT '',
`TipoDocumentoPersona` smallint(6) NOT NULL,
`TipoCif` varchar(1) NOT NULL DEFAULT '',
`MotivoBajaClienteLc` varchar(30) NOT NULL DEFAULT '',
`PuntosSR` decimal(28,10) NOT NULL DEFAULT 0.0000000000,
`TarjetaSR` varchar(100) NOT NULL DEFAULT '',
`FechaNacimiento` datetime DEFAULT NULL,
`Domicilio2` varchar(40) NOT NULL DEFAULT '',
`CuentaProvision` varchar(15) NOT NULL DEFAULT '',
`CodigoTransportista` int(11) NOT NULL DEFAULT 0,
`FormadePago` varchar(35) NOT NULL DEFAULT '',
`ObservacionesCliente` varchar(50) NOT NULL DEFAULT '',
`CodigoTipoClienteLc` varchar(3) NOT NULL DEFAULT '',
`TipoCliente` varchar(10) NOT NULL DEFAULT '',
`CodigoActividadLc` varchar(2) NOT NULL DEFAULT '',
`Actividad` varchar(50) NOT NULL DEFAULT '',
`IndicadorIva` varchar(1) NOT NULL DEFAULT '',
`CodigoRuta_` varchar(10) NOT NULL DEFAULT '',
`NombreEmpleado` varchar(10) NOT NULL DEFAULT '',
`PrimerApellidoEmpleado` varchar(15) NOT NULL DEFAULT '',
`SegundoApellidoEmpleado` varchar(15) NOT NULL DEFAULT '',
`sysTick` int(11) NOT NULL DEFAULT 0,
`RiesgoMaximo` decimal(28,10) NOT NULL DEFAULT 0.0000000000,
`PlazoMedioPCMA` smallint(6) NOT NULL DEFAULT 0,
`CriterioIvaIME` smallint(6) NOT NULL DEFAULT 0,
`ReferenciaMandato` varchar(35) NOT NULL DEFAULT '',
`%Comision` decimal(28,10) NOT NULL DEFAULT 0.0000000000,
`CodigoZona` int(11) NOT NULL DEFAULT 0,
`BloqueoAlbaran` smallint(6) NOT NULL DEFAULT 0,
`CodigoSeccion` varchar(10) NOT NULL DEFAULT '',
`CodigoSector_` varchar(10) NOT NULL DEFAULT '',
`CodigoProyecto` varchar(10) NOT NULL DEFAULT '',
PRIMARY KEY (`CodigoEmpresa`,`ClienteOProveedor`,`CodigoClienteProveedor`),
KEY `CodigoCuenta` (`CodigoCuenta`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`pendingTaxAccount` varchar(100) DEFAULT NULL COMMENT 'Cuenta contable IVA pendiente',
`nontaxableTransactionTypeFk` tinyint(4) DEFAULT NULL COMMENT 'Transacción Operaciones exentas',
`pendingServiceTransactionTypeFk` tinyint(4) DEFAULT NULL COMMENT 'Transacción Import. bienes y serv. corrientes pdte. liquidar',
`definitiveExportTransactionTypeFk` tinyint(4) DEFAULT NULL COMMENT 'Transacción Exportaciones definitivas',
`shipmentTransactionTypeFk` tinyint(4) DEFAULT NULL COMMENT 'Transacción Envíos definitivos a Canarias, Ceuta y Melilla',
PRIMARY KEY (`id`),
CONSTRAINT `config_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `invoiceType`
--
DROP TABLE IF EXISTS `invoiceType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceType` (
`code` varchar(11) NOT NULL,
`codeSage` varchar(1) NOT NULL,
PRIMARY KEY (`code`),
UNIQUE KEY `code_UNIQUE` (`code`),
UNIQUE KEY `codeSage_UNIQUE` (`codeSage`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `movConta`
--
DROP TABLE IF EXISTS `movConta`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `movConta` (
`OrdenMovimientos` int(11) NOT NULL AUTO_INCREMENT,
`MovPosicion` varchar(64) NOT NULL,
`Ejercicio` smallint(6) NOT NULL,
`CodigoEmpresa` smallint(6) NOT NULL,
`Asiento` int(11) NOT NULL,
`CargoAbono` varchar(1) NOT NULL,
`CodigoCuenta` varchar(15) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`Contrapartida` varchar(15) NOT NULL,
`FechaAsiento` datetime NOT NULL,
`TipoDocumento` varchar(6) NOT NULL,
`DocumentoConta` varchar(9) NOT NULL,
`Comentario` varchar(40) NOT NULL,
`ImporteAsiento` decimal(28,10) NOT NULL,
`CodigoDiario` smallint(6) NOT NULL,
`CodigoCanal` varchar(10) NOT NULL,
`CodigoActividad` varchar(1) NOT NULL,
`FechaVencimiento` datetime DEFAULT NULL,
`NumeroPeriodo` smallint(6) NOT NULL,
`CodigoUsuario` smallint(6) NOT NULL,
`FechaGrabacion` datetime NOT NULL,
`TipoEntrada` varchar(2) NOT NULL,
`CodigoDepartamento` varchar(10) NOT NULL,
`CodigoSeccion` varchar(10) NOT NULL,
`CodigoDivisa` varchar(3) NOT NULL,
`ImporteCambio` decimal(28,10) NOT NULL,
`ImporteDivisa` decimal(28,10) NOT NULL,
`FactorCambio` decimal(28,10) NOT NULL,
`CodigoProyecto` varchar(10) NOT NULL,
`LibreN1` int(11) NOT NULL,
`LibreN2` int(11) NOT NULL,
`LibreA1` varchar(15) NOT NULL,
`LibreA2` varchar(15) NOT NULL,
`IdDelegacion` varchar(10) NOT NULL,
`MovCartera` varchar(64) DEFAULT NULL,
`IdProcesoIME` varchar(64) NOT NULL,
`TipoCarteraIME` smallint(6) NOT NULL,
`TipoAnaliticaIME` smallint(6) NOT NULL,
`StatusTraspasadoIME` tinyint(4) NOT NULL,
`TipoImportacionIME` tinyint(4) NOT NULL,
`BaseIva1` decimal(28,10) NOT NULL,
`PorBaseCorrectora1` decimal(28,10) NOT NULL,
`PorIva1` decimal(28,10) NOT NULL,
`CuotaIva1` decimal(28,10) NOT NULL,
`PorRecargoEquivalencia1` decimal(28,10) NOT NULL,
`RecargoEquivalencia1` decimal(28,10) NOT NULL,
`CodigoTransaccion1` tinyint(4) NOT NULL,
`BaseIva2` decimal(28,10) NOT NULL,
`PorBaseCorrectora2` decimal(28,10) NOT NULL,
`PorIva2` decimal(28,10) NOT NULL,
`CuotaIva2` decimal(28,10) NOT NULL,
`PorRecargoEquivalencia2` decimal(28,10) NOT NULL,
`RecargoEquivalencia2` decimal(28,10) NOT NULL,
`CodigoTransaccion2` tinyint(4) NOT NULL,
`BaseIva3` decimal(28,10) NOT NULL,
`PorBaseCorrectora3` decimal(28,10) NOT NULL,
`PorIva3` decimal(28,10) NOT NULL,
`CuotaIva3` decimal(28,10) NOT NULL,
`PorRecargoEquivalencia3` decimal(28,10) NOT NULL,
`RecargoEquivalencia3` decimal(28,10) NOT NULL,
`CodigoTransaccion3` tinyint(4) NOT NULL,
`baseIva4` decimal(28,10) NOT NULL,
`PorBaseCorrectora4` decimal(28,10) NOT NULL,
`PorIva4` decimal(28,10) NOT NULL,
`CuotaIva4` decimal(28,10) NOT NULL,
`PorRecargoEquivalencia4` decimal(28,10) NOT NULL,
`RecargoEquivalencia4` decimal(28,10) NOT NULL,
`CodigoTransaccion4` tinyint(4) NOT NULL,
`Año` smallint(6) NOT NULL,
`Serie` varchar(10) NOT NULL,
`Factura` int(11) NOT NULL,
`SuFacturaNo` varchar(40) NOT NULL,
`FechaFactura` datetime NOT NULL,
`ImporteFactura` decimal(28,10) NOT NULL,
`TipoFactura` varchar(1) NOT NULL,
`CodigoCuentaFactura` varchar(15) NOT NULL,
`CifDni` varchar(13) NOT NULL,
`Nombre` varchar(35) NOT NULL,
`CodigoRetencion` smallint(6) NOT NULL,
`BaseRetencion` decimal(28,10) NOT NULL,
`PorRetencion` decimal(28,10) NOT NULL,
`ImporteRetencion` decimal(28,10) NOT NULL,
`AbonoIva` smallint(6) NOT NULL,
`CodigoActividadF` varchar(1) NOT NULL,
`Intracomunitaria` smallint(6) NOT NULL,
`CodigoTerritorio` smallint(6) NOT NULL,
`SiglaNacion` varchar(2) NOT NULL,
`RetencionInformativa` smallint(6) NOT NULL,
`EjercicioFacturaOriginal` smallint(6) NOT NULL,
`SerieFacturaOriginal` varchar(10) NOT NULL,
`NumeroFacturaOriginal` int(11) NOT NULL,
`EjercicioFactura` smallint(6) NOT NULL,
`CobroPagoRetencion` varchar(1) NOT NULL,
`FechaOperacion` datetime NOT NULL,
`Exclusion347` smallint(6) NOT NULL,
`MovIdentificadorIME` varchar(64) NOT NULL,
`Previsiones` varchar(1) NOT NULL,
`MantenerAsiento` tinyint(4) NOT NULL,
`OrdenMovIME` smallint(6) NOT NULL,
`Metalico347` smallint(6) NOT NULL,
`ClaveOperacionFactura_` varchar(1) NOT NULL,
`SerieAgrupacion_` varchar(10) NOT NULL,
`NumeroFacturaInicial_` int(11) NOT NULL,
`NumeroFacturaFinal_` int(11) NOT NULL,
`IdAsientoExterno` varchar(50) NOT NULL,
`IdDiarioExterno` varchar(10) NOT NULL,
`IdFacturaExterno` varchar(50) NOT NULL,
`IdMovimiento` varchar(40) NOT NULL,
`IdCuadre` smallint(6) NOT NULL,
`FechaCuadre` datetime NOT NULL,
`TipoCuadre` varchar(4) NOT NULL,
`AgrupacionCuadre` int(11) NOT NULL,
`StatusSaldo` smallint(6) NOT NULL,
`StatusConciliacion` smallint(6) NOT NULL,
`CodigoConciliacion` int(11) NOT NULL,
`FechaConciliacion` datetime NOT NULL,
`TipoConciliacion` smallint(6) NOT NULL,
`IndicadorContaBanco` varchar(1) NOT NULL,
`Descripcion3` varchar(40) NOT NULL,
`Descripcion4` varchar(40) NOT NULL,
`Descripcion5` varchar(40) NOT NULL,
`Descripcion6` varchar(40) NOT NULL,
`Descripcion7` varchar(40) NOT NULL,
`Descripcion8` varchar(50) NOT NULL,
`Descripcion9` varchar(50) NOT NULL,
`Descripcion2` varchar(250) NOT NULL,
`Descripcion1` varchar(250) NOT NULL,
`Punteo1` smallint(6) NOT NULL,
`Punteo9` smallint(6) NOT NULL,
`Punteo8` smallint(6) NOT NULL,
`Punteo7` smallint(6) NOT NULL,
`Punteo6` smallint(6) NOT NULL,
`Punteo5` smallint(6) NOT NULL,
`Punteo4` smallint(6) NOT NULL,
`Punteo3` smallint(6) NOT NULL,
`Punteo2` smallint(6) NOT NULL,
`CodigoIva1` smallint(6) NOT NULL,
`CodigoIva2` smallint(6) NOT NULL,
`CodigoIva3` smallint(6) NOT NULL,
`CodigoIva4` smallint(6) NOT NULL,
`CriterioIva` tinyint(4) NOT NULL,
`FechaMaxVencimiento` datetime NOT NULL,
`TipoCriterioCaja` tinyint(4) NOT NULL,
`MovFacturaOrigenIME` varchar(50) NOT NULL,
`IdFacturaExternoFinal` varchar(50) NOT NULL,
`IdFacturaExternoInicial` varchar(50) NOT NULL,
`IdFacturaExternoOriginal` varchar(50) NOT NULL,
`NumFacturasExternoAgrupacion` int(11) NOT NULL,
`CodigoMedioCobro` varchar(1) NOT NULL,
`MedioCobro` varchar(31) NOT NULL,
`IvaDeducible1` smallint(6) NOT NULL DEFAULT 1,
`IvaDeducible2` smallint(6) NOT NULL DEFAULT 1,
`IvaDeducible3` smallint(6) NOT NULL DEFAULT 1,
`IvaDeducible4` smallint(6) NOT NULL DEFAULT 1,
`TipoRectificativa` smallint(6) NOT NULL,
`FechaFacturaOriginal` datetime NOT NULL,
`BaseImponibleOriginal` decimal(28,10) NOT NULL,
`CuotaIvaOriginal` decimal(28,10) NOT NULL,
`ClaseAbonoRectificativas` smallint(6) NOT NULL,
`RecargoEquivalenciaOriginal` decimal(28,10) NOT NULL,
`ObjetoFactura` varchar(500) NOT NULL,
`enlazadoSage` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`OrdenMovimientos`,`LibreN1`),
KEY `ix_movconta2` (`IdProcesoIME`),
KEY `CodigoCuenta` (`CodigoCuenta`),
KEY `movConta_Asiento` (`Asiento`),
KEY `ix_movconta` (`enlazadoSage`,`IdProcesoIME`),
KEY `movConta_IdProcesoIME` (`IdProcesoIME`),
KEY `movConta_Asiento2` (`Asiento`,`IdProcesoIME`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `movContaIVA`
--
DROP TABLE IF EXISTS `movContaIVA`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `movContaIVA` (
`id` int(11) NOT NULL,
`CodigoDivisa` varchar(3) NOT NULL,
`BaseIva1` double DEFAULT NULL,
`PorBaseCorrectora1` double DEFAULT NULL,
`PorIva1` double DEFAULT NULL,
`CuotaIva1` double DEFAULT NULL,
`PorRecargoEquivalencia1` double DEFAULT NULL,
`RecargoEquivalencia1` double DEFAULT NULL,
`CodigoTransaccion1` double NOT NULL DEFAULT 0,
`CodigoIva1` smallint(6) NOT NULL,
`BaseIva2` double DEFAULT NULL,
`PorBaseCorrectora2` double DEFAULT NULL,
`PorIva2` double DEFAULT NULL,
`CuotaIva2` double DEFAULT NULL,
`PorRecargoEquivalencia2` double DEFAULT NULL,
`RecargoEquivalencia2` double DEFAULT NULL,
`CodigoTransaccion2` double NOT NULL DEFAULT 0,
`CodigoIva2` smallint(6) NOT NULL,
`BaseIva3` double DEFAULT NULL,
`PorBaseCorrectora3` double DEFAULT NULL,
`PorIva3` double DEFAULT NULL,
`CuotaIva3` double DEFAULT NULL,
`PorRecargoEquivalencia3` double DEFAULT NULL,
`RecargoEquivalencia3` double DEFAULT NULL,
`CodigoTransaccion3` double NOT NULL DEFAULT 0,
`CodigoIva3` smallint(6) NOT NULL,
`BaseIva4` double DEFAULT NULL,
`PorBaseCorrectora4` double DEFAULT NULL,
`PorIva4` double DEFAULT NULL,
`CuotaIva4` double DEFAULT NULL,
`PorRecargoEquivalencia4` double DEFAULT NULL,
`RecargoEquivalencia4` double DEFAULT NULL,
`CodigoTransaccion4` double NOT NULL DEFAULT 0,
`CodigoIva4` smallint(6) NOT NULL,
`Año` int(11) DEFAULT NULL,
`Serie` varchar(10) DEFAULT NULL,
`Factura` int(11) DEFAULT NULL,
`SuFacturaNo` varchar(40) DEFAULT NULL,
`FechaFactura` date DEFAULT NULL,
`ImporteFactura` double DEFAULT NULL,
`TipoFactura` varchar(1) DEFAULT NULL,
`CodigoCuentaFactura` varchar(15) DEFAULT NULL,
`CifDni` varchar(13) DEFAULT NULL,
`Nombre` varchar(35) DEFAULT NULL,
`CodigoRetencion` int(2) DEFAULT NULL,
`BaseRetencion` double DEFAULT NULL,
`PorRetencion` double DEFAULT NULL,
`ImporteRetencion` double DEFAULT NULL,
`SiglaNacion` varchar(2) NOT NULL DEFAULT 'ES',
`EjercicioFactura` int(2) DEFAULT NULL,
`FechaOperacion` date DEFAULT NULL,
`Exclusion347` int(2) DEFAULT NULL,
`MantenerAsiento` int(2) DEFAULT -1,
`Metalico347` int(2) DEFAULT NULL,
`ClaveOperacionFactura` varchar(1) DEFAULT NULL,
`TipoRectificativa` int(2) DEFAULT NULL,
`FechaFacturaOriginal` date DEFAULT NULL,
`CuotaIvaOriginal` double DEFAULT NULL,
`BaseImponibleOriginal` double DEFAULT NULL,
`ClaseAbonoRectificativas` int(2) DEFAULT NULL,
`RecargoEquivalenciaOriginal` double DEFAULT NULL,
`LibreA1` varchar(15) DEFAULT NULL,
`IvaDeducible1` int(2) NOT NULL DEFAULT -1,
`IvaDeducible2` int(2) NOT NULL DEFAULT -1,
`IvaDeducible3` int(2) NOT NULL DEFAULT -1,
`IvaDeducible4` int(2) NOT NULL DEFAULT -1,
`FechaGrabacion` date DEFAULT NULL,
`Intracomunitaria` tinyint(1) DEFAULT 0,
`moveData` tinyint(1) DEFAULT 1,
PRIMARY KEY (`id`),
CONSTRAINT `movContaIVA_fk1` FOREIGN KEY (`id`) REFERENCES `vn`.`XDiario` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Informa del valor de los campos de IVA para enlazar en la tabla vn.movConta';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `pgcToSage`
--
DROP TABLE IF EXISTS `pgcToSage`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `pgcToSage` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`taxCodeSage` int(11) NOT NULL,
`transactionCode` int(11) NOT NULL,
`accountTaxInput` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL,
`accountTaxOutput` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Tabla relaciona cuentas pgc con Código de IVA y Código de Transacción en Sage';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `planCuentasPGC`
--
DROP TABLE IF EXISTS `planCuentasPGC`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `planCuentasPGC` (
`CodigoEmpresa` smallint(6) NOT NULL,
`CodigoCuenta` varchar(15) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`Cuenta` varchar(50) NOT NULL,
`ClienteOProveedor` varchar(1) NOT NULL,
`CodigoDivisa` varchar(3) NOT NULL DEFAULT '',
`IndicadorProrrata` smallint(6) NOT NULL DEFAULT 0,
`TipoPlanCuentaIME` smallint(6) NOT NULL DEFAULT 2,
`StatusAnalitica` smallint(6) NOT NULL DEFAULT 0,
`AnaCodigoCuenta` varchar(15) NOT NULL DEFAULT '',
`StatusTraspasadoIME` tinyint(4) NOT NULL DEFAULT 0,
`TipoImportacionIME` tinyint(4) NOT NULL DEFAULT 0,
`CierrePatrimonio_` smallint(6) NOT NULL DEFAULT 0,
`CuentaPatrimonio_` varchar(15) NOT NULL DEFAULT '',
`CuentaVarios` smallint(6) NOT NULL DEFAULT 0,
`TodasLasActividades` smallint(6) NOT NULL DEFAULT 0,
`ValorDelegacion` varchar(10) NOT NULL DEFAULT '',
`ValorDepartamento` varchar(10) NOT NULL DEFAULT '',
`ValorProyecto` varchar(10) NOT NULL DEFAULT '',
`ValorCanal` varchar(10) NOT NULL DEFAULT '',
`ValorSeccion` varchar(10) NOT NULL DEFAULT '',
PRIMARY KEY (`CodigoEmpresa`,`CodigoCuenta`),
KEY `CodigoCuenta` (`CodigoCuenta`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `supplierLastThreeMonths`
--
DROP TABLE IF EXISTS `supplierLastThreeMonths`;
/*!50001 DROP VIEW IF EXISTS `supplierLastThreeMonths`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `supplierLastThreeMonths` AS SELECT
1 AS `supplierFk`,
1 AS `companyFk` */;
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` int(11) NOT NULL,
`code` varchar(25) DEFAULT NULL,
`isIntracommunity` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `taxType_UN` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Coincidencia del id con Sage.TiposIVA.CodigoIva(propia de Sage), en ningún caso vincular mediate FK';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping events for database 'sage'
--
--
-- Dumping routines for database 'sage'
--
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `company_getCode` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `company_getCode`(vCompanyFk INT) RETURNS int(2)
READS SQL DATA
BEGIN
/**
* Devuelve la correspondencía del código de empresa de sage.
* Tiene en cuenta el entorno
*
* @param vSelf Id de empresa de verdnatura
* @return Código de empresa sage
*/
DECLARE vCompanySageFk INT(2);
SELECT IF(c.environment = 'production',
co.companyCode,
co.companyCodeTest
) INTO vCompanySageFk
FROM util.config c
JOIN vn.company co
WHERE co.id = vCompanyFk;
RETURN vCompanySageFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `accountingMovements_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `accountingMovements_add`(
vYear INT,
vCompanyFk INT
)
BEGIN
/**
* Traslada la info de contabilidad generada en base a vn.XDiario a la tabla sage.movConta
* para poder ejecutar posteriormente el proceso de importación de datos de SQL Server
* Solo traladará los asientos marcados con el campo vn.XDiario.enlazadoSage = FALSE
* @vYear Año contable del que se quiere trasladar la información
* @vCompanyFk Empresa de la que se quiere trasladar datos
*/
DECLARE vDatedFrom DATETIME;
DECLARE vDatedTo DATETIME;
DECLARE vDuaTransactionFk INT;
DECLARE vTaxImportFk INT;
DECLARE vTaxImportReducedFk INT;
DECLARE vTaxImportSuperReducedFk INT;
DECLARE vTransactionExportFk INT;
DECLARE vTransactionExportTaxFreeFk INT;
DECLARE vSerialDua VARCHAR(1) DEFAULT 'D';
DECLARE vInvoiceTypeInformativeCode VARCHAR(1);
DECLARE vCountryCanariasCode, vCountryCeutaMelillaCode VARCHAR(2) ;
SELECT SiglaNacion INTO vCountryCanariasCode
FROM Naciones
WHERE Nacion ='ISLAS CANARIAS';
SELECT SiglaNacion INTO vCountryCeutaMelillaCode
FROM Naciones
WHERE Nacion ='CEUTA Y MELILLA';
SELECT pendingServiceTransactionTypeFk INTO vDuaTransactionFk
FROM config;
SELECT id INTO vTaxImportFk
FROM taxType
WHERE code = 'import21';
SELECT id INTO vTaxImportReducedFk
FROM taxType
WHERE code = 'import10';
SELECT id INTO vTaxImportSuperReducedFk
FROM taxType
WHERE code = 'import4';
SELECT definitiveExportTransactionTypeFk INTO vTransactionExportFk
FROM config;
SELECT shipmentTransactionTypeFk INTO vTransactionExportTaxFreeFk
FROM config;
SELECT codeSage INTO vInvoiceTypeInformativeCode
FROM invoiceType WHERE code ='informative';
SELECT MAKEDATE(vYear, 1), MAKEDATE(vYear + 1, 1) - INTERVAL 1 DAY
INTO vDatedFrom, vDatedTo;
TRUNCATE movContaIVA;
DELETE FROM movConta
WHERE enlazadoSage = FALSE
AND Asiento <> 1 ;
CALL clientSupplier_add(vCompanyFk);
CALL pgc_add(vCompanyFk);
CALL invoiceOut_manager(vYear, vCompanyFk);
CALL invoiceIn_manager(vYear, vCompanyFk);
INSERT INTO movConta(TipoEntrada,
Ejercicio,
CodigoEmpresa,
Asiento,
CargoAbono,
CodigoCuenta,
Contrapartida,
FechaAsiento,
Comentario,
ImporteAsiento,
NumeroPeriodo,
FechaGrabacion,
CodigoDivisa,
ImporteCambio,
ImporteDivisa,
FactorCambio,
IdProcesoIME,
TipoCarteraIME,
TipoAnaliticaIME,
StatusTraspasadoIME,
TipoImportacionIME,
Metalico347,
BaseIva1,
PorBaseCorrectora1,
PorIva1,
CuotaIva1,
PorRecargoEquivalencia1,
RecargoEquivalencia1,
CodigoTransaccion1,
BaseIva2,
PorBaseCorrectora2,
PorIva2,
CuotaIva2,
PorRecargoEquivalencia2,
RecargoEquivalencia2,
CodigoTransaccion2,
BaseIva3,
PorBaseCorrectora3,
PorIva3,
CuotaIva3,
PorRecargoEquivalencia3,
RecargoEquivalencia3,
CodigoTransaccion3,
BaseIva4,
PorBaseCorrectora4,
PorIva4,
CuotaIva4,
PorRecargoEquivalencia4,
RecargoEquivalencia4,
CodigoTransaccion4,
Año,
Serie,
Factura,
SuFacturaNo,
FechaFactura,
ImporteFactura,
TipoFactura,
CodigoCuentaFactura,
CifDni,
Nombre,
CodigoRetencion,
BaseRetencion,
PorRetencion,
ImporteRetencion,
SiglaNacion,
EjercicioFactura,
FechaOperacion,
Exclusion347,
MantenerAsiento,
ClaveOperacionFactura_,
TipoRectificativa,
FechaFacturaOriginal,
BaseImponibleOriginal,
CuotaIvaOriginal,
ClaseAbonoRectificativas,
RecargoEquivalenciaOriginal,
LibreA1,
CodigoIva1,
CodigoIva2,
CodigoIva3,
CodigoIva4,
IvaDeducible1,
IvaDeducible2,
IvaDeducible3,
IvaDeducible4,
Intracomunitaria
)
SELECT 'EN' TipoEntrada,
YEAR(x.FECHA) Ejercicio,
company_getCode(vCompanyFk) AS CodigoEmpresa,
x.ASIEN Asiento,
IF(EURODEBE <> 0 OR (EURODEBE = 0 AND EUROHABER IS NULL),
'D', 'H') CargoAbono,
x.SUBCTA CodigoCuenta,
x.CONTRA Contrapartida,
x.FECHA FechaAsiento,
x.CONCEPTO Comentario,
IF(x.EURODEBE, x.EURODEBE, x.EUROHABER) ImporteAsiento,
MONTH(x.FECHA) NumeroPeriodo,
IF(sub2.FECREGCON IS NULL, sub2.FECHA_EX, sub2.FECREGCON) FechaGrabacion,
IF(x.CAMBIO, IFNULL(mci.CodigoDivisa, sub3.code), '') CodigoDivisa,
x.CAMBIO ImporteCambio,
IFNULL(x.DEBEME, x.HABERME) ImporteDivisa,
IF(x.CAMBIO, TRUE, FALSE) FactorCambio,
NULL IdProcesoIME,
0 TipoCarteraIME,
0 TipoAnaliticaIME,
0 StatusTraspasadoIME,
0 TipoImportacionIME,
x.METAL Metalico347,
mci.BaseIva1,
mci.PorBaseCorrectora1,
mci.PorIva1,
mci.CuotaIva1,
mci.PorRecargoEquivalencia1,
mci.RecargoEquivalencia1,
mci.CodigoTransaccion1,
mci.BaseIva2,
mci.PorBaseCorrectora2,
mci.PorIva2,
mci.CuotaIva2,
mci.PorRecargoEquivalencia2,
mci.RecargoEquivalencia2,
mci.CodigoTransaccion2,
mci.BaseIva3,
mci.PorBaseCorrectora3,
mci.PorIva3,
mci.CuotaIva3,
mci.PorRecargoEquivalencia3,
mci.RecargoEquivalencia3,
mci.CodigoTransaccion3,
mci.BaseIva4,
mci.PorBaseCorrectora4,
mci.PorIva4,
mci.CuotaIva4,
mci.PorRecargoEquivalencia4,
mci.RecargoEquivalencia4,
mci.CodigoTransaccion4,
mci.Año,
mci.Serie,
mci.Factura,
mci.SuFacturaNo,
mci.FechaFactura,
mci.ImporteFactura,
mci.TipoFactura,
mci.CodigoCuentaFactura,
mci.CifDni,
mci.Nombre,
mci.CodigoRetencion,
mci.BaseRetencion,
mci.PorRetencion,
mci.ImporteRetencion,
mci.SiglaNacion,
mci.EjercicioFactura,
mci.FechaOperacion,
mci.Exclusion347,
TRUE,
mci.ClaveOperacionFactura,
mci.TipoRectificativa,
mci.FechaFacturaOriginal,
mci.BaseImponibleOriginal,
mci.CuotaIvaOriginal,
mci.ClaseAbonoRectificativas,
mci.RecargoEquivalenciaOriginal,
mci.LibreA1,
mci.CodigoIva1,
mci.CodigoIva2,
mci.CodigoIva3,
mci.CodigoIva4,
mci.IvaDeducible1,
mci.IvaDeducible2,
mci.IvaDeducible3,
mci.IvaDeducible4,
mci.Intracomunitaria
FROM vn.XDiario x
LEFT JOIN movContaIVA mci ON mci.id = x.id
LEFT JOIN (SELECT *
FROM (SELECT DISTINCT ASIEN, FECREGCON, FECHA_EX
FROM vn.XDiario
WHERE enlazadoSage = FALSE
ORDER BY ASIEN, FECREGCON DESC, FECHA_EX DESC
LIMIT 10000000000000000000
) sub GROUP BY ASIEN
)sub2 ON sub2.ASIEN = x.ASIEN
LEFT JOIN ( SELECT DISTINCT(a.account),cu.code
FROM vn.accounting a
JOIN vn.currency cu ON cu.id = a.currencyFk
WHERE cu.code <> 'EUR' -- no se informa cuando la divisa en EUR
)sub3 ON sub3.account = x.SUBCTA
WHERE x.enlazadoSage = FALSE
AND x.empresa_id = vCompanyFk
AND x.FECHA BETWEEN vDatedFrom AND vDatedTo;
-- Metálicos
UPDATE movConta m
JOIN (SELECT Asiento,
c.socialName name,
c.fi,
n.SiglaNacion,
m.CodigoCuenta,
m.Contrapartida
FROM movConta m
LEFT JOIN vn.client c ON c.id = IF(m.CargoAbono = 'H',
CAST(SUBSTRING(m.CodigoCuenta, 3, LENGTH(m.CodigoCuenta)) AS UNSIGNED),
CAST(SUBSTRING(m.Contrapartida, 3, LENGTH(m.Contrapartida)) AS UNSIGNED))
LEFT JOIN Naciones n ON n.countryFk = c.countryFk
WHERE m.Metalico347 = TRUE
AND m.enlazadoSage = FALSE
)sub ON m.Asiento = sub.Asiento
SET m.Metalico347 = TRUE,
m.TipoFactura = vInvoiceTypeInformativeCode,
m.CifDni = sub.fi,
m.Nombre = sub.name,
m.SiglaNacion = sub.SiglaNacion
WHERE m.enlazadoSage = FALSE;
UPDATE movConta m
SET m.Metalico347 = FALSE,
m.TipoFactura = ''
WHERE m.CargoAbono = 'D'
AND m.enlazadoSage = FALSE;
-- Elimina cuentas de cliente/proveedor que no se utilizarán en la importación
DELETE cp
FROM clientesProveedores cp
LEFT JOIN movConta mc ON mc.codigoCuenta = cp.codigoCuenta
AND mc.enlazadoSage = FALSE
WHERE mc.codigoCuenta IS NULL;
-- Elimina cuentas contables que no se utilizarán en la importación
DELETE pc
FROM planCuentasPGC pc
LEFT JOIN movConta mc ON mc.codigoCuenta = pc.codigoCuenta
AND mc.enlazadoSage = FALSE
WHERE mc.codigoCuenta IS NULL;
-- DUAS
UPDATE movConta mci
JOIN vn.XDiario x ON x.ASIEN = mci.Asiento
JOIN TiposIva ti ON ti.PorcentajeIva = x.IVA
JOIN taxType tt ON tt.id = ti.CodigoIva
JOIN vn.pgcMaster pm ON pm.code = mci.CodigoCuenta COLLATE utf8mb3_unicode_ci
SET mci.BaseIva1 = x.BASEEURO,
mci.PorIva1 = x.IVA,
mci.CuotaIva1 = CAST((x.IVA / 100) * x.BASEEURO AS DECIMAL(10, 2)),
mci.CodigoTransaccion1 = vDuaTransactionFk,
mci.CodigoIva1 = vTaxImportReducedFk,
mci.IvaDeducible1 = TRUE,
mci.FechaFacturaOriginal = x.FECHA_EX,
mci.SuFacturaNo = x.FACTURAEX,
mci.FechaOperacion = x.FECHA_OP,
mci.ImporteFactura = mci.ImporteFactura +
x.BASEEURO +
CAST((x.IVA / 100) * x.BASEEURO AS DECIMAL(10, 2))
WHERE pm.description = 'HP Iva pendiente'
AND mci.enlazadoSage = FALSE
AND x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci
AND tt.code = 'national10';
UPDATE movConta mci
JOIN vn.XDiario x ON x.ASIEN = mci.Asiento
JOIN TiposIva ti ON ti.PorcentajeIva = x.IVA
JOIN taxType tt ON tt.id = ti.CodigoIva
JOIN vn.pgcMaster pm ON pm.code = mci.CodigoCuenta COLLATE utf8mb3_unicode_ci
SET mci.BaseIva2 = x.BASEEURO ,
mci.PorIva2 = x.IVA,
mci.CuotaIva2 = CAST((x.IVA / 100) * x.BASEEURO AS DECIMAL(10,2)),
mci.CodigoTransaccion2 = vDuaTransactionFk ,
mci.CodigoIva2 = vTaxImportFk,
mci.IvaDeducible2 = TRUE,
mci.ImporteFactura = mci.ImporteFactura +
x.BASEEURO +
CAST((x.IVA / 100) * x.BASEEURO AS DECIMAL(10, 2))
WHERE pm.description = 'HP Iva pendiente'
AND mci.enlazadoSage = FALSE
AND x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci
AND tt.code = 'national21';
UPDATE movConta mci
JOIN vn.XDiario x ON x.ASIEN = mci.Asiento
JOIN TiposIva ti ON ti.PorcentajeIva = x.IVA
JOIN taxType tt ON tt.id = ti.CodigoIva
JOIN vn.pgcMaster pm ON pm.code = mci.CodigoCuenta COLLATE utf8mb3_unicode_ci
SET mci.BaseIva3 = x.BASEEURO ,
mci.PorIva3 = x.IVA,
mci.CuotaIva3 = CAST((x.IVA / 100) * x.BASEEURO AS DECIMAL(10,2)),
mci.CodigoTransaccion3 = vDuaTransactionFk ,
mci.CodigoIva3 = vTaxImportSuperReducedFk,
mci.IvaDeducible3 = TRUE,
mci.ImporteFactura = mci.ImporteFactura +
x.BASEEURO +
CAST((x.IVA / 100) * x.BASEEURO AS DECIMAL(10, 2))
WHERE pm.description = 'HP Iva pendiente'
AND mci.enlazadoSage = FALSE
AND x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci
AND tt.code = 'national4';
-- Rectificativas
UPDATE movConta mci
JOIN (SELECT x.ASIEN, x.FECHA_RT, x.SERIE_RT, x.FACTU_RT
FROM movConta mci
JOIN vn.XDiario x ON x.ASIEN = mci.Asiento
WHERE mci.TipoRectificativa > 0
AND mci.enlazadoSage = FALSE
AND x.FACTU_RT IS NOT NULL
GROUP BY x.ASIEN
) sub ON sub.ASIEN = mci.Asiento
SET mci.EjercicioFacturaOriginal = YEAR(sub.FECHA_RT),
mci.SerieFacturaOriginal = sub.SERIE_RT,
mci.NumeroFacturaOriginal = sub.FACTU_RT
WHERE mci.TipoRectificativa > 0 AND
mci.enlazadoSage = FALSE ;
-- Exportaciones Andorras y Canarias cambia TT (la cuenta es compartida)
UPDATE movConta mci
SET CodigoTransaccion1 = vTransactionExportTaxFreeFk,
CodigoTransaccion2 = IF(CodigoTransaccion2 = 0, 0, vTransactionExportTaxFreeFk),
CodigoTransaccion3 = IF(CodigoTransaccion3 = 0, 0, vTransactionExportTaxFreeFk),
CodigoTransaccion4 = IF(CodigoTransaccion4 = 0, 0, vTransactionExportTaxFreeFk)
WHERE enlazadoSage = FALSE
AND (CodigoTransaccion1 = vTransactionExportFk
OR CodigoTransaccion2 = vTransactionExportFk
OR CodigoTransaccion3 = vTransactionExportFk
OR CodigoTransaccion4 = vTransactionExportFk)
AND SiglaNacion IN (vCountryCanariasCode COLLATE utf8mb3_unicode_ci,
vCountryCeutaMelillaCode COLLATE utf8mb3_unicode_ci);
UPDATE movConta mc
SET CodigoDivisa = 'USD',
FactorCambio = TRUE,
ImporteCambio = ABS( CAST( IF( ImporteDivisa <> 0 AND ImporteCambio = 0,
ImporteAsiento / ImporteDivisa,
ImporteCambio) AS DECIMAL( 10, 2)))
WHERE enlazadoSage = FALSE
AND (ImporteCambio <> 0 OR ImporteDivisa <> 0 OR FactorCambio);
UPDATE movConta mc
SET importeDivisa= -importeDivisa
WHERE enlazadoSage = FALSE
AND importeDivisa > 0
AND ImporteAsiento < 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`()
BEGIN
/**
* Maintains tables over time by removing unnecessary data
*/
DECLARE vTwoYearAgo DATE DEFAULT util.VN_CURDATE() - INTERVAL 2 YEAR;
DELETE FROM movConta WHERE FechaAsiento < vTwoYearAgo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `clientSupplier_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clientSupplier_add`(vCompanyFk INT)
BEGIN
/**
* Prepara los datos de clientes y proveedores para exportarlos a Sage
* @vCompanyFk Empresa dela que se quiere trasladar datos
*/
DECLARE vCountryCeutaMelillaFk INT;
DECLARE vCountryCanariasCode, vCountryCeutaMelillaCode VARCHAR(2);
SELECT SiglaNacion INTO vCountryCanariasCode
FROM Naciones
WHERE Nacion ='ISLAS CANARIAS';
SELECT CodigoNacion, SiglaNacion INTO vCountryCeutaMelillaFk, vCountryCeutaMelillaCode
FROM Naciones
WHERE Nacion ='CEUTA Y MELILLA';
TRUNCATE TABLE clientesProveedores;
INSERT INTO clientesProveedores
(CodigoEmpresa,
ClienteOProveedor,
CodigoClienteProveedor,
RazonSocial,
Nombre,
Domicilio,
CodigoCuenta,
CifDni,
CifEuropeo,
CodigoPostal,
Municipio,
CodigoProvincia,
Provincia,
CodigoNacion,
SiglaNacion,
PersonaFisicaJuridica,
TipoDocumentoPersona,
CodigoIva,
Nacion,
Telefono,
Telefono2,
CodigoTransaccion,
CodigoRetencion,
Email1,
iban)
SELECT
company_getCode(vCompanyFk),
'C',
c.id,
c.socialName,
c.socialName,
IFNULL(c.street, ''),
c.accountingAccount,
@fi := IF(cu.code = LEFT(TRIM(c.fi), 2) AND c.isVies, MID(TRIM(c.fi), 3, LENGTH(TRIM(c.fi))-1), TRIM(c.fi)),
IF(c.isVies, CONCAT(cu.code, @fi ), TRIM(c.fi)),
IFNULL(c.postcode, ''),
IFNULL(c.city, ''),
IFNULL(pr.CodigoProvincia, ''),
IFNULL(p.name, ''),
IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, IF(@isCeutaMelilla := IF(pr.Provincia IN ('CEUTA', 'MELILLA'), TRUE, FALSE), vCountryCeutaMelillaFk, IF (@isCanarias, vCountryCanariasCode, n.CodigoNacion)), n.CodigoNacion),
IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, IF(@isCeutaMelilla, vCountryCeutaMelillaCode, IF (@isCanarias, vCountryCanariasCode, n.SiglaNacion)), n.SiglaNacion),
IF((c.fi REGEXP '^([[:blank:]]|[[:digit:]])'), 'J','F'),
IF(cu.code = 'ES',
1,
IF((cu.isUeeMember AND c.isVies), 2, 4)),
IFNULL(c.taxTypeSageFk,0),
IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci,
IF(@isCeutaMelilla, 'CEUTA Y MELILLA', IF (@isCanarias, 'ISLAS CANARIAS', n.Nacion)),
n.Nacion),
IFNULL(c.phone, ''),
IFNULL(c.mobile, ''),
IFNULL(c.transactionTypeSageFk, 0),
'0',
IFNULL(SUBSTR(c.email, 1, LOCATE(',', CONCAT(c.email, ','))-1), ''),
IFNULL(c.iban, '')
FROM vn.`client` c
JOIN clientLastTwoMonths clm ON clm.clientFk = c.id
LEFT JOIN vn.country cu ON cu.id = c.countryFk
LEFT JOIN Naciones n ON n.countryFk = cu.id
LEFT JOIN vn.province p ON p.id = c.provinceFk
LEFT JOIN Provincias pr ON pr.provinceFk = p.id
WHERE c.isRelevant
AND clm.companyFk = vCompanyFk
UNION ALL
SELECT company_getCode(vCompanyFk),
'P',
s.id,
s.name,
s.name,
IFNULL(s.street, ''),
s.account,
@nif := IF(co.code = LEFT(TRIM(s.nif), 2), MID(TRIM(s.nif), 3, LENGTH(TRIM(s.nif))-1), TRIM(s.nif)),
IF(s.isVies, CONCAT(co.code, @nif), TRIM(s.nif)),
IFNULL(s.postCode,''),
IFNULL(s.city, ''),
IFNULL(pr.CodigoProvincia, ''),
IFNULL(p.name, ''),
n.CodigoNacion,
n.SiglaNacion COLLATE utf8mb3_unicode_ci,
IF((s.nif REGEXP '^([[:blank:]]|[[:digit:]])'),'J','F'),
IF(co.code = 'ES', 1, IF(co.isUeeMember, 2, 4)),
IFNULL(s.taxTypeSageFk, 0),
n.Nacion,
IFNULL(sc.phone, ''),
IFNULL(sc.mobile, ''),
IFNULL(s.transactionTypeSageFk, 0),
IFNULL(s.withholdingSageFk, '0'),
IFNULL(SUBSTR(sc.email, 1, (COALESCE(NULLIF(LOCATE(',', sc.email), 0), 99) - 1)), ''),
IFNULL(iban, '')
FROM vn.supplier s
JOIN supplierLastThreeMonths pl ON pl.supplierFk = s.id
LEFT JOIN vn.country co ON co.id = s.countryFk
LEFT JOIN Naciones n ON n.countryFk = co.id
LEFT JOIN vn.province p ON p.id = s.provinceFk
LEFT JOIN Provincias pr ON pr.provinceFk = p.id
LEFT JOIN vn.supplierContact sc ON sc.supplierFk = s.id
LEFT JOIN vn.supplierAccount sa ON sa.supplierFk = s.id
WHERE pl.companyFk = vCompanyFk AND
s.isActive AND
s.nif <> ''
GROUP BY pl.supplierFk, pl.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `importErrorNotification` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importErrorNotification`()
BEGIN
/**
* Inserta notificaciones con los errores detectados durante la importación
*
*/
DECLARE vBookEntries TEXT;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
SELECT GROUP_CONCAT(error SEPARATOR ' ') INTO vBookEntries
FROM(
SELECT CONCAT('- Importes: ', sub.Asiento) error
FROM (SELECT mc.Asiento, SUM(mc.ImporteAsiento) amount
FROM movConta mc
WHERE mc.enlazadoSage = FALSE
GROUP BY mc.Asiento)sub
JOIN (SELECT x.ASIEN, SUM(IFNULL(x.EURODEBE,0) + IFNULL(x.EUROHABER,0)) amount
FROM vn.XDiario x
WHERE x.enlazadoSage = FALSE
GROUP BY ASIEN)sub2 ON sub2.ASIEN = sub.Asiento
WHERE sub.amount <> sub2.amount
UNION ALL
SELECT CONCAT('- Base imponible: ', sub.Asiento)
FROM (SELECT Asiento, SUM(BaseIva1 + BaseIva2 + BaseIva3 + BaseIva4) amountTaxableBase
FROM movConta
WHERE TipoFactura <> 'I'
AND enlazadoSage = FALSE
GROUP BY Asiento) sub
JOIN (SELECT ASIEN, SUM(BASEEURO) amountTaxableBase
FROM (SELECT ASIEN, SUM(BASEEURO) BASEEURO
FROM vn.XDiario
WHERE FACTURA
AND auxiliar <> '*'
AND enlazadoSage = FALSE
GROUP BY FACTURA, ASIEN)sub3
GROUP BY ASIEN) sub2 ON sub2.ASIEN = sub.Asiento
WHERE sub.amountTaxableBase<>sub2.amountTaxableBase
AND sub.amountTaxableBase/2 <> sub2.amountTaxableBase
UNION ALL
SELECT CONCAT('- Factura Duplicada: ', accountingEntryFk)
FROM accountingEntryError
)sub;
IF vBookEntries IS NOT NULL THEN
START TRANSACTION;
SELECT util.notification_send ("book-entries-imported-incorrectly",
CONCAT('{"bookEntries":"', vBookEntries,'"}'),
null);
TRUNCATE accountingEntryError;
COMMIT;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceIn_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_add`(vInvoiceInFk INT, vXDiarioFk INT)
BEGIN
/**
* Traslada la info de contabilidad relacionada con las facturas recibidas
*
* @vInvoiceInFk Factura recibida
* @vXDiarioFk Id tabla XDiario
*/
DECLARE vInvoiceInOriginalFk INT;
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vBase DOUBLE;
DECLARE vVat DOUBLE;
DECLARE vRate DOUBLE;
DECLARE vTransactionCode INT;
DECLARE vCounter INT DEFAULT 0;
DECLARE vTransactionCodeOld INT;
DECLARE vTaxCode INT;
DECLARE vTaxCodeOld INT;
DECLARE vOperationCode VARCHAR(1);
DECLARE vIsIntracommunity BOOL DEFAULT FALSE;
DECLARE vSerialDua VARCHAR(1) DEFAULT 'D';
DECLARE vInvoiceTypeReceived VARCHAR(1);
DECLARE vInvoiceTypeInformative VARCHAR(1);
DECLARE vIsInformativeExportation BOOL DEFAULT FALSE;
DECLARE vCursor CURSOR FOR
SELECT it.taxableBase,
CAST((( it.taxableBase / 100) * t.PorcentajeIva) AS DECIMAL (10,2)),
t.PorcentajeIva,
it.transactionTypeSageFk,
it.taxTypeSageFk,
tty.isIntracommunity,
tt.ClaveOperacionDefecto
FROM vn.invoiceIn i
JOIN vn.invoiceInTax it ON it.InvoiceInFk = i.id
JOIN TiposIva t ON t.CodigoIva = it.taxTypeSageFk
JOIN taxType tty ON tty.id = t.CodigoIva
JOIN TiposTransacciones tt ON tt.CodigoTransaccion = it.transactionTypeSageFk
LEFT JOIN vn.dua d ON d.id = vInvoiceInFk
WHERE i.id = vInvoiceInFk
AND d.id IS NULL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DELETE FROM movContaIVA
WHERE id = vXDiarioFk;
SELECT codeSage INTO vInvoiceTypeReceived
FROM invoiceType WHERE code ='received';
SELECT codeSage INTO vInvoiceTypeInformative
FROM invoiceType WHERE code ='informative';
INSERT INTO movContaIVA(id, LibreA1)
VALUES (vXDiarioFk, vInvoiceInFk);
OPEN vCursor;
l: LOOP
FETCH vCursor INTO vBase,
vVat,
vRate,
vTransactionCode,
vTaxCode,
vIsIntracommunity,
vOperationCode;
IF vDone THEN
LEAVE l;
END IF;
SET vTransactionCodeOld = vTransactionCode;
SET vTaxCodeOld = vTaxCode;
IF vOperationCode IS NOT NULL THEN
UPDATE movContaIVA
SET ClaveOperacionFactura = vOperationCode
WHERE id = vXDiarioFk;
END IF;
SET vCounter = vCounter + 1;
CASE vCounter
WHEN 1 THEN
UPDATE movContaIVA
SET BaseIva1 = vBase,
PorIva1 = vRate,
CuotaIva1 = vVat,
CodigoTransaccion1 = vTransactionCode,
CodigoIva1 = vTaxCode
WHERE id = vXDiarioFk;
WHEN 2 THEN
UPDATE movContaIVA
SET BaseIva2 = vBase,
PorIva2 = vRate,
CuotaIva2 = vVat,
CodigoTransaccion2 = vTransactionCode,
CodigoIva2 = vTaxCode
WHERE id = vXDiarioFk;
WHEN 3 THEN
UPDATE movContaIVA
SET BaseIva3 = vBase,
PorIva3 = vRate,
CuotaIva3 = vVat,
CodigoTransaccion3 = vTransactionCode,
CodigoIva3 = vTaxCode
WHERE id = vXDiarioFk;
WHEN 4 THEN
UPDATE movContaIVA
SET BaseIva4 = vBase,
PorIva4 = vRate,
CuotaIva4 = vVat,
CodigoTransaccion4 = vTransactionCode,
CodigoIva4 = vTaxCode
WHERE id = vXDiarioFk;
ELSE
SELECT vXDiarioFk INTO vXDiarioFk;
END CASE;
IF vIsIntracommunity THEN
UPDATE movContaIVA
SET Intracomunitaria = TRUE
WHERE id = vXDiarioFk;
END IF;
SET vTransactionCodeOld = vTransactionCode;
SET vTaxCodeOld = vTaxCode;
END LOOP;
CLOSE vCursor;
SELECT d.ASIEN AND x.ASIEN IS NULL INTO vIsInformativeExportation
FROM vn.dua d
LEFT JOIN vn.XDiario x ON x.ASIEN = d.ASIEN
AND x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci
WHERE d.ASIEN = (
SELECT ASIEN
FROM vn.XDiario
WHERE id = vXDiarioFk)
LIMIT 1;
UPDATE movContaIVA mci
JOIN tmp.invoiceIn ii ON ii.id = vInvoiceInFk
JOIN vn.XDiario x ON x.id = mci.id
LEFT JOIN tmp.invoiceDua id ON id.id = mci.id
JOIN vn.supplier s ON s.id = ii.supplierFk
JOIN Naciones n ON n.countryFk = s.countryFk
SET mci.CodigoDivisa = ii.currencyFk,
mci.Año = YEAR(ii.issued),
mci.Serie = ii.serial,
mci.Factura = ii.id,
mci.FechaFactura = ii.issued,
mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) +
IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) +
IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) +
IFNULL(mci.BaseIva4, 0) + IFNULL(mci.CuotaIva4, 0),
mci.TipoFactura = IF(id.id,
IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative),
IF(vIsInformativeExportation,vInvoiceTypeInformative, vInvoiceTypeReceived)),
mci.CodigoCuentaFactura = x.SUBCTA,
mci.CifDni = IF(LEFT(TRIM(s.nif), 2) = n.SiglaNacion, SUBSTRING(TRIM(s.nif), 3), s.nif),
mci.Nombre = s.name,
mci.SiglaNacion = n.SiglaNacion,
mci.EjercicioFactura = YEAR(ii.issued),
mci.FechaOperacion = ii.issued,
mci.MantenerAsiento = TRUE,
mci.SuFacturaNo = ii.supplierRef,
mci.IvaDeducible1 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva1, FALSE) = FALSE, FALSE, ii.isVatDeductible)),
mci.IvaDeducible2 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva2, FALSE) = FALSE, FALSE, ii.isVatDeductible)),
mci.IvaDeducible3 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva3, FALSE) = FALSE, FALSE, ii.isVatDeductible)),
mci.IvaDeducible4 = IF(id.id, FALSE, IF(IFNULL(mci.BaseIva4, FALSE) = FALSE, FALSE, ii.isVatDeductible)),
mci.FechaFacturaOriginal = x.FECHA_EX
WHERE mci.id = vXDiarioFk;
-- RETENCIONES
UPDATE movContaIVA mci
JOIN vn.invoiceIn ii ON ii.id = vInvoiceInFk
JOIN vn.XDiario x ON x.id = mci.id
JOIN vn.supplier s ON s.id = supplierFk
JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id
JOIN vn.expense e ON e.id = iit.expenseFk
JOIN TiposRetencion t ON t.CodigoRetencion = ii.withholdingSageFk
LEFT JOIN tmp.invoiceDua id ON id.id = mci.id
JOIN (SELECT SUM(x2.BASEEURO) taxableBase, SUM(x2.EURODEBE) taxBase
FROM vn.XDiario x1
JOIN vn.XDiario x2 ON x1.ASIEN = x2.ASIEN
WHERE x2.BASEEURO <> 0
AND x1.id = vXDiarioFk
)sub
JOIN ClavesOperacion co ON co.Descripcion = 'Arrendamiento de locales de negocio'
SET mci.CodigoRetencion = t.CodigoRetencion,
mci.ClaveOperacionFactura = IF( t.Retencion = 'ARRENDAMIENTO Y SUBARRENDAMIENTO', co.ClaveOperacionFactura_, mci.ClaveOperacionFactura),
mci.BaseRetencion = IF (t.Retencion = 'ACTIVIDADES AGRICOLAS O GANADERAS', sub.taxableBase + sub.taxBase, sub.taxableBase),
mci.PorRetencion = t.PorcentajeRetencion,
mci.ImporteRetencion = iit.taxableBase * - 1
WHERE mci.id = vXDiarioFk
AND e.name = 'Retenciones'
AND id.id IS NULL;
SELECT correctedFk INTO vInvoiceInOriginalFk
FROM vn.invoiceInCorrection
WHERE correctingFk = vInvoiceInFk;
IF vInvoiceInOriginalFk THEN
UPDATE movContaIVA mci
JOIN vn.invoiceInRefund iir ON iir.invoiceInRefundFk = vInvoiceInFk
JOIN (SELECT issued,
SUM(sub.taxableBase) taxableBase,
SUM(ROUND((sub.taxableBase * sub.PorcentajeIva) / 100 , 2)) vat
FROM(SELECT issued,
SUM(iit.taxableBase) taxableBase,
ti.PorcentajeIva
FROM vn.invoiceIn i
JOIN vn.invoiceInTax iit ON iit.invoiceInFk = i.id
JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk
WHERE i.id = vInvoiceInOriginalFk
GROUP BY ti.CodigoIva)sub
)invoiceInOriginal
JOIN ClavesOperacion co ON co.Descripcion = 'Factura rectificativa'
SET mci.TipoRectificativa = iir.refundCategoryFk,
mci.ClaseAbonoRectificativas = iir.refundType,
mci.FechaFacturaOriginal = invoiceInOriginal.issued,
mci.FechaOperacion = invoiceInOriginal.issued,
mci.BaseImponibleOriginal = invoiceInOriginal.taxableBase,
mci.CuotaIvaOriginal = invoiceInOriginal.vat,
mci.ClaveOperacionFactura = co.ClaveOperacionFactura_
WHERE mci.id = vXDiarioFk;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceIn_manager` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_manager`(vYear INT, vCompanyFk INT)
BEGIN
/**
* Traslada la info de contabilidad relacionada con las facturas recibidas
*
* @vYear Año contable del que se quiere trasladar la información
* @vCompany Empresa de la que se quiere trasladar datos
*/
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vInvoiceFk INT;
DECLARE vXDiarioFk INT;
DECLARE vDatedFrom DATETIME;
DECLARE vDatedTo DATETIME;
DECLARE vSerialDua VARCHAR(1) DEFAULT 'D';
DECLARE vAccountVNL VARCHAR(10);
DECLARE vAccountTaxOutstanding VARCHAR(10);
DECLARE vInvoiceTypeSended VARCHAR(1);
DECLARE vCursor CURSOR FOR
SELECT IFNULL(x.CLAVE, x.FACTURA) invoiceInFk,
x.id XDiarioFk
FROM vn.XDiario x
JOIN(SELECT DISTINCT(x.ASIEN)
FROM vn.XDiario x
LEFT JOIN vn.invoiceIn ii ON x.CLAVE = ii.id
LEFT JOIN vn.invoiceInTax it ON it.invoiceInFk = ii.id
WHERE(it.taxTypeSageFk IS NOT NULL OR x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci)
AND x.enlazadoSage = FALSE
AND x.FECHA BETWEEN vDatedFrom AND vDatedTo
AND x.empresa_id = vCompanyFk
) sub ON sub.ASIEN = x.ASIEN
WHERE x.CLAVE IS NOT NULL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SELECT CAST(CONCAT(vYear, '-01-01') AS DATETIME), util.dayEnd(CAST(CONCAT(vYear, '-12-31') AS DATE))
INTO vDatedFrom, vDatedTo;
SELECT accountingAccount INTO vAccountVNL
FROM vn.`client`
WHERE name='VNL';
SELECT code INTO vAccountTaxOutstanding
FROM vn.pgcMaster
WHERE description = 'HP Iva pendiente';
SELECT codeSage INTO vInvoiceTypeSended
FROM invoiceType WHERE `code` ='sended';
DROP TEMPORARY TABLE IF EXISTS tmp.invoiceDua;
CREATE TEMPORARY TABLE tmp.invoiceDua
SELECT x.id
FROM vn.XDiario x
JOIN vn.company c ON c.id = x.empresa_id
JOIN (SELECT ASIEN
FROM vn.XDiario x
WHERE x.enlazadoSage = FALSE
AND x.SUBCTA = vAccountTaxOutstanding COLLATE utf8mb3_unicode_ci
AND x.FECHA BETWEEN vDatedFrom AND vDatedTo
)sub ON sub.ASIEN = x.ASIEN
WHERE NOT x.CONTRA <=> vAccountVNL;
DROP TEMPORARY TABLE IF EXISTS tmp.invoiceIn;
CREATE TEMPORARY TABLE tmp.invoiceIn
SELECT i.id,
i.supplierRef,
i.serial COLLATE utf8mb3_unicode_ci serial,
i.supplierFk,
i.issued,
IF(expenseFkDeductible, FALSE, i.isVatDeductible) isVatDeductible,
IF(c.code = 'EUR', '',c.`code`) currencyFk
FROM vn.invoiceIn i
JOIN vn.currency c ON c.id = i.currencyFk
WHERE i.bookEntried BETWEEN vDatedFrom AND vDatedTo
UNION ALL
SELECT d.id,
d.code,
vSerialDua COLLATE utf8mb3_unicode_ci,
d.companyFk ,
d.issued,
FALSE,
'' -- EUROS
FROM vn.dua d
WHERE d.issued IS NOT NULL
AND code IS NOT NULL;
OPEN vCursor;
l: LOOP
FETCH vCursor INTO vInvoiceFk, vXDiarioFk;
IF vDone THEN
LEAVE l;
END IF;
CALL invoiceIn_add(vInvoiceFk, vXDiarioFk);
END LOOP;
CLOSE vCursor;
DROP TEMPORARY TABLE tmp.invoiceDua;
DROP TEMPORARY TABLE tmp.invoiceIn;
-- ASIENTOS CON IVA SOPORTADO 472. y 477. hay que informar 2 líneas la info de facturas una como tipo de factura emitida y otra como recibida
DROP TEMPORARY TABLE IF EXISTS tmp.movContaIVA;
CREATE TEMPORARY TABLE tmp.movContaIVA
SELECT sub3.id,
mci.CodigoDivisa,
mci.BaseIva1,
mci.PorBaseCorrectora1,
mci.PorIva1,
mci.CuotaIva1,
mci.PorRecargoEquivalencia1,
mci.RecargoEquivalencia1,
mci.CodigoTransaccion1,
mci.CodigoIva1,
mci.BaseIva2,
mci.PorBaseCorrectora2,
mci.PorIva2,
mci.CuotaIva2,
mci.PorRecargoEquivalencia2,
mci.RecargoEquivalencia2,
mci.CodigoTransaccion2,
mci.CodigoIva2,
mci.BaseIva3,
mci.PorBaseCorrectora3,
mci.PorIva3,
mci.CuotaIva3,
mci.PorRecargoEquivalencia3,
mci.RecargoEquivalencia3,
mci.CodigoTransaccion3,
mci.CodigoIva3,
mci.BaseIva4,
mci.PorBaseCorrectora4,
mci.PorIva4,
mci.CuotaIva4,
mci.PorRecargoEquivalencia4,
mci.RecargoEquivalencia4,
mci.CodigoTransaccion4,
mci.CodigoIva4,
mci.Año,
mci.Serie,
mci.Factura,
mci.SuFacturaNo,
mci.FechaFactura,
mci.ImporteFactura,
vInvoiceTypeSended,
mci.CodigoCuentaFactura,
mci.CifDni,
mci.Nombre,
mci.CodigoRetencion,
mci.BaseRetencion,
mci.PorRetencion,
mci.ImporteRetencion,
mci.SiglaNacion,
mci.EjercicioFactura,
x.FECHA,
mci.Exclusion347,
mci.MantenerAsiento,
mci.Metalico347,
mci.ClaveOperacionFactura,
mci.TipoRectificativa,
mci.FechaFacturaOriginal,
mci.CuotaIvaOriginal,
mci.BaseImponibleOriginal,
mci.ClaseAbonoRectificativas,
mci.RecargoEquivalenciaOriginal,
mci.LibreA1,
mci.IvaDeducible1,
mci.IvaDeducible2,
mci.IvaDeducible3,
mci.IvaDeducible4,
mci.FechaGrabacion,
mci.Intracomunitaria,
mci.moveData
FROM movContaIVA mci
JOIN vn.XDiario x ON x.id = mci.id
JOIN (SELECT x.ASIEN, x.id
FROM vn.XDiario x
JOIN(SELECT DISTINCT(x.ASIEN) ASIEN
FROM vn.XDiario x
JOIN (SELECT DISTINCT(ASIEN)
FROM vn.XDiario x
WHERE SUBCTA LIKE '472%'
AND x.enlazadoSage = FALSE
AND x.empresa_id = vCompanyFk
AND x.FECHA BETWEEN vDatedFrom AND vDatedTo
) sub ON sub.ASIEN = x.ASIEN
WHERE x.SUBCTA LIKE '477%'
)sub2 ON sub2.ASIEN = x.ASIEN
WHERE x.CONTRA IS NOT NULL
AND x.SUBCTA LIKE '477%'
GROUP BY x.ASIEN
)sub3 ON sub3.ASIEN = x.ASIEN;
INSERT INTO movContaIVA
(`id`,
`CodigoDivisa`,
`BaseIva1`,
`PorBaseCorrectora1`,
`PorIva1`,
`CuotaIva1`,
`PorRecargoEquivalencia1`,
`RecargoEquivalencia1`,
`CodigoTransaccion1`,
`CodigoIva1`,
`BaseIva2`,
`PorBaseCorrectora2`,
`PorIva2`,
`CuotaIva2`,
`PorRecargoEquivalencia2`,
`RecargoEquivalencia2`,
`CodigoTransaccion2`,
`CodigoIva2`,
`BaseIva3`,
`PorBaseCorrectora3`,
`PorIva3`,
`CuotaIva3`,
`PorRecargoEquivalencia3`,
`RecargoEquivalencia3`,
`CodigoTransaccion3`,
`CodigoIva3`,
`BaseIva4`,
`PorBaseCorrectora4`,
`PorIva4`,
`CuotaIva4`,
`PorRecargoEquivalencia4`,
`RecargoEquivalencia4`,
`CodigoTransaccion4`,
`CodigoIva4`,
`Año`,
`Serie`,
`Factura`,
`SuFacturaNo`,
`FechaFactura`,
`ImporteFactura`,
`TipoFactura`,
`CodigoCuentaFactura`,
`CifDni`,
`Nombre`,
`CodigoRetencion`,
`BaseRetencion`,
`PorRetencion`,
`ImporteRetencion`,
`SiglaNacion`,
`EjercicioFactura`,
`FechaOperacion`,
`Exclusion347`,
`MantenerAsiento`,
`Metalico347`,
`ClaveOperacionFactura`,
`TipoRectificativa`,
`FechaFacturaOriginal`,
`CuotaIvaOriginal`,
`BaseImponibleOriginal`,
`ClaseAbonoRectificativas`,
`RecargoEquivalenciaOriginal`,
`LibreA1`,
`IvaDeducible1`,
`IvaDeducible2`,
`IvaDeducible3`,
`IvaDeducible4`,
`FechaGrabacion`,
`Intracomunitaria`,
`moveData`)
SELECT *
FROM tmp.movContaIVA;
DROP TEMPORARY TABLE tmp.movContaIVA;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceOut_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_add`(IN vInvoiceOutFk INT, IN vXDiarioFk INT)
BEGIN
/**
* Traslada la info de contabilidad relacionada con las facturas emitidas
*
* @vYear Año contable del que se quiere trasladar la información
* @vCompany Empresa de la que se quiere trasladar datos
*/
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vMaxLengthName INT DEFAULT 35;
DECLARE vBase DOUBLE;
DECLARE vVat DOUBLE;
DECLARE vRate DOUBLE;
DECLARE vMod347 DOUBLE;
DECLARE vTaxEqu DOUBLE;
DECLARE vRateEqu DOUBLE;
DECLARE vTransactionCode INT;
DECLARE vCounter INT DEFAULT 0;
DECLARE vInvoiceOutCorrectedFk INT;
DECLARE vTaxCode INT;
DECLARE vIsIntracommunity BOOL DEFAULT FALSE;
DECLARE vInvoiceTypeSended VARCHAR(1);
DECLARE vOperationCode VARCHAR(1);
DECLARE vHasCustomsAccountingNote BOOL;
DECLARE vCursor CURSOR FOR
SELECT oit.taxableBase,
oit.vat,
pgc.rate,
pgc.mod347,
pgcRE.rate,
oitRE.vat,
tc.transactionCode,
tc.taxCode,
tc.isIntracommunity,
tc.operationcode
FROM vn.invoiceOutTax oit
JOIN vn.pgc ON pgc.code = oit.pgcFk
LEFT JOIN vn.pgcEqu e ON e.vatFk = oit.pgcFk
LEFT JOIN vn.pgcEqu eRE ON eRE.equFk = oit.pgcFk
LEFT JOIN vn.invoiceOutTax oitRE ON oitRE.invoiceOutFk = oit.invoiceOutFk
AND oitRE.pgcFk = e.equFk
LEFT JOIN vn.pgc pgcRE ON pgcRE.code = oitRE.pgcFk
LEFT JOIN vn.taxCode tc ON tc.code = pgc.code COLLATE 'utf8mb3_unicode_ci'
WHERE eRE.equFk IS NULL
AND oit.invoiceOutFk = vInvoiceOutFk
GROUP BY pgc.code;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SELECT COUNT(*) INTO vHasCustomsAccountingNote
FROM vn.XDiario x
JOIN config c ON c.pendingTaxAccount = x.SUBCTA
WHERE ASIEN = (SELECT ASIEN FROM vn.XDiario WHERE id = vXDiarioFk);
SELECT codeSage INTO vInvoiceTypeSended
FROM invoiceType
WHERE code = IF(vHasCustomsAccountingNote, 'informative', 'sended');
DELETE FROM movContaIVA
WHERE id = vXDiarioFk;
INSERT INTO movContaIVA(id) VALUES (vXDiarioFk);
OPEN vCursor;
l: LOOP
FETCH vCursor INTO vBase,
vVat,
vRate,
vMod347,
vTaxEqu,
vRateEqu,
vTransactionCode,
vTaxCode,
vIsIntracommunity,
vOperationCode;
IF vDone THEN
LEAVE l;
END IF;
SET vCounter = vCounter + 1;
CASE vCounter
WHEN 1 THEN
UPDATE movContaIVA
SET BaseIva1 = vBase,
PorIva1 = vRate,
CuotaIva1 = vVat,
PorRecargoEquivalencia1 = vTaxEqu,
RecargoEquivalencia1 = vRateEqu,
CodigoTransaccion1 = vTransactionCode,
CodigoIva1 = vTaxCode
WHERE id = vXDiarioFk;
WHEN 2 THEN
UPDATE movContaIVA
SET BaseIva2 = vBase,
PorIva2 = vRate,
CuotaIva2 = vVat,
PorRecargoEquivalencia2 = vTaxEqu,
RecargoEquivalencia2 =vRateEqu,
CodigoTransaccion2 = vTransactionCode,
CodigoIva2 = vTaxCode
WHERE id = vXDiarioFk;
WHEN 3 THEN
UPDATE movContaIVA
SET BaseIva3 = vBase,
PorIva3 = vRate,
CuotaIva3 = vVat,
PorRecargoEquivalencia3 = vTaxEqu,
RecargoEquivalencia3 = vRateEqu,
CodigoTransaccion3 = vTransactionCode,
CodigoIva3 = vTaxCode
WHERE id = vXDiarioFk;
WHEN 4 THEN
UPDATE movContaIVA
SET BaseIva4 = vBase,
PorIva4 = vRate,
CuotaIva4 = vVat,
PorRecargoEquivalencia4 = vTaxEqu,
RecargoEquivalencia4 = vRateEqu,
CodigoTransaccion4 = vTransactionCode,
CodigoIva4 = vTaxCode
WHERE id = vXDiarioFk;
END CASE;
UPDATE movContaIVA
SET Exclusion347 = NOT vMod347,
Intracomunitaria = vIsIntracommunity,
ClaveOperacionFactura = vOperationCode
WHERE id = vXDiarioFk;
END LOOP;
CLOSE vCursor;
UPDATE movContaIVA mci
JOIN vn.invoiceOut i ON i.id = vInvoiceOutFk
LEFT JOIN vn.invoiceCorrection ic ON ic.correctedFk = vInvoiceOutFk
LEFT JOIN vn.invoiceOut ioc ON ioc.id = ic.correctingFk
JOIN vn.XDiario x ON x.id = mci.id
JOIN vn.client c ON c.id = i.clientFk
JOIN Naciones n ON n.countryFk = c.countryFk
JOIN vn.invoiceOutSerial ios ON ios.code = i.serial
JOIN vn.taxArea ta ON ta.code = ios.taxAreaFk
SET mci.Año = YEAR(i.issued),
mci.Serie = i.serial,
mci.Factura = RIGHT(i.ref, LENGTH(i.ref) -1),
mci.FechaFactura = i.issued,
mci.ImporteFactura = i.amount,
mci.TipoFactura = vInvoiceTypeSended,
mci.CodigoCuentaFactura = x.SUBCTA,
mci.CifDni = c.fi,
mci.Nombre = SUBSTR(c.socialName, 1, vMaxLengthName),
mci.SiglaNacion = n.SiglaNacion,
mci.EjercicioFactura = YEAR(i.issued),
mci.FechaOperacion = i.issued,
mci.MantenerAsiento = TRUE,
mci.FechaFacturaOriginal = x.FECHA_EX
WHERE mci.id = vXDiarioFk;
SELECT correctedFk INTO vInvoiceOutCorrectedFk
FROM vn.invoiceCorrection
WHERE correctingFk = vInvoiceOutFk;
IF vInvoiceOutCorrectedFk THEN
UPDATE movContaIVA mci
JOIN vn.invoiceOut i ON i.id = vInvoiceOutCorrectedFk
JOIN vn.invoiceCorrection ic ON ic.correctedFk = vInvoiceOutCorrectedFk
JOIN (SELECT SUM(IF(IFNULL(e.vatFk, TRUE), iot.taxableBase, 0)) taxableBase,
SUM(IF(IFNULL(e.vatFk, TRUE), iot.vat, 0)) vat,
SUM(IF(IFNULL(e.vatFk, TRUE), 0, iot.vat)) equ
FROM vn.invoiceOutTax iot
LEFT JOIN vn.pgcEqu e ON e.vatFk = iot.pgcFk
WHERE iot.invoiceOutFk = vInvoiceOutCorrectedFk
) tax
JOIN ClavesOperacion co ON co.Descripcion = 'Factura rectificativa'
SET mci.TipoRectificativa = 2,
mci.ClaseAbonoRectificativas = 1,
mci.FechaFacturaOriginal = i.issued,
mci.FechaOperacion = i.issued,
mci.BaseImponibleOriginal = tax.taxableBase,
mci.CuotaIvaOriginal = tax.vat,
mci.RecargoEquivalenciaOriginal = tax.equ,
mci.ClaveOperacionFactura = co.ClaveOperacionFactura_
WHERE mci.id = vXDiarioFk
AND i.id = vInvoiceOutCorrectedFk;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceOut_manager` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_manager`(vYear INT, vCompanyFk INT)
BEGIN
/**
* Traslada la info de contabilidad relacionada con las facturas emitidas
*
* @vYear Año contable del que se quiere trasladar la información
* @vCompany Empresa de la que se quiere trasladar datos
*/
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vInvoiceFk INT;
DECLARE vXDiarioFk INT;
DECLARE vDatedFrom DATETIME;
DECLARE vDatedTo DATETIME;
DECLARE vCursor CURSOR FOR
SELECT i.id,
sub2.XDiarioFk
FROM vn.invoiceOut i
JOIN (SELECT MIN(x.id) XDiarioFk, x.ASIEN, sub.refFk
FROM vn.XDiario x
JOIN (SELECT x.ASIEN, CONCAT(x.SERIE, x.FACTURA) refFk
FROM vn.XDiario x
WHERE x.enlazadoSage = FALSE
AND x.FACTURA
AND x.empresa_id = vCompanyFk
AND x.FECHA BETWEEN vDatedFrom AND vDatedTo
GROUP BY refFk
) sub ON sub.ASIEN = x.ASIEN
GROUP BY refFk
)sub2 ON sub2.refFk = i.ref;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SELECT CAST(CONCAT(vYear, '-01-01') AS DATETIME), util.dayEnd(CAST(CONCAT(vYear, '-12-31') AS DATE))
INTO vDatedFrom, vDatedTo;
OPEN vCursor;
l: LOOP
FETCH vCursor INTO vInvoiceFk, vXDiarioFk;
IF vDone THEN
LEAVE l;
END IF;
CALL invoiceOut_add(vInvoiceFk, vXDiarioFk);
END LOOP;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `pgc_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `pgc_add`(vCompanyFk INT)
BEGIN
/**
* Añade cuentas del plan general contable para exportarlos a Sage
* @vCompanyFk Empresa de la que se quiere trasladar datos
*/
TRUNCATE TABLE planCuentasPGC;
INSERT INTO planCuentasPGC
(CodigoEmpresa,
CodigoCuenta,
Cuenta,
ClienteOProveedor)
SELECT *
FROM (SELECT company_getCode(vCompanyFk) companyFk,
e.id accountFk,
UCASE(e.name),
''
FROM vn.expense e
UNION
SELECT company_getCode(vCompanyFk),
a.account,
UCASE(a.bank),
''
FROM vn.accounting a
WHERE a.isActive
AND a.`account`
UNION
SELECT CodigoEmpresa,
CodigoCuenta,
Nombre,
ClienteOProveedor
FROM clientesProveedores)sub
GROUP BY companyFk, accountFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_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: `salix`
--
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `salix` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`property` varchar(512) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`accessType` set('READ','WRITE','*') DEFAULT 'READ',
`permission` set('DENY','ALLOW') DEFAULT 'ALLOW',
`principalType` set('ROLE','USER') DEFAULT 'ROLE',
`principalId` varchar(512) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `model_ix` (`model`(255)) COMMENT 'ernesto 3.8.2020. Mysql pide indices',
KEY `property_ix` (`property`(255)),
KEY `accessType_ix` (`accessType`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`ttl` int(11) DEFAULT NULL,
`scopes` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`created` datetime DEFAULT NULL,
`userId` int(11) DEFAULT NULL,
`outdated` datetime GENERATED ALWAYS AS (`created` + interval `ttl` second) STORED,
PRIMARY KEY (`id`),
KEY `outdated_Index` (`outdated`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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;
--
-- 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 `realm`,
1 AS `username`,
1 AS `password`,
1 AS `email`,
1 AS `emailVerified`,
1 AS `verificationToken` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `accessTokenConfig`
--
DROP TABLE IF EXISTS `accessTokenConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `accessTokenConfig` (
`id` int(10) unsigned NOT NULL,
`renewPeriod` int(10) unsigned DEFAULT NULL,
`courtesyTime` int(10) unsigned DEFAULT NULL,
`renewInterval` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `accessTokenConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `authCode`
--
DROP TABLE IF EXISTS `authCode`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `authCode` (
`userFk` int(10) unsigned NOT NULL,
`code` int(11) NOT NULL,
`expires` bigint(20) NOT NULL,
PRIMARY KEY (`userFk`),
UNIQUE KEY `authCode_unique` (`code`),
CONSTRAINT `authCode_user_id_fk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `defaultViewConfig`
--
DROP TABLE IF EXISTS `defaultViewConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `defaultViewConfig` (
`tableCode` varchar(25) NOT NULL,
`columns` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='The default configuration of columns for views';
/*!40101 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) DEFAULT NULL,
`property` varchar(255) DEFAULT NULL,
`actionType` set('insert','update','*') DEFAULT '*',
`role` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `module`
--
DROP TABLE IF EXISTS `module`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `module` (
`code` varchar(45) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `printConfig`
--
DROP TABLE IF EXISTS `printConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `printConfig` (
`id` int(10) unsigned NOT NULL,
`itRecipient` varchar(50) DEFAULT NULL COMMENT 'IT recipients for report mailing',
`incidencesEmail` varchar(50) DEFAULT NULL COMMENT 'CAU destinatary email',
PRIMARY KEY (`id`),
CONSTRAINT `printConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Print service config';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `url`
--
DROP TABLE IF EXISTS `url`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `url` (
`appName` varchar(100) NOT NULL,
`environment` varchar(100) NOT NULL,
`url` varchar(255) NOT NULL,
PRIMARY KEY (`appName`,`environment`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`configuration` text DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniqueUser_TableCode` (`userFk`,`tableCode`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping events for database 'salix'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `accessToken_prune` */;
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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `accessToken_prune` ON SCHEDULE EVERY 1 DAY STARTS '2023-03-14 05:14:00' ON COMPLETION PRESERVE ENABLE DO CALL salix.accessToken_prune */ ;;
/*!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 'salix'
--
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `accessToken_prune` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `accessToken_prune`()
BEGIN
/**
* Borra de la tabla salix.AccessToken todos aquellos tokens que hayan caducado
*/
DELETE FROM salix.AccessToken
WHERE outdated < 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 */ ;
--
-- Current Database: `srt`
--
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `srt` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */;
USE `srt`;
--
-- Table structure for table `antenna`
--
DROP TABLE IF EXISTS `antenna`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `antenna` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lector de codigos RFID en el sorter';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `buffer`
--
DROP TABLE IF EXISTS `buffer`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `buffer` (
`id` int(11) NOT NULL,
`x` int(11) DEFAULT NULL,
`y` int(11) DEFAULT NULL,
`size` int(11) DEFAULT NULL,
`length` int(11) DEFAULT NULL,
`stateFk` int(11) NOT NULL DEFAULT 1,
`typeFk` int(11) NOT NULL DEFAULT 0,
`isActive` tinyint(1) NOT NULL DEFAULT 1,
`code` varchar(3) DEFAULT NULL,
`stratus` int(11) NOT NULL COMMENT 'representa la altura del buffer',
`hasWorkerWaiting` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Indica si hay un paletizador',
`reserve` varchar(100) DEFAULT NULL,
`routeFk` int(11) DEFAULT NULL COMMENT 'ruta que va a descargar por ahi',
`dayMinute` int(11) DEFAULT NULL COMMENT 'camion que va a descargar',
`lastUnloaded` datetime DEFAULT NULL COMMENT 'hora de la última descarga',
`hasStrapper` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'tiene una flejadora acoplada',
`typeDefaultFk` int(11) NOT NULL DEFAULT 1 COMMENT 'estado por defecto',
`motors` int(11) NOT NULL DEFAULT 1 COMMENT 'número de fotocélulas que corresponden con sectores de motor independientes',
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`),
KEY `buffer_FK` (`stateFk`),
KEY `buffer_FK_1` (`typeFk`),
CONSTRAINT `buffer_FK` FOREIGN KEY (`stateFk`) REFERENCES `bufferState` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `buffer_FK_1` FOREIGN KEY (`typeFk`) REFERENCES `bufferType` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `bufferDayMinute`
--
DROP TABLE IF EXISTS `bufferDayMinute`;
/*!50001 DROP VIEW IF EXISTS `bufferDayMinute`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `bufferDayMinute` AS SELECT
1 AS `bufferFk`,
1 AS `expeditionFk`,
1 AS `dayMinute`,
1 AS `position`,
1 AS `ETD`,
1 AS `ticketFk`,
1 AS `routeFk`,
1 AS `zonaTicket`,
1 AS `expeditionState` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `bufferFreeLength`
--
DROP TABLE IF EXISTS `bufferFreeLength`;
/*!50001 DROP VIEW IF EXISTS `bufferFreeLength`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `bufferFreeLength` AS SELECT
1 AS `bufferFk`,
1 AS `bufferName`,
1 AS `freeLength`,
1 AS `saturacion`,
1 AS `state`,
1 AS `stateFk`,
1 AS `typeFk`,
1 AS `typeName`,
1 AS `stock`,
1 AS `RealFreeLength` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `bufferGroup`
--
DROP TABLE IF EXISTS `bufferGroup`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bufferGroup` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`bufferFk` int(11) NOT NULL,
`group` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `bufferGroup_UN` (`bufferFk`),
CONSTRAINT `bufferGroup_FK` FOREIGN KEY (`bufferFk`) REFERENCES `buffer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Agrupación de buffers que sirven de salida para las mismas rutas';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `bufferPool`
--
DROP TABLE IF EXISTS `bufferPool`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bufferPool` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`bufferFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `bufferPool_fk1_idx` (`bufferFk`),
CONSTRAINT `bufferPool_fk1` FOREIGN KEY (`bufferFk`) REFERENCES `buffer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='En esta tabla se almacen los buffers que se quieren utilizar como destino de las cajas que entran, para forzar el envio a los mismos.';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `bufferState`
--
DROP TABLE IF EXISTS `bufferState`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bufferState` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(20) NOT NULL,
`isAvailable` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `bufferStock`
--
DROP TABLE IF EXISTS `bufferStock`;
/*!50001 DROP VIEW IF EXISTS `bufferStock`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `bufferStock` AS SELECT
1 AS `expeditionFk`,
1 AS `bufferFk`,
1 AS `position`,
1 AS `dayMinute`,
1 AS `eta`,
1 AS `ticketFk`,
1 AS `routeFk`,
1 AS `zonaTicket`,
1 AS `truck`,
1 AS `expeditionState`,
1 AS `hasWorkerWaiting`,
1 AS `isActive`,
1 AS `bufferTruck`,
1 AS `typeName`,
1 AS `routeBuffer` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `bufferType`
--
DROP TABLE IF EXISTS `bufferType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bufferType` (
`id` int(11) NOT NULL,
`typeName` varchar(100) NOT NULL,
`isTarget` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'puede recibir cajas',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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` (
`readingPointDelay` int(11) NOT NULL DEFAULT 5 COMMENT 'tiempo de espera de la antena para considerar la lectura como una nueva ',
`boxGap` int(11) NOT NULL COMMENT 'separacion teorica entre cajas en el buffer',
`freeLength` int(11) NOT NULL DEFAULT 1200 COMMENT 'espacio minimo para declarar el buffer no full',
`isRandomMoving` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'el movimiento aleatorio esta activado',
`bufferNoLabels` int(11) NOT NULL DEFAULT 22 COMMENT 'buffer destino para cajas sin etiqueta',
`bufferTwoLabels` int(11) NOT NULL DEFAULT 24 COMMENT 'buffer destino para cajas con 2 etiquetas o más',
`bufferWidthMargin` int(11) NOT NULL DEFAULT 100 COMMENT 'margen mínimo para que una caja pueda entrar en un buffer',
`bufferDefault` int(11) NOT NULL DEFAULT 26 COMMENT 'buffer por defecto si no se encuentra otro',
`bufferLength` int(11) NOT NULL DEFAULT 13000 COMMENT 'Longitud de los buffers, en mm',
`id` int(10) unsigned NOT NULL,
`maxBoxesInBuffer` int(11) NOT NULL DEFAULT 8 COMMENT 'max numero de cajas por buffer para declararlo full',
`isEnteringBlocked` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'bloquea la entrada de nuevas cajas al sorter',
`isAuto` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'deja el sorter en auto por un buffer',
`minBoxesToUnloading` int(11) NOT NULL DEFAULT 9 COMMENT 'num de cajas mínimo para generar una descarga',
`minutesBeforeTruckDeparture` int(11) NOT NULL DEFAULT 60 COMMENT 'minutos a descontar de la hora de partida del camion para descargar el sorter',
`groupingMode` enum('TRUCK','ROUTE','BUFFER','BUFFERGROUP') NOT NULL DEFAULT 'TRUCK',
`expedition_setDimensions` int(11) NOT NULL,
`lengthSensorSpacing` int(11) NOT NULL DEFAULT 0 COMMENT 'Separación entre sensores en milimetros - largo',
`widthSensorSpacing` int(11) NOT NULL DEFAULT 0 COMMENT 'Separación entre sensores en milimetros - ancho',
`enteringSecondsReserve` int(11) NOT NULL DEFAULT 0,
`lengthToFirstSensor` int(11) NOT NULL COMMENT 'Distancia a sumar en milímetros hasta primer sensor',
`widthToFirstSensor` int(11) NOT NULL COMMENT 'Distancia a sumar en milímetros hasta primer sensor ',
`movingMaxLife` int(11) NOT NULL DEFAULT 30 COMMENT 'Tiempo máximo (en minutos) que puede estar un registro en la tabla srt.moving',
`motorsMargin` int(11) DEFAULT 3 COMMENT 'margen de motores para considerar FULL el buffer',
`isBalanced` tinyint(1) NOT NULL DEFAULT 1,
`testMode` tinyint(1) NOT NULL DEFAULT 0,
`isAllowedUnloading` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'Permite que se pueda cambiar el mode de los buffers a UNLOADING',
PRIMARY KEY (`id`),
CONSTRAINT `config_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `enteringLog`
--
DROP TABLE IF EXISTS `enteringLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `enteringLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`expeditionFk` int(11) DEFAULT NULL,
`expeditionOutFk` int(11) DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`weight` decimal(10,2) DEFAULT NULL COMMENT 'peso en kg',
`width` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'ancho en milímetros',
`length` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'largo en milímetros',
`height` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'alto en milímetros',
`bufferFk` int(11) DEFAULT NULL COMMENT 'buffer',
`position` int(11) DEFAULT NULL COMMENT 'posicion con respecto al celuveyor',
`stateFk` int(11) NOT NULL DEFAULT 0,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`updated` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `expedition_fk_idx` (`bufferFk`),
KEY `expedition_fk2_idx` (`stateFk`),
CONSTRAINT `expedition_FK` FOREIGN KEY (`stateFk`) REFERENCES `expeditionState` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `expedition_FK_1` FOREIGN KEY (`bufferFk`) REFERENCES `buffer` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='En esta tabla se almacenan los datos físicos y la posicion de cada caja en el sorter';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `expeditionLoading`
--
DROP TABLE IF EXISTS `expeditionLoading`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expeditionLoading` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`expeditionFk` int(11) NOT NULL,
`bufferFk` int(11) NOT NULL DEFAULT 24,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
UNIQUE KEY `expeditionLoading_UN` (`expeditionFk`),
KEY `expeditionLoading_FK` (`bufferFk`),
CONSTRAINT `expeditionLoading_FK` FOREIGN KEY (`bufferFk`) REFERENCES `buffer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `expeditionLoading_FK_1` FOREIGN KEY (`expeditionFk`) REFERENCES `expedition` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacena las expediciones que van a entrar al sorter por los buffers en modo loading';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `expeditionLog`
--
DROP TABLE IF EXISTS `expeditionLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expeditionLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`expeditionFk` int(11) DEFAULT NULL,
`bufferFk` int(11) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`action` varchar(3) NOT NULL,
`antennaFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `expeditionLog_FK_1` (`bufferFk`),
KEY `expeditionLog_FK_2` (`antennaFk`),
KEY `expeditionLog_action_IDX` (`action`) USING BTREE,
KEY `expeditionLog_expeditionFk_IDX` (`expeditionFk`) USING BTREE,
CONSTRAINT `expeditionLog_FK_1` FOREIGN KEY (`bufferFk`) REFERENCES `buffer` (`id`) ON UPDATE CASCADE,
CONSTRAINT `expeditionLog_FK_2` FOREIGN KEY (`antennaFk`) REFERENCES `antenna` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `expeditionState`
--
DROP TABLE IF EXISTS `expeditionState`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expeditionState` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(45) NOT NULL,
`isMovable` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'Estados que correponden a cajas paradas en el sorter',
`isInside` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `expeditionVolume`
--
DROP TABLE IF EXISTS `expeditionVolume`;
/*!50001 DROP VIEW IF EXISTS `expeditionVolume`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `expeditionVolume` AS SELECT
1 AS `dayMinute`,
1 AS `ETD`,
1 AS `cajas`,
1 AS `isReady`,
1 AS `truck`,
1 AS `zonaTicket`,
1 AS `bufferTruck` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `failureLog`
--
DROP TABLE IF EXISTS `failureLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `failureLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(100) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `lastRFID`
--
DROP TABLE IF EXISTS `lastRFID`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `lastRFID` (
`code` varchar(20) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`antennaFk` int(11) NOT NULL,
`isConsulted` tinyint(1) NOT NULL DEFAULT 0,
`isChoosed` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Es la lectura devuelta',
`id` int(11) NOT NULL AUTO_INCREMENT,
`antennaPort` int(11) DEFAULT NULL COMMENT 'puerto al que esta conectada la antena en el switch',
`peakRssi` int(11) DEFAULT NULL COMMENT 'intensidad media de lectura',
`seenCount` int(11) DEFAULT NULL COMMENT 'número de veces que se ha leido el mismo código',
PRIMARY KEY (`id`),
KEY `lastRFID_antennaFk_IDX` (`antennaFk`) USING BTREE,
CONSTRAINT `lastRFID_FK` FOREIGN KEY (`antennaFk`) REFERENCES `antenna` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='last codes read by the antennas';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `moving`
--
DROP TABLE IF EXISTS `moving`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `moving` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`expeditionFk` int(11) DEFAULT NULL,
`bufferFromFk` int(11) DEFAULT NULL,
`bufferToFk` int(11) DEFAULT NULL,
`stateFk` int(11) NOT NULL DEFAULT 1,
`isColliding` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Define si el movimiento colisiona con los que ya estan en marcha',
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
UNIQUE KEY `moving_UN` (`expeditionFk`),
KEY `moving_fk1_idx` (`expeditionFk`),
KEY `moving_fk2_idx` (`bufferFromFk`),
KEY `moving_fk3_idx` (`bufferToFk`),
KEY `moving_FK` (`stateFk`),
CONSTRAINT `moving_FK` FOREIGN KEY (`stateFk`) REFERENCES `movingState` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `moving_FK_1` FOREIGN KEY (`expeditionFk`) REFERENCES `expedition` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `moving_fk2` FOREIGN KEY (`bufferFromFk`) REFERENCES `buffer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `moving_fk3` FOREIGN KEY (`bufferToFk`) REFERENCES `buffer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `movingLast`
--
DROP TABLE IF EXISTS `movingLast`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `movingLast` (
`id` int(11) NOT NULL,
`expeditionFk` int(11) DEFAULT NULL,
`bufferFromFk` int(11) DEFAULT NULL,
`bufferToFk` int(11) DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `movingLog`
--
DROP TABLE IF EXISTS `movingLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `movingLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`expeditionFk` int(11) DEFAULT NULL,
`bufferFromFk` int(11) DEFAULT NULL,
`bufferToFk` int(11) DEFAULT NULL,
`stateFk` int(11) DEFAULT NULL,
`isColliding` tinyint(1) DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`movingFk` int(11) NOT NULL,
`action` varchar(25) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `movingState`
--
DROP TABLE IF EXISTS `movingState`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `movingState` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(20) NOT NULL,
`isInterfering` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'afecta al calculo de los posibles movimientos',
`isRedirectable` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'admite cambio de destino',
`isBeforeCelluveyor` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'define los estados que aún estan en el buffer origen',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `photocell`
--
DROP TABLE IF EXISTS `photocell`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `photocell` (
`bufferFk` int(11) NOT NULL,
`position` int(11) NOT NULL COMMENT 'Posición relativa al celluveyor de dentro a fuera, siendo 1 la más cercana a este',
`isActive` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`bufferFk`,`position`),
CONSTRAINT `photocell_FK` FOREIGN KEY (`bufferFk`) REFERENCES `buffer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `routePalletized`
--
DROP TABLE IF EXISTS `routePalletized`;
/*!50001 DROP VIEW IF EXISTS `routePalletized`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `routePalletized` AS SELECT
1 AS `routeFk`,
1 AS `expediciones`,
1 AS `paletizadas` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `routeVolume`
--
DROP TABLE IF EXISTS `routeVolume`;
/*!50001 DROP VIEW IF EXISTS `routeVolume`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `routeVolume` AS SELECT
1 AS `dayMinute`,
1 AS `ETD`,
1 AS `cajas`,
1 AS `isReady`,
1 AS `routeFk`,
1 AS `zonaTicket`,
1 AS `bufferTruck`,
1 AS `routeBuffer` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `sorterLog`
--
DROP TABLE IF EXISTS `sorterLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sorterLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`action` varchar(25) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `ticketPalletized`
--
DROP TABLE IF EXISTS `ticketPalletized`;
/*!50001 DROP VIEW IF EXISTS `ticketPalletized`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketPalletized` AS SELECT
1 AS `ticketFk`,
1 AS `routeFk`,
1 AS `expediciones`,
1 AS `paletizadas` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `upperStickers`
--
DROP TABLE IF EXISTS `upperStickers`;
/*!50001 DROP VIEW IF EXISTS `upperStickers`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `upperStickers` AS SELECT
1 AS `expeditionFk`,
1 AS `expedition`,
1 AS `ETD`,
1 AS `ticketFk`,
1 AS `routeFk`,
1 AS `zonaTicket`,
1 AS `truck`,
1 AS `worker`,
1 AS `labeler`,
1 AS `expeditionCounter`,
1 AS `m3`,
1 AS `clientFk` */;
SET character_set_client = @saved_cs_client;
--
-- Dumping events for database 'srt'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `moving_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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `moving_clean` ON SCHEDULE EVERY 5 MINUTE STARTS '2022-01-21 00:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Llama a srt.moving_clean para que elimine y notifique de registr' DO BEGIN
CALL srt.moving_clean();
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 */ ;;
DELIMITER ;
/*!50106 SET TIME_ZONE= @save_time_zone */ ;
--
-- Dumping routines for database 'srt'
--
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `bid` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `bid`(vCode VARCHAR(3)) RETURNS int(11)
DETERMINISTIC
BEGIN
/**
* Devuelve el identificador de vn.buffer a partir del código
*
* @param vCode código de vn.buffer
* @return Identificador de vn.buffer
*
*/
DECLARE vNumber INT;
DECLARE vLetter VARCHAR(1);
IF LENGTH(vCode) < 3 THEN
SET vCode = CONCAT('0',vCode);
END IF;
SELECT LEFT(vCode,2), RIGHT(vCode,1) INTO vNumber, vLetter;
IF vLetter = 'A' THEN
RETURN vNumber * 2;
ELSE
RETURN VNumber * 2 + 1;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `bufferPool_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `bufferPool_get`() RETURNS int(11)
READS SQL DATA
BEGIN
/**
* Devuelve el primer bufferFk de la tabla srt.bufferPool
*
* @return Identificador de vn.buffer
*
*/
DECLARE vBufferFk INT;
DECLARE vBufferPoolFk INT;
SELECT MIN(id) INTO vBufferPoolFk
FROM srt.bufferPool;
IF vBufferPoolFk THEN
SELECT bufferFk INTO vBufferFk
FROM srt.bufferPool
WHERE id = vBufferPoolFk;
DELETE
FROM srt.bufferPool
WHERE id = vBufferPoolFk;
ELSE
RETURN 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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `buffer_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `buffer_get`(vExpeditionFk INT) RETURNS int(11)
READS SQL DATA
BEGIN
/**
* Devuelve el buffer destino para una expedición
*
* @param vExpeditionFk Identificador de srt.expedition
* @return Identificador de srt.buffer
*/
DECLARE vBufferToFk INT;
DECLARE vBufferFromFk INT;
DECLARE vBufferGroup INT;
DECLARE vBufferStrapping INT;
SELECT IFNULL(rm.bufferFk, c.bufferDefault), IFNULL(e.bufferFk,0)
INTO vBufferToFk, vBufferFromFk
FROM srt.expedition e
LEFT JOIN vn.expedition e2 ON e2.id = e.id
LEFT JOIN vn.ticket t ON t.id = e2.ticketFk
LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk
JOIN srt.config c
WHERE e.id = vExpeditionFk;
SELECT `group` INTO vBufferGroup
FROM srt.bufferGroup
WHERE bufferFk = vBufferToFk;
SELECT bg.bufferFk
INTO vBufferStrapping
FROM srt.bufferGroup bg
JOIN srt.buffer b ON b.id = bg.bufferFk
JOIN srt.bufferType bt ON bt.id = b.typeFk
WHERE bt.typeName = 'STRAPPING'
AND bg.`group` = vBufferGroup
LIMIT 1;
IF vBufferGroup THEN
SELECT sub.bufferFk INTO vBufferToFk
FROM (
SELECT b.id bufferFk,
count(DISTINCT e.id) expeditions,
bs.description,
bt.typeName,
b.motors
FROM srt.buffer b
JOIN srt.bufferType bt ON bt.id = b.typeFk
JOIN srt.bufferState bs ON bs.id = b.stateFk
JOIN srt.bufferGroup bg ON bg.bufferFk = b.id
LEFT JOIN srt.expedition e ON e.bufferFk = b.id
LEFT JOIN srt.moving m ON m.bufferFromFk = b.id
WHERE bg.`group` = vBufferGroup
AND b.id != vBufferFromFk
AND bt.isTarget
AND m.id IS NULL
GROUP BY b.id) sub
JOIN srt.config c
ORDER BY (sub.description = 'FREE') DESC,
(sub.typeName = ('STRAPPING')) DESC,
IF(c.isBalanced , sub.expeditions, -sub.expeditions),
ABS(sub.bufferFk - vBufferStrapping)
LIMIT 1;
END IF;
RETURN vBufferToFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `buffer_getRandom` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `buffer_getRandom`() RETURNS int(11)
READS SQL DATA
BEGIN
/* Devuelve de forma aleatoria, uno de entre los buffers que tienen flejadora
*
*/
DECLARE vBufferFk INT;
SELECT b.id INTO vBufferFk
FROM srt.buffer b
WHERE b.hasStrapper
ORDER BY RAND()
LIMIT 1;
RETURN vBufferFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `buffer_getState` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `buffer_getState`(vSelf INT) RETURNS varchar(20) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
READS SQL DATA
BEGIN
/**
* Devuelve una cadena con el estado del buffer
*
*/
DECLARE vState VARCHAR(20);
SELECT bs.description INTO vState
FROM srt.buffer b
JOIN srt.bufferState bs ON bs.id = b.stateFk
WHERE b.id = vSelf;
RETURN 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `buffer_getType` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `buffer_getType`(vSelf INT) RETURNS varchar(20) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
READS SQL DATA
BEGIN
/**
* Devuelve una cadena con el tipo del buffer
*
*/
DECLARE vType VARCHAR(20);
SELECT bt.typeName INTO vType
FROM srt.buffer b
JOIN srt.bufferType bt ON bt.id = b.typeFk
WHERE b.id = vSelf;
RETURN vType;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `buffer_isFull` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `buffer_isFull`(vBufferFk INT) RETURNS tinyint(1)
READS SQL DATA
BEGIN
/**
* Comprueba si un buffer está lleno
*
* @param vBufferFk Identificador de vn.buffer
*
*/
DECLARE vBufferStock INT;
DECLARE vIsFull BOOL;
SELECT COUNT(*) INTO vBufferStock
FROM srt.expedition e
LEFT JOIN srt.moving m ON m.expeditionFk = e.id
WHERE e.bufferFk = vBufferFk
AND ISNULL(m.id);
SELECT vBufferStock + COUNT(*) INTO vBufferStock
FROM srt.moving m
WHERE m.bufferToFk = vBufferFk;
SELECT (vBufferStock >= maxBoxesInBuffer) INTO vIsFull
FROM srt.config;
RETURN vIsFull;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `dayMinute` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `dayMinute`(vDateTime DATETIME) RETURNS int(11)
READS SQL DATA
BEGIN
/*
* Devuelve el numero de minutos absoluto diario
*
* @vDateTime Fecha a analizar
*
*/
RETURN HOUR(vDateTime) * 60 + MINUTE(vDateTime);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `expedition_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `expedition_check`(vExpeditionFk INT) RETURNS int(11)
READS SQL DATA
BEGIN
/**
* Comprueba si existe una expedición, generando una aleatoria en caso contrario.
*
* @param vExpeditionFk Identificador de srt.expedition
*
*/
DECLARE vExpeditionOutFk INT;
DECLARE vIsOnTheCelluveyor BOOL;
SELECT id INTO vExpeditionOutFk
FROM srt.expedition
WHERE id = vExpeditionFk;
SELECT COUNT(*) INTO vIsOnTheCelluveyor
FROM srt.moving m
JOIN srt.movingState ms ON ms.id = m.stateFk
WHERE m.expeditionFk = vExpeditionFk
AND ms.description != 'NEW';
IF ISNULL(vExpeditionOutFk) OR vIsOnTheCelluveyor THEN
SELECT LEAST(-1,MIN(id)- 1) INTO vExpeditionOutFk
FROM srt.expedition;
CASE vExpeditionFk
WHEN 0 THEN -- Genera una EXP que termine en 0
SET vExpeditionOutFk = CEIL((vExpeditionOutFk - 10) / 10) * 10;
WHEN 2 THEN -- Genera una EXP que termine en 2
SET vExpeditionOutFk = -2 + CEIL((vExpeditionOutFk - 10) / 10) * 10;
ELSE -- Genera una EXP que termine en 9
SET vExpeditionOutFk = -9 + CEIL((vExpeditionOutFk - 10) / 10) * 10;
END CASE;
INSERT INTO srt.expedition(id,stateFk,width,`length`, height)
SELECT vExpeditionOutFk, es.id , p.width * 10, p.`depth` *10, p.height * 10
FROM srt.expeditionState es
JOIN vn.packaging p ON p.id = '94'
WHERE es.description = 'ENTERING';
END IF;
RETURN vExpeditionOutFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `expedition_getDayMinute` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `expedition_getDayMinute`(vExpeditionFk INT) RETURNS int(11)
READS SQL DATA
BEGIN
/**
* Devuelve el minuto absoluto ( un dia tiene 24 x 60 minutos ) de salida del camión
*
* @param vExpeditionFk Identificador de srt.expedition
*
* @return vDayMinute Minuto absoluto diario
*/
DECLARE vDayMinute INT;
SELECT HOUR(IFNULL(et.ETD, z.`hour`)) * 60 + MINUTE(IFNULL(et.ETD, z.`hour`)) INTO vDayMinute
FROM vn.expedition e
JOIN vn.ticket t ON e.ticketFk = t.id
JOIN vn.`zone` z ON z.id = t.zoneFk
LEFT JOIN vn.route r ON r.id = t.routeFk
LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk
LEFT JOIN vn.routesMonitor rm ON t.routeFk = rm.routeFk
LEFT JOIN vn.expeditionTruck et ON rm.expeditionTruckFk = et.id
WHERE e.id = vExpeditionFk;
RETURN vDayMinute;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buffer_getExpCount` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buffer_getExpCount`(IN vBufferFk INT, OUT vExpCount INT)
BEGIN
/* Devuelve el número de expediciones de un buffer
*
* @param vBufferFk Identificador de srt.buffer
* @param vExpCount Número de expediciones
*/
SELECT COUNT(*)
INTO vExpCount
FROM srt.expedition
WHERE bufferFk = vBufferFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buffer_getStateType` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buffer_getStateType`(vBufferFk INT, OUT vStateFk INT, OUT vTypeFk INT)
BEGIN
/**
* Devuelve el estado y el tipo de un buffer
*
* @param vBufferFk Identificador de srt.buffer
* @return vStateFk Identificador de srt.bufferState
* @return vTypeFk Identificador de srt.bufferType
*
*/
SELECT b.stateFk, b.typeFk INTO vStateFk, vTypeFk
FROM srt.buffer b
WHERE b.id = vBufferFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buffer_giveBack` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buffer_giveBack`(vSelf INT)
BEGIN
/* Devuelve una caja al celluveyor *
*
* @param vSelf Identificador de srt.buffer
*/
DECLARE vExpeditionFk INT;
SELECT e.id INTO vExpeditionFk
FROM srt.expedition e
WHERE e.bufferFk = vSelf
ORDER BY e.`position`
LIMIT 1;
IF vExpeditionFk THEN
CALL srt.expedition_relocate(vExpeditionFk, srt.buffer_get(vExpeditionFk));
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buffer_readPhotocell` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buffer_readPhotocell`(vSelf INT, vNumber INT)
BEGIN
/**
* Establece el estado de un buffer en función del número de fotocélulas activas
*
* @param vSelf Identificador de srt.buffer
* @param vNumber Número de fotocélulas activas
*/
DECLARE vIsFull BOOL;
DECLARE vBoxes INT;
DECLARE vMotors INT;
DECLARE vMargin INT;
SELECT ((COUNT(*) + vNumber + c.motorsMargin) >= b.motors AND b.motors > 1), COUNT(*), b.motors, c.motorsMargin
INTO vIsFull, vBoxes, vMotors, vMargin
FROM srt.buffer b
LEFT JOIN srt.moving m ON m.bufferToFk = b.id
JOIN srt.config c
WHERE b.id = vSelf;
IF vIsFull THEN
CALL srt.buffer_setStateType(vSelf, 'FULL', NULL);
ELSE
CALL srt.buffer_setStateType(vSelf, 'FREE', 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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buffer_setEmpty` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buffer_setEmpty`(vBufferFk INT)
BEGIN
/**
* Actualiza a NULL el valor bufferFk de las expediciones que esten en ese buffer
*
* @param vBufferFk Identificador de srt.buffer
*
*/
UPDATE srt.expedition e
SET e.bufferFk = NULL
WHERE e.bufferFk = vBufferFk;
UPDATE srt.buffer b
SET b.typeFk = b.typeDefaultFk
WHERE b.id = vBufferFk;
CALL srt.buffer_setStateType(vBufferFk, 'FREE', 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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buffer_setState` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buffer_setState`(vBufferFk INT(11), vStateFk INT(11))
BEGIN
/**
* Cambia el estado de un buffer
*
* @param vBufferFk Identificador de srt.buffer
* @param vStateFk Identificador de srt.bufferState
*
*/
UPDATE srt.buffer b
SET b.stateFk = vStateFk
WHERE b.id = vBufferFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buffer_setStateType` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buffer_setStateType`(vBufferFk INT, vState VARCHAR(25), vType VARCHAR(25))
BEGIN
/**
* Cambia el estado y el tipo de un buffer
*
* @param vBufferFk Identificador del buffer
* @param vState Estado
* @param vType Tipo
*
*/
DECLARE vBufferStateFk INT;
DECLARE vBufferTypeFk INT;
IF NOT ISNULL(vState) THEN
SELECT bs.id INTO vBufferStateFk
FROM srt.bufferState bs
WHERE bs.description = vState;
CALL srt.buffer_setState(vBufferFk, vBufferStateFk);
END IF;
IF NOT ISNULL(vType) THEN
IF vType = 'DEFAULT' THEN
SELECT b.typeDefaultFk INTO vBufferTypeFk
FROM srt.buffer b
WHERE b.id = vBufferFk;
ELSE
SELECT bt.id INTO vBufferTypeFk
FROM srt.bufferType bt
WHERE bt.typeName = vType;
END IF;
CALL srt.buffer_setType(vBufferFk, vBufferTypeFk);
IF vType = 'UNLOADING' THEN
UPDATE srt.buffer
SET lastUnloaded = util.VN_NOW()
WHERE id = vBufferFk;
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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buffer_setType` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buffer_setType`(vBufferFk INT(11), vTypeFk INT(11))
BEGIN
/**
* Cambia el tipo de un buffer, si está permitido
*
* @param vBufferFk Identificador de srt.buffer
* @param vTypeFk Identificador de srt.bufferType
*
*/
UPDATE srt.buffer b
JOIN srt.config c
JOIN srt.bufferType bt ON bt.typeName = 'UNLOADING'
SET b.typeFk = vTypeFk
WHERE b.id = vBufferFk
AND (vTypeFk <> bt.id OR c.isAllowedUnloading);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buffer_setTypeByName` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buffer_setTypeByName`(vBufferFk INT(11), vTypeName VARCHAR(100))
BEGIN
/**
* Cambia el tipo de un buffer
*
* @param vBufferFk Identificador de srt.buffer
* @param vTypeName Nombre Identificador de srt.bufferType
*
*/
DECLARE vTypeFk INT;
SELECT bt.id INTO vTypeFk
FROM srt.bufferType bt
WHERE bt.typeName = vTypeName;
UPDATE srt.buffer b
SET b.typeFk = vTypeFk
WHERE b.id = vBufferFk;
SELECT count(*)
FROM srt.buffer b
WHERE b.id = vBufferFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`()
BEGIN
DECLARE vLastDated DATE DEFAULT TIMESTAMPADD(WEEK,-2,util.VN_CURDATE());
DELETE FROM srt.lastRFID
WHERE created < vLastDated;
DELETE FROM srt.expedition
WHERE created < vLastDated;
DELETE FROM srt.moving;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expeditionLoading_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionLoading_add`(vExpeditionFk INT, vBufferFk INT)
BEGIN
DECLARE vMessage VARCHAR(50) DEFAULT '';
IF (SELECT COUNT(*) FROM srt.buffer WHERE id = vBufferFk) = 0 THEN
SET vMessage = 'Buffer incorrecto';
END IF;
IF (SELECT COUNT(*) FROM srt.expedition WHERE id = vExpeditionFk) = 0 THEN
SET vMessage = 'Expedición no existe';
END IF;
IF LENGTH(vMessage) = 0 THEN
REPLACE srt.expeditionLoading (expeditionFk, bufferFk)
VALUES (vExpeditionFk, vBufferFk);
SET vMessage = 'Registro añadido';
END IF;
SELECT 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_arrived` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_arrived`(vExpeditionFk INT, vBufferFk INT, OUT vTypeFk INT)
BEGIN
/**
* La expedición ha entrado en un buffer, superando fc2
*
* @param vExpeditionFk Identificador de srt.expedition
* @param vBufferFk Identificador de srt.buffer
*
* @return vTypeFk Identificador de srt.bufferType
*
*/
DECLARE vComingBoxes INT;
DECLARE vHasWorkerWaiting BOOL;
DECLARE vIsRandomMoving BOOL;
DECLARE vState VARCHAR(15);
DECLARE vType VARCHAR(15);
DECLARE visBufferWhithoutBoxesCount BOOL;
IF vBufferFk = 1 THEN
SET vBufferFk = 0;
END IF;
INSERT INTO srt.expeditionLog (expeditionFk, bufferFk, `action`)
VALUES(vExpeditionFk, vBufferFk, 'ARR');
SELECT COUNT(*) INTO vComingBoxes
FROM srt.moving m
WHERE m.bufferToFk = vBufferFk
AND m.expeditionFk != vExpeditionFk;
SELECT b.hasWorkerWaiting,
c.isRandomMoving ,
(bt.typeName = 'STRAPPING') OR vBufferFk IN (c.bufferNoLabels, c.bufferTwoLabels, c.bufferDefault)
INTO vHasWorkerWaiting,
vIsRandomMoving,
visBufferWhithoutBoxesCount
FROM srt.buffer b
JOIN srt.bufferType bt ON bt.id = b.typeFk
JOIN srt.config c
WHERE b.id = vBufferFk
LIMIT 1;
SET vState = IF(srt.buffer_isFull(vBufferFk), 'FULL', 'FREE');
SET vType = IF(vHasWorkerWaiting
AND NOT vComingBoxes
AND NOT vIsRandomMoving
AND vState = 'FULL', 'UNLOADING', 'ACCUMULATION');
IF NOT visBufferWhithoutBoxesCount THEN
CALL srt.buffer_setStateType(vBufferFk,vState,vType);
END IF;
UPDATE srt.expedition e
JOIN srt.expeditionState es ON es.description = 'STORED'
SET e.bufferFk = IF(visBufferWhithoutBoxesCount,0,vBufferFk),
e.`position` = 0,
e.stateFk = es.id
WHERE e.id = vExpeditionFk;
UPDATE srt.expedition e
SET e.`position` = e.`position` + 1
WHERE e.bufferFk = vBufferFk
AND e.bufferFk > 0;
INSERT INTO srt.movingLog(expeditionFk, bufferFromFk, bufferToFk, stateFk, isColliding, movingFk, `action`)
SELECT expeditionFk, bufferFromFk, bufferToFk, stateFk, isColliding, id, 'ARRIVED'
FROM srt.moving
WHERE expeditionFk = vExpeditionFk
ORDER BY id DESC
LIMIT 1;
DELETE FROM srt.moving
WHERE expeditionFk = vExpeditionFk;
SELECT bt.id INTO vTypeFk
FROM srt.bufferType bt
JOIN srt.buffer b ON b.typeFk = bt.id
WHERE b.id = vBufferFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_bufferOut` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_bufferOut`(vBufferToFk INT)
BEGIN
/**
* Selecciona y enruta las expediciones en el sorter hacia un buffer de salida, que sean de ese buffer
*
* @param vBufferToFk Identificador de srt.buffer
*/
DECLARE vExpListFk INT;
DECLARE vExpBufFk INT;
DECLARE vDone INT DEFAULT FALSE;
DECLARE vExpList CURSOR FOR
SELECT bs.expeditionFk
FROM srt.bufferStock bs
JOIN srt.expedition e ON e.id = bs.expeditionFk
LEFT JOIN srt.moving m ON m.expeditionFk = bs.expeditionFk
WHERE bs.routeBuffer = vBufferToFk
AND ISNULL(m.expeditionFk)
AND bs.typeName = 'ACCUMULATION'
ORDER BY (vBufferToFk - e.bufferFk),
e.`position` ;
DECLARE vExpBuf CURSOR FOR
SELECT e.id
FROM srt.expedition e
JOIN srt.expedition e2 ON e2.bufferFk = e.bufferFk
LEFT JOIN srt.moving m ON m.expeditionFk = e.id
WHERE e2.id = vExpListFk
AND ISNULL(m.expeditionFk)
AND e.`position` <= e2.`position`
ORDER BY e.`position`;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN vExpList;
FETCH vExpList INTO vExpListFk;
WHILE NOT vDone DO
OPEN vExpBuf;
FETCH vExpBuf INTO vExpBufFk;
WHILE NOT vDone DO
IF vExpBufFk = vExpListFk THEN
CALL srt.expedition_relocate(vExpListFk, vBufferToFk);
SET vDone = TRUE;
ELSE
CALL srt.expedition_relocate(vExpBufFk, NULL);
SET vDone = FALSE;
FETCH vExpBuf INTO vExpBufFk;
END IF;
END WHILE;
CLOSE vExpBuf;
SET vDone = FALSE;
FETCH vExpList INTO vExpListFk;
END WHILE;
CLOSE vExpList;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_entering` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_entering`(vExpeditionFk INT, OUT vExpeditionOutFk INT )
BEGIN
/**
* Una expedición llega a la entrada del celuveyor y comunica su ID
*
* @param vExpeditionFk Identificador de srt.expedition
*
* @return vExpeditionOutFk Identificador de srt.expedition
*
*/
DECLARE vBufferFk INT DEFAULT NULL;
SET vExpeditionOutFk = srt.expedition_check(vExpeditionFk);
IF vExpeditionOutFk < 0 THEN
SELECT IF(vExpeditionOutFk MOD 10 = 0, c.bufferNoLabels, c.bufferTwoLabels)
INTO vBufferFk
FROM srt.config c;
END IF;
UPDATE srt.expedition e
SET e.bufferFk = 0
WHERE id = vExpeditionOutFk;
UPDATE srt.moving m
JOIN srt.movingState ms ON ms.description = 'NEW'
SET m.stateFk = ms.id
WHERE m.expeditionFk = vExpeditionOutFk;
IF (SELECT isAuto FROM srt.config) THEN
SELECT b.id INTO vBufferFk
FROM srt.buffer b
JOIN srt.bufferType bt ON bt.id = b.typeFk
WHERE b.isActive
ORDER BY (bt.typeName = 'STRAPPING') DESC,
b.hasWorkerWaiting DESC,
srt.buffer_IsFull(b.id),
b.stateFk,
b.typeFk,
b.lastUnloaded,
b.id DESC
LIMIT 1;
END IF;
/*
INSERT INTO srt.expeditionLog (expeditionFk, bufferFk, `action`)
VALUES(vExpeditionOutFk, 0, 'ENT');
INSERT INTO srt.enteringLog(expeditionFk , expeditionOutFk )
VALUES(vExpeditionFk, vExpeditionOutFk);
*/
CALL srt.expedition_relocate(vExpeditionOutFk, vBufferFk);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_get`(vAntennaFk INT, OUT vExpeditionOutFk INT )
BEGIN
DECLARE vId INT;
DECLARE vCount INT;
DECLARE vCreatedMin DATETIME;
DECLARE vCreatedMax DATETIME;
DECLARE vSecondsScope INT DEFAULT 30;
START TRANSACTION;
SELECT count(DISTINCT lr.code) INTO vCount
FROM srt.lastRFID lr
WHERE lr.antennaFk = vAntennaFk
AND NOT isConsulted;
CASE vCount
WHEN 0 THEN
SET vExpeditionOutFk = srt.expedition_check(vCount);
WHEN 1 THEN
SELECT CAST(code AS DECIMAL(10,0)), lr.id
INTO vExpeditionOutFk, vId
FROM srt.lastRFID lr
WHERE lr.antennaFk = vAntennaFk
AND NOT isConsulted
ORDER BY lr.seenCount DESC, lr.peakRssi
LIMIT 1;
ELSE
-- Descartamos aquellas lecturas que se han producido unos segundos antes.
SELECT MIN(created), MAX(created) INTO vCreatedMin, vCreatedMax
FROM srt.lastRFID lr
WHERE lr.antennaFk = vAntennaFk
AND NOT isConsulted;
UPDATE srt.lastRFID lr
JOIN (SELECT id, code
FROM srt.lastRFID
WHERE created
BETWEEN TIMESTAMPADD(SECOND, - vSecondsScope, vCreatedMin)
AND TIMESTAMPADD(SECOND, -1, vCreatedMin)
AND isChoosed = 1#
) sub ON sub.code = lr.code AND sub.id != lr.id
SET lr.isConsulted = TRUE
WHERE lr.created BETWEEN vCreatedMin AND vCreatedMax
AND lr.antennaFk = vAntennaFk;
SELECT CAST(code AS DECIMAL(10,0)), lr.id
INTO vExpeditionOutFk, vId
FROM srt.lastRFID lr
WHERE lr.antennaFk = vAntennaFk
AND NOT isConsulted
ORDER BY lr.peakRssi DESC, lr.seenCount DESC #
LIMIT 1;
END CASE;
UPDATE srt.lastRFID
SET isChoosed = TRUE
WHERE id = vId;
UPDATE srt.lastRFID
SET isConsulted = TRUE
WHERE antennaFk = vAntennaFk
AND NOT isConsulted;
COMMIT;
INSERT INTO srt.expeditionLog (expeditionFk, bufferFk, `action`, antennaFk) VALUES(vExpeditionOutFk, 0, 'DIM', vAntennaFk);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_groupOut` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_groupOut`(vDayMinute INT, vBufferToFk INT)
BEGIN
/**
* Selecciona y enruta las expediciones en el sorter hacia un buffer de salida, que sean de la hora pedida
*
* @param vDayMinute Minuto absoluto del dia
* @param vBufferToFk Identificador de srt.buffer
*
*/
DECLARE vExpListFk INT;
DECLARE vExpBufFk INT;
DECLARE vDone INT DEFAULT FALSE;
DECLARE vExpList CURSOR FOR
SELECT bs.expeditionFk
FROM srt.bufferStock bs
JOIN srt.expedition e ON e.id = bs.expeditionFk
WHERE bs.dayMinute = vDayMinute
AND bs.expeditionState = 'STORED'
AND bs.isActive
AND bs.hasWorkerWaiting = FALSE
AND bs.typeName = 'ACCUMULATION'
ORDER BY (vBufferToFk - e.bufferFk),
e.`position`;
DECLARE vExpBuf CURSOR FOR
SELECT e.id
FROM srt.expedition e
JOIN srt.expedition e2 ON e2.bufferFk = e.bufferFk
JOIN srt.expeditionState es ON es.id = e.stateFk
WHERE e2.id = vExpListFk
AND e.`position` <= e2.`position`
AND es.description = 'STORED'
ORDER BY e.`position`;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN vExpList;
FETCH vExpList INTO vExpListFk;
UPDATE srt.moving m
JOIN srt.movingState ms ON ms.id = m.stateFk
SET m.bufferToFk = vBufferToFk
WHERE m.expeditionFk = vExpListFk
AND ms.isRedirectable
AND m.bufferFromFk != vBufferToFk;
WHILE NOT vDone DO
OPEN vExpBuf;
FETCH vExpBuf INTO vExpBufFk;
WHILE NOT vDone DO
IF vExpBufFk = vExpListFk THEN
CALL srt.expedition_Relocate(vExpListFk, vBufferToFk);
SET vDone = TRUE;
ELSE
CALL srt.expedition_Relocate(vExpBufFk, NULL);
SET vDone = FALSE;
FETCH vExpBuf INTO vExpBufFk;
END IF;
END WHILE;
CLOSE vExpBuf;
SET vDone = FALSE;
FETCH vExpList INTO vExpListFk;
END WHILE;
CLOSE vExpList;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_in` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_in`(vBufferFk INT, OUT vExpeditionFk INT)
proc:BEGIN
/**
* Ha entrado una caja en un buffer, por la zona de descarga.
*
* @param vBufferFk Identificador de srt.buffer
*
* @return vExpeditionFk Identificador de srt.expedition *
*/
DECLARE vMaxPosition INT;
DECLARE vIsBufferFull BOOL;
DECLARE vBufferTypeFk INT;
DECLARE vBufferStateFk INT;
SELECT el.expeditionFk INTO vExpeditionFk
FROM srt.expeditionLoading el
WHERE el.bufferFk = vBufferFk
ORDER BY id
LIMIT 1;
IF vExpeditionFk THEN
DELETE FROM srt.expeditionLoading
WHERE expeditionFk = vExpeditionFk;
-- SET vExpeditionFk = srt.expedition_check(vExpeditionFk);
INSERT INTO srt.expeditionLog (expeditionFk, bufferFk, `action`)
VALUES(vExpeditionFk, vBufferFk, 'IN');
SELECT MAX(e.position) INTO vMaxPosition
FROM srt.expedition e
WHERE e.bufferFk = vBufferFk;
UPDATE srt.expedition e
JOIN srt.expeditionState es ON es.description = 'STORED'
SET e.bufferFk = vBufferFk,
e.`position` = IFNULL(vMaxPosition,0) + 1,
e.stateFk = es.id
WHERE e.id = vExpeditionFk;
SELECT bfl.freeLength < c.freeLength * 2 INTO vIsBufferFull
FROM srt.bufferFreeLength bfl
JOIN srt.config c
WHERE bfl.bufferFk = vBufferFk;
IF vIsBufferFull THEN
CALL srt.buffer_setStateType(vBufferFk, 'FREE','ACCUMULATION');
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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_moving` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_moving`(vBufferFk INT)
BEGIN
/**
* Una expedición ha entrado en el celuveyor desde un buffer
*
* @param vBufferFk Identificador de srt.buffer
*
*/
DECLARE vExpeditionFk INT;
DECLARE vPosition INT;
SELECT min(`position`) INTO vPosition
FROM srt.expedition e
WHERE e.bufferFk = vBufferFk;
SELECT e.id INTO vExpeditionFk
FROM srt.expedition e
WHERE e.`position` = vPosition
AND e.bufferFk = vBufferFk
LIMIT 1;
INSERT INTO srt.expeditionLog (expeditionFk, bufferFk, `action`)
VALUES(vExpeditionFk, vBufferFk, 'MOV');
UPDATE srt.expedition e
JOIN srt.expeditionState es on es.description = 'MOVING'
JOIN srt.moving m ON m.expeditionFk = e.id
SET e.stateFk = es.id,
e.bufferFk = m.bufferToFk,
e.`position` = 0
WHERE e.id = vExpeditionFk;
SET @posicion := 0;
UPDATE srt.expedition e
SET e.`position` = @posicion := @posicion + 1
WHERE e.bufferFk = vBufferFk
AND e.id != vExpeditionFk
ORDER BY e.`position`;
CALL srt.buffer_setStateType(vBufferFk, 'FREE', 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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_out` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_out`(vBufferFk INT, OUT vTypeFk INT)
proc:BEGIN
/**
* Una expedición ha salido de un buffer por el extremo distal
* Se ignorará en caso de que el buffer esté en modo ACCUMULATION
*
* @param vBufferFk Identificador de srt.buffer
*
* @return vTypeFk Identificador de srt.bufferType
*/
DECLARE vMaxPosition INT;
DECLARE vIsFree BOOL;
DECLARE vExpeditionFk INT;
DECLARE vBufferType VARCHAR(15);
SELECT bt.typeName
INTO vBufferType
FROM srt.buffer b
JOIN srt.bufferType bt ON bt.id = b.typeFk
WHERE b.id = vBufferFk;
IF vBufferType = 'ACCUMULATION' THEN
LEAVE proc;
END IF;
SELECT MAX(e.`position`) INTO vMaxPosition
FROM srt.expedition e
WHERE e.bufferFk = vBufferFk;
SELECT e.id INTO vExpeditionFk
FROM srt.expedition e
WHERE e.`position` = vMaxPosition
AND e.bufferFk = vBufferFk
LIMIT 1;
INSERT INTO srt.expeditionLog (expeditionFk, bufferFk, `action`)
VALUES(vExpeditionFk, vBufferFk, 'OUT');
UPDATE srt.expedition e
JOIN srt.expeditionState es ON es.description = 'OUT'
SET e.bufferFk = NULL,
e.`position` = NULL,
e.stateFk = es.id
WHERE e.id = vExpeditionFk;
SELECT (COUNT(*) = 0) INTO vIsFree
FROM srt.expedition e
JOIN srt.buffer b ON b.id = e.bufferFk
WHERE e.bufferFk = vBufferFk
AND e.`position` > 0;
IF vIsFree AND vBufferType NOT IN('LOADING','STRAPPING') THEN
UPDATE srt.buffer SET reserve = NULL, routeFk = NULL, dayMinute = NULL
WHERE id = vBufferFk;
CALL srt.buffer_setStateType(vBufferFk,'FREE','DEFAULT');
END IF;
SELECT b.typeFk INTO vTypeFk
FROM srt.buffer b
WHERE b.id = vBufferFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_outAll` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_outAll`(vBufferFk INT)
BEGIN
/**
* Envia todas las expediciones al mismo buffer
*
* @param vBufferFk Identificador de vn.buffer
*
*/
INSERT INTO srt.moving (expeditionFk, bufferFromFk, bufferToFk)
SELECT e.id, e.bufferFk, vBufferFk
FROM srt.expedition e
LEFT JOIN srt.moving m ON m.expeditionFk = e.id
WHERE e.bufferFk > 0
AND e.bufferFk != vBufferFk
AND ISNULL(m.expeditionFk);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_relocate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_relocate`(vExpeditionFk INT, vBufferToFk INT)
proc:BEGIN
/**
* Asigna buffer destino nuevo para una expedición
*
* @param vExpeditionFk Identificacion de srt.expedition
*
* @param vBufferToFk Identificador de srt.buffer
*
*/
DECLARE vBufferFromFk INT;
START TRANSACTION;
IF (SELECT COUNT(*) FROM srt.moving WHERE expeditionFk = vExpeditionFk) THEN
LEAVE proc;
END IF;
SELECT e.bufferFk INTO vBufferFromFk
FROM srt.expedition e
WHERE e.id = vExpeditionFk;
SET vBufferToFk = IFNULL(vBufferToFk, IFNULL(srt.bufferPool_get(), `srt`.`buffer_get`(vExpeditionFk)));
IF vBufferFromFk = vBufferToFk THEN
LEAVE proc;
END IF;
REPLACE srt.moving (expeditionFk,
bufferFromFk,
bufferToFk,
stateFk)
SELECT e.id,
e.bufferFk,
vBufferToFk,
ms.id
FROM srt.expedition e
JOIN srt.movingState ms ON ms.description = 'NEW'
LEFT JOIN srt.moving m ON m.expeditionFk
WHERE e.id = vExpeditionFk;
UPDATE srt.expedition e
JOIN srt.expeditionState es on es.description = 'ENTERING'
JOIN srt.moving m ON m.expeditionFk = e.id
SET e.stateFk = es.id
WHERE e.id = vExpeditionFk;
COMMIT;
IF srt.buffer_isFull(vBufferToFk) THEN
CALL srt.buffer_setStateType(vBufferToFk,'FULL', 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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_reset` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_reset`()
BEGIN
DELETE FROM srt.moving;
DELETE FROM srt.expedition;
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(3223666, NULL, 280.00, 900.00, 280.00, NULL, NULL, 1, '2021-08-25 11:32:16.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4634827, NULL, 320.01, 1008.00, 330.00, 10, 54, 5, '2021-07-15 10:28:21.0', '2021-08-27 14:16:32.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4634836, NULL, 310.01, 1110.00, 300.00, 2, 3, 5, '2021-07-15 10:31:45.0', '2021-08-27 12:07:46.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4634840, NULL, 300.01, 1000.00, 230.00, 13, 2, 5, '2021-07-15 10:32:13.0', '2021-08-27 13:03:48.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4634871, NULL, 320.01, 1080.00, 330.00, 2, 4, 5, '2021-07-15 10:36:30.0', '2021-08-27 12:07:46.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4634872, NULL, 300.00, 900.00, 250.00, 5, 1, 5, '2021-07-15 10:36:49.0', '2021-08-27 12:29:57.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4637714, NULL, 260.01, 520.00, 210.00, NULL, NULL, 1, '2021-07-16 09:43:46.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4637715, NULL, 260.01, 520.00, 210.00, NULL, NULL, 1, '2021-07-16 09:43:51.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4637716, NULL, 260.01, 520.00, 210.00, 9, 1, 4, '2021-07-16 09:43:55.0', '2021-08-27 12:08:33.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651292, NULL, 250.01, 1010.00, 150.00, NULL, NULL, 1, '2021-07-22 09:00:56.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651293, NULL, 300.01, 980.00, 160.00, 0, 1, 5, '2021-07-22 09:03:44.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651295, NULL, 490.01, 1180.00, 250.00, 0, 1, 5, '2021-07-22 09:07:08.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651298, NULL, 260.01, 1040.00, 240.00, 0, 1, 5, '2021-07-22 09:15:57.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651300, NULL, 490.01, 1180.00, 250.00, 0, 1, 5, '2021-07-22 09:17:06.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651302, NULL, 490.01, 1180.00, 250.00, NULL, NULL, 1, '2021-07-22 09:18:04.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651303, NULL, 370.01, 840.00, 180.00, 0, 1, 5, '2021-07-22 09:19:45.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651304, NULL, 260.01, 1040.00, 260.00, 0, 1, 5, '2021-07-22 09:21:07.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651305, NULL, 260.01, 1040.00, 260.00, 2, 7, 5, '2021-07-22 09:23:26.0', '2021-08-27 12:07:46.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651306, NULL, 260.01, 1040.00, 260.00, NULL, NULL, 6, '2021-07-22 09:23:26.0', '2021-08-27 10:01:00.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651307, NULL, 490.01, 1180.00, 250.00, 26, 30, 5, '2021-07-22 09:24:57.0', '2021-08-27 14:08:37.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651308, NULL, 330.01, 1000.00, 170.00, 0, 1, 5, '2021-07-22 09:27:08.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651309, NULL, 290.01, 940.00, 230.00, NULL, NULL, 1, '2021-07-22 09:29:12.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651310, NULL, 290.01, 940.00, 230.00, 10, 1, 5, '2021-07-22 09:30:55.0', '2021-08-27 14:16:32.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651311, NULL, 290.01, 940.00, 230.00, 0, 1, 5, '2021-07-22 09:30:55.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651313, NULL, 490.01, 1180.00, 250.00, NULL, NULL, 6, '2021-07-22 09:32:43.0', '2021-08-27 10:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651314, NULL, 300.00, 900.00, 150.00, 13, 3, 5, '2021-07-22 09:34:20.0', '2021-08-27 13:03:48.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651317, NULL, 330.01, 960.00, 300.00, 0, 1, 5, '2021-07-22 09:35:38.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651321, NULL, 490.01, 1180.00, 250.00, 0, 1, 5, '2021-07-22 09:38:58.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651326, NULL, 260.01, 1040.00, 240.00, 0, 1, 5, '2021-07-22 09:41:42.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651327, NULL, 330.01, 960.00, 300.00, 0, 1, 5, '2021-07-22 09:42:51.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651329, NULL, 300.00, 900.00, 150.00, NULL, NULL, 6, '2021-07-22 09:43:54.0', '2021-08-27 10:01:00.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651333, NULL, 300.01, 1000.00, 230.00, 16, 1, 5, '2021-07-22 09:45:50.0', '2021-08-27 14:16:34.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651335, NULL, 300.01, 1000.00, 230.00, NULL, NULL, 6, '2021-07-22 09:47:25.0', '2021-08-27 10:01:00.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651337, NULL, 330.01, 960.00, 300.00, NULL, NULL, 6, '2021-07-22 09:48:15.0', '2021-08-27 10:01:00.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651342, NULL, 490.01, 1180.00, 250.00, NULL, NULL, 6, '2021-07-22 09:50:56.0', '2021-08-27 10:11:00.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651343, NULL, 490.01, 1180.00, 260.00, 26, 31, 5, '2021-07-22 09:52:18.0', '2021-08-27 14:08:37.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651356, NULL, 290.01, 940.00, 230.00, NULL, NULL, 6, '2021-07-22 09:54:35.0', '2021-08-27 10:01:00.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4651357, NULL, 300.00, 900.00, 150.00, 0, 1, 5, '2021-07-22 09:54:40.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4682051, NULL, 490.00, 1180.00, 260.00, 0, 1, 5, '2021-08-16 08:58:17.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4682052, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-16 08:58:17.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4682262, NULL, 490.00, 1180.00, 260.00, 0, 1, 5, '2021-08-16 08:58:17.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4691609, NULL, 280.00, 900.00, 280.00, 17, 1, 5, '2021-08-10 09:43:05.0', '2021-08-27 14:16:27.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4691611, NULL, 280.00, 600.00, 700.00, NULL, NULL, 1, '2021-08-10 09:53:22.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4691612, NULL, 280.00, 500.00, 430.00, 6, 1, 4, '2021-08-10 09:56:31.0', '2021-08-27 14:16:33.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4691617, NULL, 280.00, 600.00, 700.00, NULL, NULL, 6, '2021-08-10 09:59:39.0', '2021-08-27 10:36:36.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4691618, NULL, 330.00, 590.00, 650.00, 18, 1, 5, '2021-08-10 10:02:48.0', '2021-08-27 12:22:15.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4691892, NULL, 280.00, 600.00, 800.00, NULL, NULL, 1, '2021-08-10 11:52:12.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4691895, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-10 11:52:56.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4691974, NULL, 330.00, 590.00, 1200.00, NULL, NULL, 1, '2021-08-10 12:18:20.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4691990, NULL, 330.00, 590.00, 1200.00, NULL, NULL, 1, '2021-08-10 12:23:34.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4701752, NULL, 490.00, 1180.00, 260.00, 27, 43, 5, '2021-08-16 07:55:04.0', '2021-08-27 14:08:31.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4701753, NULL, 490.00, 1180.00, 260.00, 27, 44, 5, '2021-08-16 08:15:21.0', '2021-08-27 14:08:31.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4701754, NULL, 490.00, 1180.00, 260.00, 27, 42, 5, '2021-08-16 08:18:48.0', '2021-08-27 14:08:31.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4701755, NULL, 490.00, 1180.00, 260.00, 27, 46, 5, '2021-08-16 08:18:52.0', '2021-08-27 14:08:31.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4701756, NULL, 490.00, 1180.00, 260.00, 0, 1, 5, '2021-08-16 08:26:38.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4701757, NULL, 490.00, 1180.00, 260.00, 31, 1, 4, '2021-08-16 08:29:07.0', '2021-08-27 14:16:11.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4701758, NULL, 490.00, 1180.00, 260.00, 0, 1, 5, '2021-08-16 08:41:56.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4701759, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 6, '2021-08-16 08:45:52.0', '2021-08-27 09:28:11.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4701760, NULL, 490.00, 1180.00, 260.00, 27, 45, 5, '2021-08-16 08:45:54.0', '2021-08-27 14:08:31.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4701761, NULL, 490.00, 1180.00, 260.00, 28, 44, 5, '2021-08-16 08:45:54.0', '2021-08-27 14:16:27.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4701762, NULL, 490.00, 1180.00, 260.00, 0, 1, 5, '2021-08-16 08:55:14.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4701763, NULL, 490.00, 1180.00, 260.00, 26, 27, 5, '2021-08-16 08:58:17.0', '2021-08-27 14:08:37.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4701764, NULL, 490.00, 1180.00, 260.00, 26, 26, 5, '2021-08-16 09:04:36.0', '2021-08-27 14:08:37.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4701765, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 6, '2021-08-16 09:06:22.0', '2021-08-27 12:44:44.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4704297, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-16 16:52:11.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4704312, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-16 16:55:02.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4704345, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-16 17:00:36.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4708347, NULL, 300.00, 900.00, 150.00, NULL, NULL, 1, '2021-08-18 11:38:42.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4710866, NULL, 280.00, 600.00, 900.00, 0, 1, 5, '2021-08-19 07:40:52.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4710867, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 07:44:27.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4710868, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 07:45:47.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4710869, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 07:48:06.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4710870, NULL, 280.00, 600.00, 900.00, 0, 1, 5, '2021-08-19 07:50:36.0', '2021-08-27 13:08:45.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4710871, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 07:53:33.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4710872, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 07:56:13.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4710873, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 07:58:42.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4710874, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 08:00:10.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4710875, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 08:02:33.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4710876, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 08:05:59.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4710877, NULL, 280.00, 600.00, 900.00, NULL, NULL, 1, '2021-08-19 08:08:27.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4724421, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-25 11:33:31.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4724454, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-25 11:37:58.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4724463, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-25 11:39:45.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4724474, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-25 11:42:08.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4724484, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-25 11:43:21.0', '2021-08-27 08:41:01.0');
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4730464, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-27 09:57:17.0', NULL);
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4730467, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-27 10:04:06.0', NULL);
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4730472, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-27 10:27:15.0', NULL);
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4730473, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-27 10:27:27.0', NULL);
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4730474, NULL, 490.00, 1180.00, 260.00, NULL, NULL, 1, '2021-08-27 10:30:13.0', NULL);
INSERT INTO srt.expedition
(id, weight, width, `length`, height, bufferFk, `position`, stateFk, created, updated)
VALUES(4730476, NULL, 490.00, 1180.00, 260.00, 23, 1, 5, '2021-08-27 10:35:28.0', '2021-08-27 14:16:09.0');
UPDATE srt.expedition e
JOIN srt.expeditionState es ON es.description = 'PRINTED'
SET e.stateFk = es.id,
e.weight = NULL,
e.bufferFk = NULL,
e.`position` = NULL;
UPDATE srt.buffer b
JOIN srt.bufferState bs on bs.id = b.stateFk
SET stateFk = bs.id
WHERE bs.description = 'FREE';
UPDATE srt.config
SET isRandomMoving = FALSE;
SET @dm := (24 * 60) - 10;
UPDATE vn.expeditionTruck et
SET et.eta = timestampadd(MINUTE ,@dm := 1 + @dm,util.VN_CURDATE())
WHERE description LIKE 'PRU%' ;
DELETE FROM srt.movingLog ;
DELETE FROM srt.expeditionLog WHERE created < timestampadd(week,-1,util.VN_CURDATE());
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_routeOut` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_routeOut`(vRouteFk INT, vBufferToFk INT)
BEGIN
/**
* Selecciona y enruta las expediciones en el sorter hacia un buffer de salida, que sean de la ruta pedida
*
* @param vRouteFk Identificador de vn.route
* @param vBufferToFk Identificador de srt.buffer
*
*/
DECLARE vExpListFk INT;
DECLARE vExpBufFk INT;
DECLARE vDone INT DEFAULT FALSE;
DECLARE vExpList CURSOR FOR
SELECT bs.expeditionFk
FROM srt.bufferStock bs
JOIN srt.expedition e ON e.id = bs.expeditionFk
WHERE bs.routeFk = vRouteFk
AND bs.expeditionState = 'STORED'
AND bs.isActive
AND bs.hasWorkerWaiting = FALSE
ORDER BY (vBufferToFk - e.bufferFk),
e.`position` ;
DECLARE vExpBuf CURSOR FOR
SELECT e.id
FROM srt.expedition e
JOIN srt.expedition e2 ON e2.bufferFk = e.bufferFk
JOIN srt.expeditionState es ON es.id = e.stateFk
WHERE e2.id = vExpListFk
AND e.`position` <= e2.`position`
AND es.description = 'STORED'
ORDER BY e.`position`;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN vExpList;
FETCH vExpList INTO vExpListFk;
WHILE NOT vDone DO
OPEN vExpBuf;
FETCH vExpBuf INTO vExpBufFk;
WHILE NOT vDone DO
IF vExpBufFk = vExpListFk THEN
CALL srt.expedition_relocate(vExpListFk, vBufferToFk);
SET vDone = TRUE;
ELSE
CALL srt.expedition_relocate(vExpBufFk, NULL);
SET vDone = FALSE;
FETCH vExpBuf INTO vExpBufFk;
END IF;
END WHILE;
CLOSE vExpBuf;
SET vDone = FALSE;
FETCH vExpList INTO vExpListFk;
END WHILE;
CLOSE vExpList;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_scan` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_scan`(vSelf INT)
BEGIN
/* Actualiza el estado de una expedicion a OUT, al ser escaneada manualmente
*
* @param vSelf Identificador de srt.expedition
*
*/
UPDATE srt.expedition e
JOIN srt.expeditionState es ON es.description = 'OUT'
SET e.stateFk = es.id,
e.`position` = NULL,
e.bufferFk = NULL
WHERE e.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_setDimensions` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_setDimensions`(
vExpeditionFk INT,
vWeight DECIMAL(10,2),
vLength INT,
vWidth INT,
vHeight INT,
OUT vExpeditionOutFk INT)
BEGIN
/**
* Actualiza las dimensiones, peso y estado de una expedición
*
* @param vExpeditionFk Identificador de expedition
* @param vWeight Peso en kilos
* @param vLength Byte con el número de fotocélulas activadas a lo largo
* @param vWidth Byte con el número de fotocélulas activadas a lo ancho
* @param vHeight Altura de la caja en cm
* @return vExpeditionOutFk Identificador de expedition
*/
DECLARE vWidthSensorsUsed INT;
DECLARE vLengthSensorsUsed INT;
SET vExpeditionOutFk = expedition_check(vExpeditionFk);
#primer bit a 1 a la izquierda - primer bit a 1 a la derecha
SET vWidthSensorsUsed = length(BIN(vWidth)) - LOG2(vWidth & -vWidth);
SET vLengthSensorsUsed = length(BIN(vLength)) - LOG2(vLength & -vLength);
UPDATE expedition e
JOIN expeditionState es ON es.`description` = 'WEIGHED'
JOIN config c
SET weight = IFNULL(vWeight, 0),
stateFk = es.id,
width = IFNULL(c.widthToFirstSensor + (c.widthSensorSpacing * vWidthSensorsUsed), 0),
`length` = IFNULL(c.lengthToFirstSensor + (c.lengthSensorSpacing * vLengthSensorsUsed), 0),
height = IFNULL(vHeight * 10, 0)
WHERE e.id = vExpeditionOutFk;
SET vExpeditionOutFk = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_weighing` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_weighing`(vWeight DECIMAL(10,2), vExpeditionFk INT, OUT vExpeditionOutFk INT )
BEGIN
/**
* Actualiza el peso de una expedición
*
* @param vWeight Peso en kilos
* @param vExpeditionFk Identificador de srt.expedition
*
* @return vExpeditionOutFk Identificador de srt.expedition
*/
SET vExpeditionOutFk = srt.expedition_check(vExpeditionFk);
UPDATE srt.expedition e
JOIN srt.expeditionState es on es.description = 'WEIGHED'
SET weight = vWeight,
stateFk = es.id
WHERE e.id = vExpeditionOutFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `failureLog_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `failureLog_add`(vDescription VARCHAR(100))
BEGIN
/* Añade un registro a srt.failureLog
*
* @param vDescription descripción del fallo
*/
INSERT INTO srt.failureLog(description) VALUES(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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `lastRFID_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `lastRFID_add`(vCode VARCHAR(20), vAntennaFk INT, vAntennaPortFk INT, vPeakRssi INT, vSeenCount INT)
BEGIN
/* Insert a new record in lastRFID table
*
* @param vCode Char string read by the antenna
* @param vAntennaFk Identifier for srt.antenna table
*/
INSERT INTO srt.lastRFID(code, antennaFk, antennaPort, peakRssi, seenCount)
VALUES(vCode, vAntennaFk, vAntennaPortFk , vPeakRssi , vSeenCount );
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `lastRFID_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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `lastRFID_add_beta`(vCode VARCHAR(20), vAntennaFk INT, vAntennaPortFk INT, vPeakRssi INT, vSeenCount INT)
BEGIN
/* Insert a new record in lastRFID table
*
* @param vCode Char string read by the antenna
* @param vAntennaFk Identifier for srt.antenna table
*/
INSERT INTO srt.lastRFID(code, antennaFk, antennaPort, peakRssi, seenCount)
VALUES(vCode, vAntennaFk, vAntennaPortFk , vPeakRssi , vSeenCount );
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `moving_between` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `moving_between`(vBufferA INT, vBufferB INT)
BEGIN
DECLARE vExpeditionFk INT;
SELECT e.id INTO vExpeditionFk
FROM srt.expedition e
LEFT JOIN srt.moving m ON m.expeditionFk = e.id
WHERE e.bufferFk = vBufferA
AND ISNULL(m.id)
ORDER BY e.`position`
LIMIT 1;
IF ISNULL(vExpeditionFk) THEN
SET vExpeditionFk = srt.expedition_check(0);
UPDATE srt.expedition
SET bufferFk = vBufferA, `position` = 1
WHERE id = vExpeditionFk;
END IF;
CALL `srt`.`expedition_Relocate`(vExpeditionFk, IFNULL(vBufferB,srt.buffer_get(vExpeditionFk)));
SELECT * FROM srt.moving m ORDER BY 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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `moving_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `moving_clean`()
BEGIN
/**
* Elimina movimientos por inactividad
*
*/
DECLARE vExpeditionFk INT;
DECLARE vBufferToFk INT;
DECLARE vBufferFromFk INT;
DECLARE done BOOL DEFAULT FALSE;
DECLARE cur CURSOR FOR
SELECT m.expeditionFk, m.bufferToFk, m.bufferFromFk
FROM srt.moving m
JOIN srt.config c
JOIN (SELECT bufferFk, SUM(isActive) hasBox
FROM srt.photocell
GROUP BY bufferFk) sub ON sub.bufferFk = m.bufferFromFk
WHERE m.created < TIMESTAMPADD(MINUTE, - c.movingMaxLife , util.VN_NOW())
AND NOT sub.hasBox;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur;
bucle: LOOP
FETCH cur INTO vExpeditionFk, vBufferToFk, vBufferFromFk;
IF done THEN
LEAVE bucle;
END IF;
DELETE FROM srt.moving
WHERE expeditionFk = vExpeditionFk;
UPDATE srt.expedition e
JOIN srt.expeditionState es ON es.description = 'OUT'
SET
bufferFk = NULL,
`position` = NULL,
stateFk = es.id
WHERE e.id = vExpeditionFk;
UPDATE srt.expedition e
SET e.`position` = e.`position` - 1
WHERE e.bufferFk = vBufferFromFk
AND e.`position` > 0;
CALL vn.mail_insert(
'pako@verdnatura.es, carles@verdnatura.es',
NULL,
CONCAT('Moving_clean. Expedition: ', vExpeditionFk, ' estaba parada'),
CONCAT('Expedition: ', vExpeditionFk,' vBufferToFk: ', vBufferToFk)
);
END LOOP bucle;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `moving_CollidingSet` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `moving_CollidingSet`()
BEGIN
UPDATE srt.moving
SET isColliding = FALSE;
UPDATE srt.moving m1
JOIN srt.buffer sf1 ON sf1.id = m1.bufferFromFk
JOIN srt.buffer st1 ON st1.id = m1.bufferToFk
JOIN srt.movingState ms1 ON ms1.id = m1.stateFk
JOIN srt.moving m2
JOIN srt.buffer sf2 ON sf2.id = m2.bufferFromFk
JOIN srt.buffer st2 ON st2.id = m2.bufferToFk
JOIN srt.movingState ms2 ON ms2.id = m2.stateFk
SET m1.isColliding = TRUE
WHERE NOT ms1.isInterfering
AND ms2.isInterfering
AND (sf1.stratus = st2.stratus
OR
st1.stratus = sf2.stratus )
;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `moving_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `moving_delete`(vExpeditionFk INT)
BEGIN
/* Elimina un movimiento
*
* @param vExpeditionFk Identificador de srt.expedition
*
*/
INSERT INTO srt.movingLog(expeditionFk, bufferFromFk, bufferToFk, stateFk, isColliding, movingFk, `action`)
SELECT expeditionFk, bufferFromFk, bufferToFk, stateFk, isColliding, id, 'DELETE'
FROM srt.moving
WHERE expeditionFk = vExpeditionFk;
DELETE FROM srt.moving
WHERE expeditionFk = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `moving_groupOut` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `moving_groupOut`()
proc: BEGIN
DECLARE vDayMinute INT;
DECLARE vRouteFk INT;
DECLARE vBufferToFk INT;
DECLARE vBufferFromFk INT;
DECLARE vBufferGroupFk INT;
DECLARE vDone INT DEFAULT FALSE;
DECLARE cur1 CURSOR FOR
SELECT DISTINCT b.id
FROM srt.buffer b
JOIN srt.bufferState bs ON bs.id = b.stateFk
JOIN srt.bufferType bt ON bt.id = b.typeFk
JOIN srt.bufferGroup bg ON bg.bufferFk = b.id
LEFT JOIN srt.moving m ON m.bufferToFk = b.id
WHERE bs.description = 'FREE'
AND b.isActive
AND bt.typeName = 'STRAPPING';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
IF (SELECT (isAuto OR isRandomMoving) FROM srt.config) THEN
LEAVE proc;
END IF;
CASE (SELECT groupingMode FROM srt.config)
WHEN 'TRUCK' THEN
SELECT min(ev.dayMinute) INTO vDayMinute
FROM srt.expeditionVolume ev
WHERE ev.isReady
AND ev.dayMinute
AND ev.bufferTruck;
IF vDayMinute THEN
SELECT min(ev.bufferTruck) INTO vBufferToFk
FROM srt.expeditionVolume ev
WHERE ev.dayMinute = vDayMinute;
UPDATE srt.buffer
SET dayMinute = vDayMinute
WHERE id = vBufferToFk;
CALL srt.expedition_groupOut(vDayMinute,vBufferToFk);
END IF;
WHEN 'ROUTE' THEN
SELECT min(rv.dayMinute) INTO vDayMinute
FROM srt.routeVolume rv
LEFT JOIN srt.buffer b ON b.routeFk = rv.routeFk
WHERE rv.isReady
AND rv.dayMinute
AND rv.bufferTruck
AND ISNULL(b.id);
IF vDayMinute THEN
SELECT min(ev.bufferTruck) INTO vBufferToFk
FROM srt.expeditionVolume ev
WHERE ev.dayMinute = vDayMinute;
SELECT rv.routeFk INTO vRouteFk
FROM srt.routeVolume rv
WHERE rv.dayMinute = vDayMinute
AND rv.isReady
ORDER BY dayMinute, cajas DESC
LIMIT 1;
UPDATE srt.buffer
SET routeFk = vRouteFk
WHERE id = vBufferToFk;
CALL srt.expedition_routeOut(vRouteFk,vBufferToFk);
END IF;
WHEN 'BUFFER' THEN
SELECT rv.dayMinute, rv.routeBuffer
INTO vDayMinute, vBufferToFk
FROM srt.routeVolume rv
WHERE rv.isReady
AND rv.dayMinute
AND rv.routeBuffer
ORDER BY rv.dayMinute
LIMIT 1;
IF vDayMinute THEN
CALL srt.expedition_bufferOut(vBufferToFk);
END IF;
WHEN 'BUFFERGROUP' THEN
-- En el caso de que haya cajas en buffers auxiliares y los principales esten libres, reenvia cajas
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO vBufferToFk;
IF vDone THEN
LEAVE read_loop;
END IF;
SELECT bg.`group` INTO vBufferGroupFk
FROM srt.bufferGroup bg
WHERE bg.bufferFk = vBufferToFk;
SELECT MAX(e.bufferFk) INTO vBufferFromFk
FROM srt.expedition e
JOIN srt.expeditionState es ON es.id = e.stateFk
JOIN srt.bufferGroup bg ON bg.bufferFk = e.bufferFk
LEFT JOIN srt.moving m ON m.bufferToFk = e.bufferFk
LEFT JOIN srt.moving mo ON mo.bufferFromFk = e.bufferFk
JOIN srt.buffer b on b.id = e.bufferFk
JOIN srt.bufferType bt on bt.id = b.typeFk
WHERE bg.`group` = vBufferGroupFk
AND ISNULL(m.bufferToFk)
AND ISNULL(mo.id)
AND bt.typeName = 'ACCUMULATION';
IF vBufferFromFk THEN
CALL srt.buffer_giveBack(vBufferFromFk);
END IF;
END LOOP;
CLOSE cur1;
END CASE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `moving_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `moving_next`()
BEGIN
DECLARE vExpeditionFk INT;
DECLARE vMovingFk INT;
DECLARE vSecondsFromLastRFIDReading INT;
CALL srt.randomMoving_Launch();
CALL srt.moving_GroupOut();
CALL srt.moving_CollidingSet();
SELECT TIME_TO_SEC((TIMEDIFF(util.VN_NOW(),MAX(lr.created))))
INTO vSecondsFromLastRFIDReading
FROM srt.lastRFID lr;
SELECT m.id INTO vMovingFk
FROM srt.moving m
JOIN srt.expedition e ON e.id = m.expeditionFk
JOIN srt.movingState ms ON ms.id = m.stateFk
JOIN srt.buffer b ON b.id = m.bufferToFk
JOIN srt.buffer b2 ON b2.id = m.bufferFromFk
JOIN srt.bufferType bt ON bt.id = b.typeFk
JOIN srt.bufferState bs ON bs.id = b.stateFk
JOIN srt.config c
WHERE NOT ms.isInterfering
AND NOT m.isColliding
AND (c.isEnteringBlocked = FALSE OR m.bufferFromFk > 0)
AND (e.`position` = 1 OR m.bufferFromFk = 0)
AND (vSecondsFromLastRFIDReading > c.enteringSecondsReserve OR m.bufferFromFk = 0)
AND (bs.description != 'FULL' OR m.bufferFromFk = 0)
ORDER BY (m.bufferFromFk = 0) DESC,
m.bufferFromFk DESC
LIMIT 1;
SELECT m.expeditionFk
INTO vExpeditionFk
FROM moving m
WHERE m.id = vMovingFk;
IF vExpeditionFk THEN
SELECT m.expeditionFk,
m.bufferFromFk,
m.bufferToFk
FROM moving m
WHERE m.id = vMovingFk;
UPDATE expedition e
JOIN expeditionState es ON es.description = 'MOVING'
SET e.stateFk = es.id
WHERE e.id = vExpeditionFk;
UPDATE srt.moving m
JOIN srt.movingState ms ON ms.description = 'MOVING'
SET m.stateFk = ms.id
WHERE m.id = vMovingFk;
INSERT INTO srt.movingLog(expeditionFk, bufferFromFk, bufferToFk, stateFk, isColliding, movingFk, `action`)
SELECT expeditionFk, bufferFromFk, bufferToFk, stateFk, isColliding, id, 'NEXT'
FROM srt.moving
WHERE id = vMovingFk;
ELSE
SELECT 0 expeditionFk, 0 bufferFromFk, 0 bufferToFk;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `photocell_setActive` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `photocell_setActive`(vBufferFk int, vPosition int, vIsActive bool)
BEGIN
REPLACE srt.photocell VALUES (vbufferFk, vPosition, vIsActive);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `randomMoving` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `randomMoving`(vBufferMin INT, vBufferMax INT)
BEGIN
DECLARE vBufferOld INT DEFAULT 0;
DECLARE vBufferFk INT;
DECLARE vExpeditionFk INT;
SELECT e.id INTO vExpeditionFk
FROM srt.expedition e
LEFT JOIN srt.moving m ON m.expeditionFk = e.id
JOIN srt.buffer b ON b.id = e.bufferFk
JOIN srt.bufferType bt ON bt.id = b.typeFk
WHERE e.bufferFk BETWEEN vBufferMin AND vBufferMax
AND m.id IS NULL
AND bt.typeName = 'ACCUMULATION'
AND b.isActive
ORDER BY e.`position`, e.updated
LIMIT 1;
SELECT IFNULL(e.bufferFk,0) INTO vBufferOld
FROM srt.expedition e
WHERE e.id = vExpeditionFk;
SELECT b.id INTO vBufferFk
FROM srt.buffer b
JOIN srt.bufferFreeLength bfl ON bfl.bufferFk = b.id
JOIN srt.bufferType bt ON bt.id = b.typeFk
JOIN srt.config c
LEFT JOIN srt.moving m ON m.bufferToFk = b.id
LEFT JOIN srt.moving m2 ON m2.bufferFromFk = b.id
WHERE ISNULL(m.bufferToFk)
AND ISNULL(m2.bufferFromFk)
AND b.id BETWEEN vBufferMin AND vBufferMax
AND b.id != vBufferOld
AND b.isActive
AND bt.typeName = 'ACCUMULATION'
AND bfl.freeLength > c.freeLength * 2
ORDER BY (b.id = floor(MINUTE(util.VN_NOW())/2)) DESC
LIMIT 1;
IF vBufferFk THEN
INSERT INTO srt.moving (expeditionFk, bufferFromFk, bufferToFk)
SELECT e.id, e.bufferFk, vBufferFk
FROM srt.expedition e
WHERE e.id = vExpeditionFk;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `randomMoving_Launch` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `randomMoving_Launch`()
BEGIN
DECLARE i INT DEFAULT 5;
IF (SELECT count(*) FROM srt.moving) < 5 AND (SELECT isRandomMoving FROM srt.config) THEN
WHILE i DO
SET i = i - 1;
-- CALL srt.randomMoving(22,35);
CALL srt.randomMoving(2,5);
END WHILE;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `restart` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `restart`()
BEGIN
/*
* Se ha pulsado el botón RESTART en la pantalla tàctil del sorter
*/
DELETE FROM srt.moving
WHERE bufferFromFk = 0;
INSERT INTO srt.sorterLog(`action`) VALUES('RESTART');
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `start`()
BEGIN
/*
* Se ha pulsado el botón START en la pantalla tàctil del sorter
*/
INSERT INTO srt.sorterLog(`action`) VALUES('START');
UPDATE srt.config SET isEnteringBlocked = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `stop` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `stop`()
BEGIN
/*
* Se ha pulsado el botón STOP en la pantalla tàctil del sorter
*/
INSERT INTO srt.sorterLog(`action`) VALUES('STOP');
UPDATE srt.config SET isEnteringBlocked = 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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `test` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `test`()
BEGIN
SELECT 'procedimiento ejecutado con éxito';
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_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 utf8mb3 COLLATE utf8mb3_general_ci */;
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=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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 NOT NULL,
`outboundFk` int(10) unsigned NOT NULL,
`quantity` int(11) NOT NULL,
PRIMARY KEY (`inboundFk`,`outboundFk`,`quantity`),
UNIQUE KEY `buyFk` (`inboundFk`,`outboundFk`),
KEY `saleFk` (`outboundFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `log`
--
DROP TABLE IF EXISTS `log`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `log` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`operation` set('insert','delete') NOT NULL,
`tableName` varchar(255) NOT NULL,
`tableId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `tableName` (`tableName`,`tableId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!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=utf8mb3 COLLATE=utf8mb3_general_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` (
`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=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `log_clean` ON SCHEDULE EVERY 1 DAY STARTS '2022-01-28 09:29:18' 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 = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `log_refreshOrder`(
`vTableName` VARCHAR(255),
`vTableId` INT)
BEGIN
DECLARE vExpireTime INT DEFAULT 20;
DECLARE vExpired DATETIME DEFAULT TIMESTAMPADD(MINUTE, -vExpireTime, util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 <= util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `log_syncNoWait` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `visible_log` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 */ ;
--
-- Current Database: `tmp`
--
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `tmp` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */;
USE `tmp`;
--
-- Dumping events for database 'tmp'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `clean` ON SCHEDULE EVERY 1 HOUR STARTS '2022-03-01 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL tmp.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 'tmp'
--
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`()
BEGIN
DECLARE vTableName VARCHAR(255);
DECLARE vDone BOOL;
DECLARE cur CURSOR FOR
SELECT TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'tmp'
AND CREATE_TIME < TIMESTAMPADD(DAY, 1, util.VN_NOW());
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN cur;
l: LOOP
SET vDone = FALSE;
FETCH cur INTO vTableName;
IF vDone THEN
LEAVE l;
END IF;
CALL util.exec(CONCAT('DROP TABLE `tmp`.`', vTableName, '`'));
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 */ ;
--
-- Current Database: `util`
--
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `util` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */;
USE `util`;
--
-- Table structure for table `binlogQueue`
--
DROP TABLE IF EXISTS `binlogQueue`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `binlogQueue` (
`code` varchar(255) NOT NULL,
`logName` varchar(255) NOT NULL,
`position` bigint(20) unsigned NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Binary log position of asynchronous queues';
/*!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,
`dbVersion` char(11) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci 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 utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT 'The current Database environment',
`lastDump` datetime DEFAULT NULL COMMENT 'Timestamp of the last data dump',
`mockUtcTime` datetime DEFAULT NULL,
`mockTime` datetime DEFAULT NULL,
`mockEnabled` tinyint(3) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
CONSTRAINT `config_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`host` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`variable` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`value` text DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `created` (`created`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Log de depuración';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `eventLog`
--
DROP TABLE IF EXISTS `eventLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `eventLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` datetime NOT NULL,
`event` varchar(512) NOT NULL,
`error` varchar(1024) NOT NULL,
PRIMARY KEY (`id`),
KEY `date` (`date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Event scheduler error log';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `eventLogGrouped`
--
DROP TABLE IF EXISTS `eventLogGrouped`;
/*!50001 DROP VIEW IF EXISTS `eventLogGrouped`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `eventLogGrouped` AS SELECT
1 AS `lastHappened`,
1 AS `nErrors`,
1 AS `event`,
1 AS `error` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `notification`
--
DROP TABLE IF EXISTS `notification`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `notification` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `notificationAcl`
--
DROP TABLE IF EXISTS `notificationAcl`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `notificationAcl` (
`notificationFk` int(11) NOT NULL,
`roleFk` int(10) unsigned NOT NULL,
PRIMARY KEY (`notificationFk`,`roleFk`),
KEY `notificationAcl_ibfk_2` (`roleFk`),
CONSTRAINT `notificationAcl_Fk` FOREIGN KEY (`notificationFk`) REFERENCES `notification` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `notificationAcl_ibfk_2` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `notificationConfig`
--
DROP TABLE IF EXISTS `notificationConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `notificationConfig` (
`id` int(10) unsigned NOT NULL,
`cleanDays` mediumint(9) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `notificationConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `notificationQueue`
--
DROP TABLE IF EXISTS `notificationQueue`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `notificationQueue` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`notificationFk` varchar(255) DEFAULT NULL,
`params` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`params`)),
`authorFk` int(10) unsigned DEFAULT NULL,
`status` enum('pending','sent','error') NOT NULL DEFAULT 'pending',
`created` datetime DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `notificationFk` (`notificationFk`),
KEY `authorFk` (`authorFk`),
KEY `status` (`status`),
CONSTRAINT `notificationQueue_Fk` FOREIGN KEY (`notificationFk`) REFERENCES `notification` (`name`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `notificationQueue_ibfk_2` FOREIGN KEY (`authorFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `notificationSubscription`
--
DROP TABLE IF EXISTS `notificationSubscription`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `notificationSubscription` (
`notificationFk` int(11) NOT NULL,
`userFk` int(10) unsigned NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
UNIQUE KEY `notificationSubscription_UN` (`notificationFk`,`userFk`),
KEY `notificationSubscription_ibfk_2` (`userFk`),
KEY `notificationSubscription_ibfk_1` (`notificationFk`),
CONSTRAINT `notificationSubscription_Fk` FOREIGN KEY (`notificationFk`) REFERENCES `notification` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `notificationSubscription_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `version`
--
DROP TABLE IF EXISTS `version`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `version` (
`code` varchar(50) NOT NULL,
`number` char(11) DEFAULT NULL,
`gitCommit` varchar(255) DEFAULT NULL,
`updated` datetime DEFAULT NULL,
`lastNumber` char(11) DEFAULT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `versionConfig`
--
DROP TABLE IF EXISTS `versionConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `versionConfig` (
`id` int(10) unsigned NOT NULL,
`realm` varchar(16) DEFAULT NULL COMMENT 'Data set on which the project runs',
PRIMARY KEY (`id`),
CONSTRAINT `versionConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `versionLog`
--
DROP TABLE IF EXISTS `versionLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `versionLog` (
`code` varchar(50) NOT NULL,
`number` char(11) NOT NULL,
`file` varchar(255) NOT NULL,
`user` varchar(255) DEFAULT NULL,
`updated` datetime NOT NULL,
`errorNumber` int(10) unsigned DEFAULT NULL,
`errorMessage` varchar(255) DEFAULT NULL,
PRIMARY KEY (`code`,`number`,`file`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping events for database 'util'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `slowLog_prune` */;
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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `slowLog_prune` ON SCHEDULE EVERY 1 DAY STARTS '2021-10-08 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL util.slowLog_prune */ ;;
/*!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 'util'
--
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `accountNumberToIban` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `accountNumberToIban`(vAccount VARCHAR(20)
) RETURNS varchar(4) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
DETERMINISTIC
BEGIN
/**
* Calcula y genera el código IBAN correspondiente
* a un número de cuenta bancaria español.
*
* @param vAccount Número de cuenta bancaria
* @return vIban Código IBAN de 4 caracteres.
*/
DECLARE vIban VARCHAR(4);
SELECT
CONCAT('ES',
RIGHT(
CONCAT(0,
98-MOD(
CONCAT(
MOD(
CONCAT(
MOD(
CONCAT(
MOD(
SUBSTRING(vAccount, 1, 8),
97
),
SUBSTRING(vAccount,9,8)
),
97
),
SUBSTRING(
CONCAT(vAccount, 142800),
17,
8
)
),
97
),
SUBSTRING(
CONCAT(vAccount, 142800),
25,
2
)
),
97
)
),
2
)
) INTO vIban;
RETURN vIban;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `accountShortToStandard` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `accountShortToStandard`(vAccount VARCHAR(10)) RETURNS varchar(10) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
DETERMINISTIC
BEGIN
RETURN REPLACE(vAccount, '.', REPEAT('0', 11 - LENGTH(vAccount)));
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `binlogQueue_getDelay` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `binlogQueue_getDelay`(vCode VARCHAR(255)) RETURNS bigint(20)
READS SQL DATA
BEGIN
/**
* Returns the difference between the current position of the binary log and
* the passed queue.
*
* @param vCode The queue code
* @return The difference in MB
*/
DECLARE vCurLogName VARCHAR(255);
DECLARE vCurPosition BIGINT;
DECLARE vQueueLogName VARCHAR(255);
DECLARE vQueuePosition BIGINT;
DECLARE vDelay BIGINT;
SELECT VARIABLE_VALUE INTO vCurLogName
FROM information_schema.GLOBAL_STATUS
WHERE VARIABLE_NAME = 'BINLOG_SNAPSHOT_FILE';
SELECT VARIABLE_VALUE INTO vCurPosition
FROM information_schema.GLOBAL_STATUS
WHERE VARIABLE_NAME = 'BINLOG_SNAPSHOT_POSITION';
SELECT logName, `position`
INTO vQueueLogName, vQueuePosition
FROM binlogQueue
WHERE code = vCode;
IF vQueuePosition IS NULL THEN
RETURN NULL;
END IF;
SET vDelay =
vCurPosition - CAST(vQueuePosition AS SIGNED) +
@@max_binlog_size * (
CAST(REGEXP_SUBSTR(vCurLogName, '[0-9]+') AS SIGNED) -
CAST(REGEXP_SUBSTR(vQueueLogName, '[0-9]+') AS SIGNED)
);
RETURN ROUND(vDelay / POW(1024, 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `capitalizeFirst`(vString VARCHAR(255)) RETURNS varchar(255) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `checkPrintableChars` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `checkPrintableChars`(vString VARCHAR(255)
) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
/**
* Validates whether the input string contains only printable characters
* and Spanish special characters (such as ¡, ÿ, etc.).
*
* @vString string to check
*/
RETURN vString REGEXP '^[ -~¡-ÿ]*$';
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `crypt`(vText VARCHAR(255), vKey VARCHAR(255)) RETURNS varchar(255) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `cryptOff`(vText VARCHAR(255), vKey VARCHAR(255)) RETURNS varchar(255) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 TIMESTAMPADD(DAY, - DAY(vDate) + 1, 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `formatRow` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `formatRow`(vType CHAR(3), vValues VARCHAR(512)) RETURNS varchar(512) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
DETERMINISTIC
BEGIN
DECLARE vRow VARCHAR(512);
IF vValues IS NOT NULL THEN
SET vRow = CONCAT('
', vType ,' |
', REPLACE(vValues, ',', ' | ') ,' |
');
ELSE
SET vRow = '';
END IF;
RETURN vRow;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `formatTable` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `formatTable`(vFields VARCHAR(512), vOldValues VARCHAR(512), vNewValues VARCHAR(512)) RETURNS text CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
DETERMINISTIC
BEGIN
DECLARE vTable TEXT;
SET vTable = CONCAT('
type |
', REPLACE(vFields, ',', ' | ') ,'
|
', formatRow('old', vOldValues) ,'
', formatRow('new', vNewValues) ,'
');
RETURN 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `hasDateOverlapped` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `hasDateOverlapped`(vSarted1 DATE, vEnded1 DATE, vSarted2 DATE, vEnded2 DATE) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
RETURN GREATEST(vSarted1, vSarted2) <= LEAST(vEnded1,vEnded2);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `hmacSha2`(`vAlg` SMALLINT, `vMsg` MEDIUMBLOB, `vKey` MEDIUMBLOB) RETURNS varchar(128) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `isLeapYear` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `isLeapYear`(vYear INT) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
RETURN (DAYOFYEAR(CONCAT(vYear, "-02-29")) IS NOT NULL);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `json_removeNulls` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `json_removeNulls`(vObject JSON) RETURNS longtext CHARSET utf8mb4 COLLATE utf8mb4_bin
DETERMINISTIC
BEGIN
/**
* Elimina las propiedades con valor NULL de un objeto.
*
* @param vObject El objeto en formato JSON
* @return El objeto JSON sin propiedades a NULL
*/
DECLARE vKeys JSON;
DECLARE vPath VARCHAR(255);
DECLARE vValue VARCHAR(255);
DECLARE i INT DEFAULT 0;
DECLARE vCount INT;
SET vKeys = JSON_KEYS(vObject);
SET vCount = JSON_LENGTH(vKeys);
WHILE i < vCount DO
SET vPath = CONCAT('$.', JSON_VALUE(vKeys, CONCAT('$[',i,']')));
SET vValue = JSON_VALUE(vObject, vPath);
IF vValue IS NULL THEN
SET vObject = JSON_REMOVE(vObject, vPath);
END IF;
SET i := i + 1;
END WHILE;
RETURN vObject;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `lang`() RETURNS char(2) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `lastDayOfYear` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `lastDayOfYear`(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-12-31');
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `log_formatDate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `log_formatDate`(vInstance JSON) RETURNS longtext CHARSET utf8mb4 COLLATE utf8mb4_bin
DETERMINISTIC
BEGIN
DECLARE vKeys JSON;
DECLARE vPath VARCHAR(255);
DECLARE vValue VARCHAR(255);
DECLARE i INT DEFAULT 0;
DECLARE vCount INT;
IF vInstance IS NULL THEN
RETURN NULL;
END IF;
SET vKeys = JSON_KEYS(vInstance);
SET vCount = JSON_LENGTH(vInstance);
WHILE i < vCount DO
SET vPath = CONCAT('$.', JSON_VALUE(vKeys, CONCAT('$[', i ,']')));
SET vValue = JSON_VALUE(vInstance, vPath);
IF vValue REGEXP '^[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2} [[:digit:]]{2}:[[:digit:]]{2}:[[:digit:]]{2}$' THEN
SET vInstance = JSON_SET(vInstance, vPath, DATE_FORMAT(CONVERT_TZ(vValue, '+01:00', '+00:00'), '%Y-%m-%dT%T.%fZ'));
END IF;
SET i := i + 1;
END WHILE;
RETURN vInstance;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `midnight` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `midnight`() RETURNS datetime
READS SQL DATA
BEGIN
RETURN TIMESTAMP(util.VN_CURDATE(), '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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `mockTime` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `mockTime`() RETURNS datetime
DETERMINISTIC
BEGIN
/**
* Returns current dateTime
*
* @return current datetime
*/
RETURN 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `mockTimeBase` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `mockTimeBase`(vIsUtc BOOL) RETURNS datetime
DETERMINISTIC
BEGIN
/**
* Returns the date formatted to utc if vIsUtc or config.mocTz if not
*
* @param vIsUtc If date must be returned as UTC format
* @return The formatted mock time
*/
DECLARE vMockUtcTime DATETIME;
DECLARE vMockTz VARCHAR(255);
SELECT mockUtcTime, mockTz
INTO vMockUtcTime, vMockTz
FROM config
LIMIT 1;
IF vIsUtc OR vMockTz IS NULL THEN
RETURN vMockUtcTime;
ELSE
RETURN CONVERT_TZ(vMockUtcTime, '+00:00', vMockTz);
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `mockUtcTime` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `mockUtcTime`() RETURNS datetime
DETERMINISTIC
BEGIN
/**
* Returns the UTC datetime in mockTime format or timeStamp depending on config table
*
* @return The UTC datetime format
*/
-- FIXME: #5041 Commented because there is slowness when querying a table
/*
DECLARE vMockEnabled BOOL;
SELECT mockEnabled INTO vMockEnabled FROM config LIMIT 1;
IF vMockEnabled THEN
RETURN mockTimeBase(TRUE);
ELSE
RETURN UTC_TIMESTAMP();
END IF;
*/
RETURN UTC_TIMESTAMP();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `nextWeek` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `notification_send` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `notification_send`(vNotificationName VARCHAR(255), vParams TEXT, vAuthorFk INT) RETURNS int(11)
MODIFIES SQL DATA
BEGIN
/**
* Sends a notification.
*
* @param vNotificationName The notification name
* @param vParams The notification parameters formatted as JSON
* @param vAuthorFk The notification author or %NULL if there is no author
* @return The notification id
*/
INSERT INTO notificationQueue
SET notificationFk = vNotificationName,
params = vParams,
authorFk = vAuthorFk;
RETURN 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `quarterFirstDay` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `quarterFirstDay`(vYear INT, vQuarter INT) RETURNS date
DETERMINISTIC
BEGIN
RETURN CONCAT(vYear,"-", ((vQuarter - 1) * 3) + 1, "-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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `quoteIdentifier` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `quoteIdentifier`(vString TEXT) RETURNS text CHARSET utf8mb3 COLLATE utf8mb3_general_ci
NO SQL
DETERMINISTIC
BEGIN
RETURN CONCAT('`', REPLACE(vString, '`', '``'), '`');
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `today` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `today`() RETURNS date
DETERMINISTIC
BEGIN
/**
* Devuelve la fecha actual. Usar en lugar de la función nativa
* util.VN_CURDATE() en aquellos que se necesite rendimiento ya que la
* la última no es determinista.
*
* @return La fecha actual
*/
RETURN util.VN_CURDATE();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `tomorrow`() RETURNS date
DETERMINISTIC
BEGIN
/**
* Devuelve la fecha de mañana.
*
* @return La fecha de mañana
*/
RETURN TIMESTAMPADD(DAY, 1, util.VN_CURDATE());
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `twoDaysAgo` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `twoDaysAgo`() RETURNS date
DETERMINISTIC
BEGIN
/**
* Devuelve la fecha de antes de ayer.
*
* @return La fecha de antes de ayer
*/
RETURN TIMESTAMPADD(DAY, -2, util.VN_CURDATE());
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `VN_CURDATE` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `VN_CURDATE`() RETURNS date
DETERMINISTIC
BEGIN
/**
* @return The mock date
*/
RETURN DATE(mockTime());
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `VN_CURTIME` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `VN_CURTIME`() RETURNS time
DETERMINISTIC
BEGIN
/**
* @return The mock curtime
*/
RETURN TIME(mockTime());
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `VN_NOW` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `VN_NOW`() RETURNS datetime
DETERMINISTIC
BEGIN
/**
* @return The mock datetime
*/
RETURN mockTime();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `VN_UNIX_TIMESTAMP` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `VN_UNIX_TIMESTAMP`() RETURNS int(11)
DETERMINISTIC
BEGIN
/**
* @return The mock time in unix timestamp format
*/
RETURN UNIX_TIMESTAMP(mocktime());
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `VN_UTC_DATE` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `VN_UTC_DATE`() RETURNS date
DETERMINISTIC
BEGIN
/**
* @return The mock Date in UTC format
*/
RETURN DATE(mockUtcTime());
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `VN_UTC_TIME` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `VN_UTC_TIME`() RETURNS time
DETERMINISTIC
BEGIN
/**
* @return The mock time in utc format
*/
RETURN TIME(mockUtcTime());
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `VN_UTC_TIMESTAMP` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `VN_UTC_TIMESTAMP`() RETURNS datetime
DETERMINISTIC
BEGIN
/*
* @return The mock utc datetime
*/
RETURN mockUtcTime();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `yearRelativePosition` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `yearRelativePosition`(vYear INT) RETURNS varchar(20) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
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(util.VN_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 */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `yesterday` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `yesterday`() RETURNS date
DETERMINISTIC
BEGIN
/**
* Devuelve la fecha de ayer.
*
* @return La fecha de ayer
*/
RETURN TIMESTAMPADD(DAY, -1, util.VN_CURDATE());
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `checkHex` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `checkHex`(vParam VARCHAR(255))
BEGIN
/**
* Comprueba si vParam es un número hexadecimal que empieza por # y tiene una longitud total de 7 dígitos
*
* @param expresión a comprobar
*/
IF vParam NOT REGEXP ('^#[0-9a-f]{6}$') THEN
CALL util.throw('Invalid RGB format');
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `connection_kill` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `connection_kill`(
vConnectionId BIGINT
)
BEGIN
/**
* Kill a connection
*
* @param vConnectionId
*/
KILL vConnectionId;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `debugAdd` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `exec`(vSqlQuery TEXT)
SQL SECURITY INVOKER
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `log_add`(
vSchema VARCHAR(45),
vEntity VARCHAR(45),
vChangedModel VARCHAR(45),
vOriginFk INT,
vChangedModelId INT,
vActionCode VARCHAR(45),
vOldInstance JSON,
vNewInstance JSON)
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 vScheme Esquema al que pertenece la tabla.
* @param vEntity Nombre que hace referencia a la tabla.
* @param vOldInstance Valores antiguos
* @param vNewInstance Valores nuevos
*/
CALL util.log_addWithUser(vSchema, vEntity,
vChangedModel, vOriginFk, vChangedModelId, vActionCode, vOldInstance, vNewInstance, account.myUser_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `log_addWithUser` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `log_addWithUser`(
vSchema VARCHAR(45),
vEntity VARCHAR(45),
vChangedModel VARCHAR(45),
vOriginFk INT,
vChangedModelId INT,
vActionCode VARCHAR(45),
vOldInstance JSON,
vNewInstance JSON,
vUserId INT)
BEGIN
/**
* Guarda las acciones realizadas por el usuario
*
* @param vScheme Esquema al que pertenece la tabla.
* @param vEntity Nombre que hace referencia a la tabla donde se insertará el log
* @param vChangedModel Nombre que hace referencia a la tabla que se modifica
* @param vOriginFk Id del registro de la tabla origen
* @param vChangedModelId Id del registro de la tabla a la que se realiza la acción
* @param vActionCode Código de la acción {insert | delete | update}
* @param vOldInstance JSON que contiene los valores viejos
* @param vNewInstance JSON que contiene los valores nuevos
* @param vUserId Id del usuario que realiza la acción
*/
DECLARE vTableName VARCHAR(255) DEFAULT CONCAT(IFNULL(vEntity, ''), 'Log');
SET vSchema = util.quoteIdentifier(vSchema);
SET vTableName = util.quoteIdentifier(vTableName);
CALL util.log_cleanInstances(vActionCode, vOldInstance, vNewInstance);
EXECUTE IMMEDIATE CONCAT(
'INSERT INTO ', vSchema, '.', vTableName, ' SET changedModel = ?, originFk = ?, changedModelId= ?, action = ?, oldInstance = ?, newInstance = ?, userFk = ?'
) USING vChangedModel, vOriginFk, vChangedModelId, vActionCode, vOldInstance, vNewInstance, 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `log_cleanInstances` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `log_cleanInstances`(
vActionCode VARCHAR(45),
INOUT vOldInstance JSON,
INOUT vNewInstance JSON)
BEGIN
/**
* Cleans both instances removing nulls and keys whose values are the same.
*
* @param vActionCode The action code {insert | delete | update}
* @param vOldInstance JSON containing the old values
* @param vNewInstance JSON containing the new values
*/
DECLARE vKeys JSON;
DECLARE vPath VARCHAR(255);
DECLARE vOldValue JSON;
DECLARE vNewValue JSON;
DECLARE vOld JSON;
DECLARE vNew JSON;
DECLARE i INT DEFAULT 0;
DECLARE vCount INT;
CASE vActionCode
WHEN 'insert' THEN
SET vNewInstance = json_removeNulls(vNewInstance);
WHEN 'update' THEN
SET vOld = '{}';
SET vNew = '{}';
SET vKeys = JSON_KEYS(vNewInstance);
SET vCount = JSON_LENGTH(vKeys);
WHILE i < vCount DO
SET vPath = CONCAT('$.', JSON_VALUE(vKeys, CONCAT('$[',i,']')));
SET vOldValue = JSON_EXTRACT(vOldInstance, vPath);
SET vNewValue = JSON_EXTRACT(vNewInstance, vPath);
IF NOT (vOldValue <=> vNewValue) THEN
IF vOldValue IS NOT NULL AND vOldValue <> 'null' THEN
SET vOld = JSON_SET(vOld, vPath, JSON_COMPACT(vOldValue));
END IF;
IF vNewValue IS NOT NULL THEN
SET vNew = JSON_SET(vNew, vPath, JSON_COMPACT(vNewValue));
END IF;
END IF;
SET i := i + 1;
END WHILE;
SET vOldInstance = vOld;
SET vNewInstance = vNew;
WHEN 'delete' THEN
SET vOldInstance = json_removeNulls(vOldInstance);
ELSE BEGIN END;
END CASE;
SET vOldInstance = log_formatDate(vOldInstance);
SET vNewInstance = log_formatDate(vNewInstance);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `procNoOverlap` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `procNoOverlap`(procName VARCHAR(255))
SQL SECURITY INVOKER
proc: BEGIN
/**
* call procedure without overlap
*/
DECLARE vIsChanged BOOL;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
DO RELEASE_LOCK(procName);
RESIGNAL;
END;
IF !GET_LOCK(procName, 0) THEN
LEAVE proc;
END IF;
CALL exec(CONCAT('CALL ', procName));
DO RELEASE_LOCK(procName);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `slowLog_prune` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `slowLog_prune`()
BEGIN
/**
* Prunes MySQL slow query log table deleting all records older than one week.
*/
DECLARE vSlowQueryLog INT DEFAULT @@slow_query_log;
DECLARE vSqlLogBin INT DEFAULT @@SESSION.sql_log_bin;
DECLARE vLogExists BOOL;
SET sql_log_bin = OFF;
SET GLOBAL slow_query_log = OFF;
SELECT COUNT(*) > 0 INTO vLogExists
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'mysql' AND TABLE_NAME = 'slow_log';
IF vLogExists THEN
DROP TEMPORARY TABLE IF EXISTS mysql.slow_log_temp;
RENAME TABLE mysql.slow_log TO mysql.slow_log_temp;
END IF;
DELETE FROM mysql.slow_log_temp
WHERE start_time < TIMESTAMPADD(WEEK, -1, util.VN_NOW());
RENAME TABLE mysql.slow_log_temp TO mysql.slow_log;
SET GLOBAL slow_query_log = vSlowQueryLog;
SET sql_log_bin = vSqlLogBin;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `throw`(vMessage CHAR(55))
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `time_generate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `time_generate`(vStarted DATE, vEnded DATE)
BEGIN
/**
* Generate a temporary table between the days passed as parameters
*
* @param vStarted Start date
* @param vEnded End date
* @table tmp.time (dated, dayed, weeked, monthed, yeared)
*/
DECLARE vCurrentDate DATE;
CREATE OR REPLACE TEMPORARY TABLE tmp.time(
dated DATE PRIMARY KEY,
`day` INT,
`week` INT,
`month` INT,
`year` INT
) ENGINE = MEMORY;
IF(vStarted > vEnded) THEN
CALL throw('The started cannot be later than the ended');
END IF;
SET vCurrentDate = vStarted;
WHILE vCurrentDate <= vEnded DO
INSERT INTO tmp.time
SET dated = vCurrentDate,
`day` = DAY(vCurrentDate),
`week` = WEEK(vCurrentDate),
`month` = MONTH(vCurrentDate),
`year` = YEAR(vCurrentDate);
SET vCurrentDate = vCurrentDate + 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `tx_commit` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `tx_commit`(isTx BOOL)
BEGIN
/**
* Confirma los cambios asociados a una transacción.
*
* @param isTx es true si existe transacción asociada
*/
IF isTx THEN
COMMIT;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `tx_rollback` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `tx_rollback`(isTx BOOL)
BEGIN
/**
* Deshace los cambios asociados a una transacción.
*
* @param isTx es true si existe transacción asociada
*/
IF isTx THEN
ROLLBACK;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `tx_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `tx_start`(isTx BOOL)
BEGIN
/**
* Inicia una transacción.
*
* @param isTx es true si existe transacción asociada
*/
IF isTx THEN
START TRANSACTION;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 utf8mb3 COLLATE utf8mb3_unicode_ci */;
USE `vn`;
--
-- Temporary table structure for view `NewView`
--
DROP TABLE IF EXISTS `NewView`;
/*!50001 DROP VIEW IF EXISTS `NewView`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `NewView` AS SELECT
1 AS `clientFk`,
1 AS `lastShipped`,
1 AS `notBuyingMonths` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `XDiario`
--
DROP TABLE IF EXISTS `XDiario`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `XDiario` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ASIEN` double DEFAULT NULL,
`FECHA` datetime DEFAULT NULL,
`SUBCTA` varchar(12) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`CONTRA` varchar(12) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`CONCEPTO` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`EURODEBE` decimal(10,2) DEFAULT NULL,
`EUROHABER` decimal(10,2) DEFAULT NULL,
`BASEEURO` decimal(10,2) DEFAULT NULL,
`SERIE` varchar(1) DEFAULT NULL,
`FACTURA` varchar(8) DEFAULT '0',
`IVA` decimal(10,2) DEFAULT NULL,
`RECEQUIV` decimal(10,2) DEFAULT 0.00,
`CLAVE` int(11) DEFAULT NULL,
`CAMBIO` decimal(10,2) DEFAULT NULL,
`DEBEME` decimal(10,2) DEFAULT NULL,
`HABERME` decimal(10,2) DEFAULT NULL,
`AUXILIAR` varchar(1) DEFAULT NULL,
`MONEDAUSO` varchar(1) DEFAULT '2',
`TIPOOPE` varchar(1) DEFAULT NULL,
`NFACTICK` tinyint(1) NOT NULL DEFAULT 1,
`TERIDNIF` tinyint(1) NOT NULL DEFAULT 2,
`TERNIF` varchar(20) NOT NULL DEFAULT 'I.F.',
`TERNOM` varchar(50) NOT NULL DEFAULT 'Nombre Importador',
`OPBIENES` tinyint(1) NOT NULL DEFAULT 1,
`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` int(10) 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) DEFAULT NULL,
`METALEJE` varchar(4) DEFAULT NULL,
`FECHA_OP` date DEFAULT NULL COMMENT 'FEcha de operacion',
`FACTURAEX` varchar(45) 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) DEFAULT NULL,
`FACTU_RT` varchar(10) 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,
`enlazadoSage` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY `empresa_id` (`empresa_id`),
KEY `ASIENidx` (`id`,`ASIEN`),
KEY `SERIEidx` (`ASIEN`,`SERIE`),
KEY `XDiario` (`enlazado`),
KEY `enlazadoSage` (`enlazadoSage`),
CONSTRAINT `XDiarioCompany_Fk` FOREIGN KEY (`empresa_id`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `absenceType`
--
DROP TABLE IF EXISTS `absenceType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `absenceType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` 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,
`isPrintable` tinyint(1) NOT NULL DEFAULT 0,
`discountRate` decimal(3,2) DEFAULT NULL,
`holidayEntitlementRate` decimal(3,2) DEFAULT 1.00,
`isNaturalDay` tinyint(1) DEFAULT 0 COMMENT 'Para el cálculo de los salarios de los repartidores',
`isCalculate` tinyint(1) DEFAULT 0 COMMENT 'Para el cálculo de los salarios de los repartidores',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `accountDetail`
--
DROP TABLE IF EXISTS `accountDetail`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `accountDetail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`value` varchar(50) NOT NULL,
`accountDetailTypeFk` int(11) NOT NULL,
`supplierAccountFk` mediumint(8) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_account_detail_account_detail_type1_idx` (`accountDetailTypeFk`),
KEY `fk_account_detail_Proveedores_account1_idx` (`supplierAccountFk`),
CONSTRAINT `fk_account_detail_account_detail_type1` FOREIGN KEY (`accountDetailTypeFk`) REFERENCES `accountDetailType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `fk_account_detail_account_id_proveedores_account` FOREIGN KEY (`supplierAccountFk`) REFERENCES `supplierAccount` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `accountDetailType`
--
DROP TABLE IF EXISTS `accountDetailType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `accountDetailType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `accountReconciliation`
--
DROP TABLE IF EXISTS `accountReconciliation`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `accountReconciliation` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`supplierAccountFk` mediumint(8) unsigned NOT NULL,
`operationDated` datetime NOT NULL,
`valueDated` datetime NOT NULL,
`amount` double NOT NULL,
`concept` varchar(255) DEFAULT NULL,
`debitCredit` enum('debit','credit') DEFAULT NULL,
`calculatedCode` varchar(255) DEFAULT NULL,
`created` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
UNIQUE KEY `idaccount_conciliacion_UNIQUE` (`id`),
KEY `fg_accconciliacion_key1_idx` (`supplierAccountFk`),
KEY `index_id_calculated` (`calculatedCode`),
CONSTRAINT `fg_key1_accountconc` FOREIGN KEY (`supplierAccountFk`) REFERENCES `supplierAccount` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `accountReconciliationConfig`
--
DROP TABLE IF EXISTS `accountReconciliationConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `accountReconciliationConfig` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`currencyFk` tinyint(3) unsigned DEFAULT NULL,
`warehouseFk` smallint(6) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `account_fk_currency` (`currencyFk`),
KEY `account_fk_warehouse` (`warehouseFk`),
CONSTRAINT `account_fk_currency` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`),
CONSTRAINT `account_fk_warehouse` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `accounting`
--
DROP TABLE IF EXISTS `accounting`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `accounting` (
`id` int(11) NOT NULL DEFAULT 0,
`bank` varchar(50) DEFAULT NULL,
`account` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`accountingTypeFk` smallint(6) NOT NULL DEFAULT 0,
`entityFk` int(10) unsigned DEFAULT NULL,
`isActive` tinyint(4) NOT NULL DEFAULT 1,
`currencyFk` tinyint(3) unsigned DEFAULT 1,
`code` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `BancosBanco` (`bank`),
KEY `fk_Bancos_entity1_idx` (`entityFk`),
KEY `foreignkey1_idx` (`accountingTypeFk`),
KEY `Bancoscurrency_idx` (`currencyFk`),
CONSTRAINT `Bancoscurrency` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON UPDATE CASCADE,
CONSTRAINT `accounting_FK` FOREIGN KEY (`entityFk`) REFERENCES `bankEntity` (`id`) ON UPDATE CASCADE,
CONSTRAINT `bank_FK` FOREIGN KEY (`accountingTypeFk`) REFERENCES `accountingType` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `accountingConfig`
--
DROP TABLE IF EXISTS `accountingConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `accountingConfig` (
`id` int(10) unsigned NOT NULL,
`minDate` date NOT NULL,
`maxDate` date NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `accountingConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 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) NOT NULL,
`receiptDescription` varchar(50) DEFAULT NULL COMMENT 'Descripción por defecto al crear nuevo recibo',
`code` varchar(20) DEFAULT NULL,
`isAutoConciliated` tinyint(1) DEFAULT 1 COMMENT 'Si hay que marcar como conciliado el recibo al usar este tipo',
`maxAmount` int(11) DEFAULT NULL,
`daysInFuture` int(11) DEFAULT 0,
PRIMARY KEY (`id`),
KEY `accountingType_code_IDX` (`code`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='descripcio dels valors de la columna "cash" de la taula vn2008.Bancios';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `activityTaxDismissed`
--
DROP TABLE IF EXISTS `activityTaxDismissed`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `activityTaxDismissed` (
`clientFk` int(11) NOT NULL,
`isNotified` tinyint(1) DEFAULT 0,
`isDismissed` tinyint(1) DEFAULT 0,
`notified` int(11) DEFAULT 0,
PRIMARY KEY (`clientFk`),
CONSTRAINT `clientFk` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`street` varchar(255) DEFAULT NULL,
`city` varchar(50) DEFAULT NULL,
`provinceFk` smallint(5) unsigned DEFAULT NULL,
`postalCode` varchar(10) DEFAULT NULL,
`phone` varchar(15) DEFAULT NULL,
`mobile` varchar(15) DEFAULT NULL,
`nickname` varchar(40) DEFAULT NULL,
`isDefaultAddress` tinyint(1) NOT NULL DEFAULT 0,
`agencyModeFk` int(11) NOT NULL DEFAULT 2,
`isActive` tinyint(4) NOT NULL DEFAULT 1,
`longitude` decimal(11,7) DEFAULT NULL COMMENT 'Indica la última longitud proporcionada por tabla delivery',
`latitude` decimal(11,7) DEFAULT NULL COMMENT 'Indica la última latitud proporcionada por tabla delivery',
`isEqualizated` tinyint(1) DEFAULT NULL,
`customsAgentFk` int(11) DEFAULT NULL,
`incotermsFk` varchar(3) DEFAULT NULL,
`isLogifloraAllowed` tinyint(4) NOT NULL DEFAULT 0,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `Id_Agencia` (`agencyModeFk`),
KEY `Id_cliente` (`clientFk`),
KEY `province_id` (`provinceFk`),
KEY `telefono` (`phone`),
KEY `movil` (`mobile`),
KEY `CODPOSTAL` (`postalCode`),
KEY `address_customsAgentFk_idx` (`customsAgentFk`),
KEY `address_incotermsFk_idx` (`incotermsFk`),
KEY `address_fk_editor` (`editorFk`),
CONSTRAINT `address_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE,
CONSTRAINT `address_customsAgentFk` FOREIGN KEY (`customsAgentFk`) REFERENCES `customsAgent` (`id`) ON UPDATE CASCADE,
CONSTRAINT `address_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
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,
CONSTRAINT `address_incotermsFk` FOREIGN KEY (`incotermsFk`) REFERENCES `incoterms` (`code`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `addressFilter`
--
DROP TABLE IF EXISTS `addressFilter`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `addressFilter` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`provinceFk` smallint(5) unsigned DEFAULT NULL,
`countryFk` mediumint(8) unsigned DEFAULT NULL,
`isLogifloraAllowed` tinyint(1) DEFAULT 0,
`isVNHSupplier` tinyint(1) DEFAULT 0 COMMENT 'corresponde al campo edi.VMPSettings.isVNHSupplier',
`isEarlyBird` tinyint(1) DEFAULT 0 COMMENT 'corresponde al campo edi.marketPlace.isEarlybird',
`warehouseFk` smallint(5) unsigned DEFAULT NULL,
`beforeDated` date DEFAULT NULL,
`afterDated` date DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `addressFilter_FK` (`provinceFk`),
KEY `addressFilter_FK_1` (`countryFk`),
KEY `addressFilter_FK_2` (`warehouseFk`),
CONSTRAINT `addressFilter_FK` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `addressFilter_FK_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `addressFilter_FK_2` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Establece los criterios para habilitar las compras directas a Logiflora';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `addressForPackaging`
--
DROP TABLE IF EXISTS `addressForPackaging`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `addressForPackaging` (
`addressFk` int(11) NOT NULL,
`packagingValue` decimal(10,2) NOT NULL DEFAULT 0.04,
PRIMARY KEY (`addressFk`),
CONSTRAINT `addresForPackaging_fk1` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Observaciones de los consignatarios';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `addressShortage`
--
DROP TABLE IF EXISTS `addressShortage`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `addressShortage` (
`addressFk` int(11) NOT NULL,
PRIMARY KEY (`addressFk`),
CONSTRAINT `addressShortage_FK` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `agency`
--
DROP TABLE IF EXISTS `agency`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agency` (
`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(25) NOT NULL,
`warehouseFk` smallint(5) unsigned DEFAULT NULL COMMENT 'A nulo si se puede enrutar desde todos los almacenes',
`warehouseAliasFk__` smallint(5) unsigned DEFAULT NULL COMMENT '@deprecated 2024-01-23 refs #5167',
`isOwn` tinyint(1) NOT NULL DEFAULT 0,
`workCenterFk` int(11) DEFAULT NULL,
`isAnyVolumeAllowed` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Permite vender productos que tengan vn.itemType.IsUnconventionalSize = TRUE',
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `warehouse_id` (`warehouseFk`),
KEY `agencias_alias_idx` (`warehouseAliasFk__`),
KEY `agency_ibfk_3_idx` (`workCenterFk`),
KEY `agency_user_FK` (`editorFk`),
CONSTRAINT `agency_FK` FOREIGN KEY (`warehouseAliasFk__`) REFERENCES `warehouseAlias__` (`id`) ON UPDATE CASCADE,
CONSTRAINT `agency_ibfk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
CONSTRAINT `agency_ibfk_3` FOREIGN KEY (`workCenterFk`) REFERENCES `workCenter` (`id`) ON UPDATE CASCADE,
CONSTRAINT `agency_user_FK` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `agencyExtraCharge`
--
DROP TABLE IF EXISTS `agencyExtraCharge`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agencyExtraCharge` (
`id` int(11) NOT NULL,
`agencyFk` smallint(5) unsigned NOT NULL,
`sizeMin` int(11) NOT NULL COMMENT 'suma de x + y + z a partir del cual se cobrará el sobrecoste',
`sizeMax` int(11) NOT NULL COMMENT 'suma de x + y + z a hasta el cual se cobrará el sobrecoste',
`sinced` date NOT NULL COMMENT 'desde la cual se aplica',
`price` decimal(10,2) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `agencyExtraChargeUniqueIdx` (`agencyFk`,`sinced`,`sizeMin`),
CONSTRAINT `agencyExtraChargeFk1` FOREIGN KEY (`agencyFk`) REFERENCES `agency` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `agencyLog`
--
DROP TABLE IF EXISTS `agencyLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agencyLog` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`originFk` smallint(5) unsigned DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete','select') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` enum('agency','agencyMode') NOT NULL DEFAULT 'agency',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `logAgencyUserFk` (`userFk`),
KEY `agencyLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `agencyLog_originFk` (`originFk`,`creationDate`),
CONSTRAINT `agencyOriginFk` FOREIGN KEY (`originFk`) REFERENCES `agency` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `agencyUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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) DEFAULT NULL,
`description` varchar(50) DEFAULT NULL,
`deliveryMethodFk` int(11) DEFAULT NULL,
`m3` double DEFAULT 0,
`web` smallint(1) unsigned zerofill NOT NULL DEFAULT 0,
`agencyFk` smallint(5) unsigned NOT NULL,
`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) 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 DEFAULT NULL COMMENT 'obsoleta',
`code` varchar(45) DEFAULT NULL,
`isRiskFree` tinyint(1) NOT NULL DEFAULT 0,
`hasWeightVolumetric` int(11) NOT NULL DEFAULT 0 COMMENT 'Tiene en cuenta el peso volumetrico para los calculos',
PRIMARY KEY (`id`),
KEY `Agencias` (`name`),
KEY `Vista` (`deliveryMethodFk`),
KEY `agencyMode_agencyFk` (`agencyFk`),
KEY `agencyMode_code` (`code`),
CONSTRAINT `agencyMode_agencyFk` FOREIGN KEY (`agencyFk`) REFERENCES `agency` (`id`) ON UPDATE CASCADE,
CONSTRAINT `agencyMode_deliveryMethodFk` FOREIGN KEY (`deliveryMethodFk`) REFERENCES `deliveryMethod` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `agencyModeItemType`
--
DROP TABLE IF EXISTS `agencyModeItemType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agencyModeItemType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`agencyModeFk` int(11) NOT NULL,
`itemTypeFk` smallint(5) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `agencyModeFk_ItemType_UNIQUE` (`agencyModeFk`,`itemTypeFk`),
KEY `agencyModeItemType_FK_1` (`itemTypeFk`),
CONSTRAINT `agencyModeItemType_FK` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `agencyModeItemType_FK_1` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Combinaciones prohibidas entre agencyMode e itemType al calcular el catálogo de items';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `agencyModePricePercentage`
--
DROP TABLE IF EXISTS `agencyModePricePercentage`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agencyModePricePercentage` (
`agencyModeFk` int(11) NOT NULL,
`percentage` double NOT NULL,
PRIMARY KEY (`agencyModeFk`),
CONSTRAINT `agencyModePricePercentage_FK` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `agencyTerm`
--
DROP TABLE IF EXISTS `agencyTerm`;
/*!50001 DROP VIEW IF EXISTS `agencyTerm`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `agencyTerm` AS SELECT
1 AS `agencyFk`,
1 AS `minimumPackages`,
1 AS `kmPrice`,
1 AS `packagePrice`,
1 AS `routePrice`,
1 AS `minimumKm`,
1 AS `minimumM3`,
1 AS `m3Price` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `agencyTermConfig`
--
DROP TABLE IF EXISTS `agencyTermConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agencyTermConfig` (
`expenseFk` varchar(10) DEFAULT NULL,
`vatAccountSupported` varchar(15) DEFAULT NULL,
`vatPercentage` decimal(28,10) DEFAULT NULL,
`transaction` varchar(50) DEFAULT NULL,
KEY `agencyTermConfig_expense_FK` (`expenseFk`),
CONSTRAINT `agencyTermConfig_expense_FK` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `agencyWorkCenter`
--
DROP TABLE IF EXISTS `agencyWorkCenter`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agencyWorkCenter` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`agencyFk` smallint(5) unsigned NOT NULL,
`workCenterFk` int(11) NOT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `agencyWorkCenter_unique` (`agencyFk`,`workCenterFk`),
KEY `agencyWorkCenter_workCenter_FK` (`workCenterFk`),
KEY `agencyWorkCenter_user_FK` (`editorFk`),
CONSTRAINT `agencyWorkCenter_agency_FK` FOREIGN KEY (`agencyFk`) REFERENCES `agency` (`id`) ON DELETE CASCADE,
CONSTRAINT `agencyWorkCenter_user_FK` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `agencyWorkCenter_workCenter_FK` FOREIGN KEY (`workCenterFk`) REFERENCES `workCenter` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `airline`
--
DROP TABLE IF EXISTS `airline`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `airline` (
`id` smallint(2) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `airport`
--
DROP TABLE IF EXISTS `airport`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `airport` (
`id` smallint(2) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`id` int(11) NOT NULL,
`hasToRecalcPrice` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `amortizationType`
--
DROP TABLE IF EXISTS `amortizationType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `amortizationType` (
`code` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `arcRead`
--
DROP TABLE IF EXISTS `arcRead`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `arcRead` (
`id` smallint(2) unsigned NOT NULL AUTO_INCREMENT,
`printerFk` int(10) unsigned DEFAULT NULL,
`ip` varchar(50) NOT NULL,
`counter` smallint(2) unsigned DEFAULT NULL COMMENT 'Número de etiquetas leídas del pallet actual por el arco',
`error` varchar(50) DEFAULT NULL,
`minimum` tinyint(4) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `arcRead_ip_UN` (`ip`),
KEY `arcRead_FK` (`printerFk`),
CONSTRAINT `arcRead_FK` FOREIGN KEY (`printerFk`) REFERENCES `printer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `assignedTicketToWorker`
--
DROP TABLE IF EXISTS `assignedTicketToWorker`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `assignedTicketToWorker` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`idWorker` int(11) DEFAULT NULL,
`idTicket` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `idWorker_UNIQUE` (`idWorker`),
UNIQUE KEY `idTicket_UNIQUE` (`idTicket`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `auctionConfig`
--
DROP TABLE IF EXISTS `auctionConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `auctionConfig` (
`id` int(10) unsigned NOT NULL,
`conversionCoefficient` double NOT NULL DEFAULT 1 COMMENT 'value used to calculate the used space of an item in a container',
`warehouseFk` smallint(6) unsigned NOT NULL DEFAULT 7 COMMENT 'Default warehouse used for the calculation',
PRIMARY KEY (`id`),
KEY `auctionConfig_FK` (`warehouseFk`),
CONSTRAINT `auctionConfig_FK` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`),
CONSTRAINT `auctionConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!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(10) unsigned NOT NULL,
`password` varchar(45) DEFAULT NULL,
`user` varchar(45) DEFAULT NULL,
`url` varchar(75) DEFAULT NULL,
`client` int(32) DEFAULT NULL,
`center` varchar(2) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `autoRadioConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `autonomy`
--
DROP TABLE IF EXISTS `autonomy`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `autonomy` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`countryFk` mediumint(8) unsigned NOT NULL,
`geoFk` int(11) DEFAULT NULL,
`isUeeMember` tinyint(1) DEFAULT NULL,
`hasDailyInvoice` tinyint(4) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `autonomy_FK` (`countryFk`),
KEY `autonomy_FK_1` (`geoFk`),
CONSTRAINT `autonomy_FK` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `autonomy_FK_1` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Comunidades autónomas o su equivalente en otros paises. Agrupación de provincias, en una categoria inferior a country.';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `awb`
--
DROP TABLE IF EXISTS `awb`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awb` (
`id` smallint(11) unsigned NOT NULL AUTO_INCREMENT,
`code` varchar(18) NOT NULL,
`package` float unsigned NOT NULL,
`weight` float unsigned DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`transitoryFk` int(10) unsigned DEFAULT NULL,
`taxFk` int(10) unsigned DEFAULT 62,
`duakk` varchar(18) DEFAULT NULL,
`docFk` int(11) DEFAULT NULL,
`amount` double NOT NULL DEFAULT 0,
`freightFk` int(10) unsigned DEFAULT NULL,
`m3` double unsigned DEFAULT NULL,
`stems` int(10) unsigned DEFAULT NULL,
`flightFk` varchar(10) DEFAULT NULL,
`volumeWeight` float unsigned DEFAULT NULL,
`hb` decimal(10,1) unsigned DEFAULT NULL,
`rate` decimal(10,2) unsigned DEFAULT NULL,
`booked` datetime DEFAULT NULL,
`issued` datetime DEFAULT NULL,
`operated` datetime DEFAULT NULL,
`bookEntried` date DEFAULT NULL,
`invoiceInFk` mediumint(8) unsigned DEFAULT NULL,
`isChecked` tinyint(3) DEFAULT 0,
`isTransitoryChecked` tinyint(3) DEFAULT 0,
`year` int(4) DEFAULT NULL,
`observation` varchar(45) DEFAULT NULL,
`hasFreightPrepaid` tinyint(3) DEFAULT 0,
`invoiceInPaletizedFk` mediumint(8) unsigned DEFAULT NULL,
`propertyNumber` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `codigo_UNIQUE` (`code`,`year`),
KEY `proveedor_id` (`transitoryFk`),
KEY `iva_id` (`taxFk`),
KEY `carguera_id` (`freightFk`),
KEY `flight_id` (`flightFk`),
KEY `awbInvoiceIn` (`invoiceInFk`),
KEY `awb_FK` (`docFk`),
KEY `awb_FK_3` (`invoiceInPaletizedFk`),
CONSTRAINT `awbInvoiceIn` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `awb_FK` FOREIGN KEY (`docFk`) REFERENCES `dms` (`id`) ON UPDATE CASCADE,
CONSTRAINT `awb_FK_1` FOREIGN KEY (`flightFk`) REFERENCES `flight` (`id`) ON UPDATE CASCADE,
CONSTRAINT `awb_FK_3` FOREIGN KEY (`invoiceInPaletizedFk`) REFERENCES `invoiceIn` (`id`) ON UPDATE CASCADE,
CONSTRAINT `awb_ibfk_1` FOREIGN KEY (`taxFk`) REFERENCES `taxCode` (`id`) ON UPDATE CASCADE,
CONSTRAINT `awb_supplierFk` FOREIGN KEY (`transitoryFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `awbComponent`
--
DROP TABLE IF EXISTS `awbComponent`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awbComponent` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`awbFk` smallint(11) unsigned DEFAULT NULL,
`supplierFk` int(11) NOT NULL,
`dated__` date NOT NULL,
`typeFk` mediumint(3) unsigned DEFAULT NULL,
`awbRoleFk` tinyint(1) unsigned NOT NULL DEFAULT 1,
`awbUnitFk` varchar(10) DEFAULT NULL,
`value` decimal(10,2) DEFAULT NULL,
`currencyFk` tinyint(3) unsigned NOT NULL DEFAULT 2,
`invoiceInFk` mediumint(8) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_idx` (`awbFk`,`supplierFk`,`typeFk`),
KEY `Id_Moneda` (`currencyFk`),
KEY `awb_component_fk` (`typeFk`),
KEY `awb_role_fk` (`awbRoleFk`),
KEY `awb_unit_fk` (`awbUnitFk`),
CONSTRAINT `Id_Monedafk` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON DELETE CASCADE,
CONSTRAINT `awb_component_` FOREIGN KEY (`typeFk`) REFERENCES `awbComponentType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `awb_role_fk` FOREIGN KEY (`awbRoleFk`) REFERENCES `awbRole` (`id`) ON UPDATE CASCADE,
CONSTRAINT `awb_unit_fk` FOREIGN KEY (`awbUnitFk`) REFERENCES `awbUnit` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `awbComponentTemplate`
--
DROP TABLE IF EXISTS `awbComponentTemplate`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awbComponentTemplate` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`freightFk` int(11) DEFAULT NULL,
`airportIn` varchar(3) DEFAULT NULL,
`airportOut` varchar(3) DEFAULT NULL,
`airlineFk` smallint(2) unsigned DEFAULT NULL,
`typeFk` mediumint(3) unsigned NOT NULL,
`dated` date NOT NULL,
`awbRoleFk` tinyint(1) unsigned NOT NULL,
`awbUnit` varchar(10) DEFAULT NULL,
`value` decimal(10,3) DEFAULT NULL,
`maxValue` decimal(10,2) unsigned DEFAULT NULL,
`minValue` decimal(10,2) unsigned DEFAULT NULL,
`currencyFk` tinyint(3) unsigned NOT NULL DEFAULT 2,
`days` varchar(7) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `carguera_id_UNIQUE` (`freightFk`,`airportIn`,`airportOut`,`airlineFk`,`typeFk`,`dated`,`days`),
KEY `Id_Moneda` (`currencyFk`),
KEY `airline_idx` (`airlineFk`),
KEY `role_idx` (`awbRoleFk`),
KEY `awb_unit_fk1` (`awbUnit`),
KEY `awb_component_template_FK` (`typeFk`),
CONSTRAINT `Id_Moneda` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON UPDATE CASCADE,
CONSTRAINT `awb_component_template_FK` FOREIGN KEY (`typeFk`) REFERENCES `awbComponentType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `awb_component_template_FK_1` FOREIGN KEY (`airlineFk`) REFERENCES `airline` (`id`) ON UPDATE CASCADE,
CONSTRAINT `awb_unit_fk1` FOREIGN KEY (`awbUnit`) REFERENCES `awbUnit` (`id`) ON UPDATE CASCADE,
CONSTRAINT `role_fk` FOREIGN KEY (`awbRoleFk`) REFERENCES `awbRole` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `awbComponentType`
--
DROP TABLE IF EXISTS `awbComponentType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awbComponentType` (
`id` mediumint(3) unsigned NOT NULL AUTO_INCREMENT,
`description` varchar(45) DEFAULT NULL,
`hasStems` tinyint(1) NOT NULL DEFAULT 1,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT=' ';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `awbDms`
--
DROP TABLE IF EXISTS `awbDms`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awbDms` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`awbFk` smallint(11) unsigned NOT NULL,
`dmsFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `awb_gestdoc_awb_fk` (`awbFk`),
KEY `awb_gestdoc_gestdoc_fk` (`dmsFk`),
CONSTRAINT `awb_gestdoc_awb_fk` FOREIGN KEY (`awbFk`) REFERENCES `awb` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `awb_gestdoc_gestdoc_fk` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `awbInvoiceIn`
--
DROP TABLE IF EXISTS `awbInvoiceIn`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awbInvoiceIn` (
`awbFk` smallint(5) unsigned NOT NULL,
`invoiceInFk` mediumint(8) unsigned NOT NULL,
`sad` varchar(18) DEFAULT NULL,
PRIMARY KEY (`invoiceInFk`),
KEY `awb_id` (`awbFk`),
CONSTRAINT `awbInvoiceIn_ibfk_1` FOREIGN KEY (`awbFk`) REFERENCES `awb` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `awbInvoiceIn_ibfk_2` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `awbRole`
--
DROP TABLE IF EXISTS `awbRole`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awbRole` (
`id` tinyint(1) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT=' ';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `awbUnit`
--
DROP TABLE IF EXISTS `awbUnit`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `awbUnit` (
`id` varchar(10) NOT NULL DEFAULT '',
`operation` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='tipos de unidades';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `awbVolume`
--
DROP TABLE IF EXISTS `awbVolume`;
/*!50001 DROP VIEW IF EXISTS `awbVolume`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `awbVolume` AS SELECT
1 AS `awbFk`,
1 AS `volume`,
1 AS `buyFk` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `balanceNestTree`
--
DROP TABLE IF EXISTS `balanceNestTree`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `balanceNestTree` (
`lft` int(11) DEFAULT NULL,
`rgt` int(11) DEFAULT NULL,
`name` text DEFAULT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`isSelected` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `balanceNestTree_expense_FK` (`expenseFk`),
CONSTRAINT `balanceNestTree_expense_FK` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!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) NOT NULL,
`bic` varchar(11) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `fg_entity1_idx` (`countryFk`),
CONSTRAINT `fg_entity1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Entidades bancarias ';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `bankEntityConfig`
--
DROP TABLE IF EXISTS `bankEntityConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bankEntityConfig` (
`id` int(10) unsigned NOT NULL,
`bicLength` tinyint(4) DEFAULT 11 COMMENT 'Tamaño del campo bic',
`defaultBankId` int(11) NOT NULL DEFAULT 3117 COMMENT 'Id del banco por defecto',
PRIMARY KEY (`id`),
CONSTRAINT `bankEntityConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `bankErrorCode`
--
DROP TABLE IF EXISTS `bankErrorCode`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bankErrorCode` (
`code` char(5) NOT NULL,
`description` varchar(255) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla de códigos de error bancario';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `bankPolicy`
--
DROP TABLE IF EXISTS `bankPolicy`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bankPolicy` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ref` varchar(45) DEFAULT NULL,
`amount` double NOT NULL,
`committedFee` double DEFAULT NULL,
`nonCommittedFee` double DEFAULT NULL,
`annualFee` double DEFAULT NULL,
`started` date NOT NULL,
`ended` date DEFAULT NULL,
`accountingFk` int(11) NOT NULL,
`companyFk` int(10) unsigned NOT NULL DEFAULT 442,
`supplierFk` int(10) unsigned DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`hasGuarantee` tinyint(1) NOT NULL DEFAULT 0,
`dmsFk` int(11) DEFAULT NULL,
`notaryFk` int(10) unsigned DEFAULT NULL,
`currencyFk` tinyint(3) unsigned DEFAULT 2,
`amortizationTypeFk` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`periodicityTypeFk` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`insuranceExpired` date DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `Id_Banco_Poliza_idx` (`accountingFk`),
KEY `Id_Poliza_Empresa_idx` (`companyFk`),
KEY `bankSupplierIdx1_idx` (`supplierFk`),
KEY `bankDmsIdx2_idx` (`dmsFk`),
KEY `bankNotaryIdx3_idx` (`notaryFk`),
KEY `asdf_idx` (`amortizationTypeFk`),
KEY `bankPeriodicityIdx4_idx` (`periodicityTypeFk`),
CONSTRAINT `Bancos_polizaCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `Bancos_poliza_notaryFk` FOREIGN KEY (`notaryFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE,
CONSTRAINT `Bancos_poliza_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE,
CONSTRAINT `Id_Banco_Poliza` FOREIGN KEY (`accountingFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE,
CONSTRAINT `asdf` FOREIGN KEY (`amortizationTypeFk`) REFERENCES `amortizationType` (`code`) ON UPDATE CASCADE,
CONSTRAINT `bankDmsIdx2` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON UPDATE CASCADE,
CONSTRAINT `bankPeriodicityIdx4` FOREIGN KEY (`periodicityTypeFk`) REFERENCES `periodicityType` (`code`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lineas de credito asociadas a cuentas corrientes';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `bankPolicyDetail`
--
DROP TABLE IF EXISTS `bankPolicyDetail`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bankPolicyDetail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`bankPolicyFk` int(11) NOT NULL,
`installmentNumber` int(11) NOT NULL,
`dueDated` date NOT NULL,
`netAmount` decimal(10,2) DEFAULT NULL,
`amortization` decimal(10,2) DEFAULT NULL,
`outstanding` decimal(10,2) DEFAULT NULL,
`rate` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Detalle de las cuotas';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `bankPolicyReview`
--
DROP TABLE IF EXISTS `bankPolicyReview`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bankPolicyReview` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`bankPolicyFk` int(11) NOT NULL,
`amount` double NOT NULL,
`rate` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Revisiones del euribor';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `beach`
--
DROP TABLE IF EXISTS `beach`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `beach` (
`code` varchar(45) NOT NULL,
`warehouseFk` smallint(6) NOT NULL DEFAULT 60,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Ubicaciones respecto a la playa del almacén';
/*!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(10) unsigned NOT NULL,
`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`),
CONSTRAINT `bionicConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`taxAreaFk` varchar(15) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'SPAIN',
`priority` int(2) unsigned DEFAULT NULL,
`taxClassFk` tinyint(3) unsigned NOT NULL DEFAULT 1,
`countryFk` mediumint(8) unsigned NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
KEY `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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`description` varchar(45) DEFAULT NULL,
`isProtectedZone` tinyint(1) NOT NULL DEFAULT 0,
`code` enum('importProhibited','phytosanitaryPassport','individualPassport') DEFAULT NULL,
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #4419 Deprecated 2023-07-20';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `budget`
--
DROP TABLE IF EXISTS `budget`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `budget` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`name` varchar(100) NOT NULL,
`started` date DEFAULT NULL,
`finished` date DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`departmentFk` int(11) DEFAULT NULL,
`supplierFk` int(10) unsigned DEFAULT NULL,
`photo` blob DEFAULT NULL,
`amount` decimal(10,2) DEFAULT NULL,
`projectFk` int(11) NOT NULL,
`budgetStateFk` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `budget_FK` (`projectFk`),
KEY `budget_FK_1` (`userFk`),
KEY `budget_FK_2` (`departmentFk`),
KEY `budget_supplierFk` (`supplierFk`),
KEY `budgetStateFk` (`budgetStateFk`),
CONSTRAINT `budgetStateFk` FOREIGN KEY (`budgetStateFk`) REFERENCES `budgetState` (`code`) ON UPDATE CASCADE,
CONSTRAINT `budget_FK` FOREIGN KEY (`projectFk`) REFERENCES `project` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `budget_FK_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `budget_FK_2` FOREIGN KEY (`departmentFk`) REFERENCES `department` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `budget_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Master de presupuestos de project';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `budgetDms`
--
DROP TABLE IF EXISTS `budgetDms`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `budgetDms` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`budgetFk` int(11) NOT NULL,
`dmsFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `budgetDms_FK` (`budgetFk`),
KEY `budgetDms_FK_1` (`dmsFk`),
CONSTRAINT `budgetDms_FK` FOREIGN KEY (`budgetFk`) REFERENCES `budget` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `budgetDms_FK_1` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Gestion documental de budget';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `budgetInvoiceIn`
--
DROP TABLE IF EXISTS `budgetInvoiceIn`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `budgetInvoiceIn` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`budgetFk` int(11) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`invoiceInFk` mediumint(8) unsigned NOT NULL,
`amount` decimal(10,2) NOT NULL,
PRIMARY KEY (`id`),
KEY `budgetInvoiceIn_FK` (`budgetFk`),
KEY `budgetInvoiceIn_FK_1` (`invoiceInFk`),
CONSTRAINT `budgetInvoiceIn_FK` FOREIGN KEY (`budgetFk`) REFERENCES `budget` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `budgetInvoiceIn_FK_1` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Facturas relativas al presupuesto';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `budgetNotes`
--
DROP TABLE IF EXISTS `budgetNotes`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `budgetNotes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`budgetFk` int(11) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`txt` varchar(255) NOT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `budgetNotes_FK` (`budgetFk`),
KEY `budgetNotes_FK_2` (`userFk`),
CONSTRAINT `budgetNotes_FK` FOREIGN KEY (`budgetFk`) REFERENCES `budget` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `budgetNotes_FK_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Historico de budget';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `budgetState`
--
DROP TABLE IF EXISTS `budgetState`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `budgetState` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`code` varchar(45) NOT NULL,
`description` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `budgetState_UN` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!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` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`companyCodeFk` char(3) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`started` date DEFAULT NULL,
`ended` date DEFAULT NULL,
`workerBusiness` longtext DEFAULT NULL,
`reasonEndFk` int(11) DEFAULT NULL,
`payedHolidays` decimal(5,2) NOT NULL DEFAULT 0.00,
`occupationCodeFk` varchar(1) DEFAULT NULL,
`workerFk` int(10) unsigned NOT NULL,
`notes` longtext DEFAULT NULL,
`departmentFk` int(11) DEFAULT NULL,
`workerBusinessProfessionalCategoryFk` int(11) DEFAULT NULL,
`calendarTypeFk` int(11) DEFAULT 1,
`isHourlyLabor` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Contrato por horas',
`workcenterFk` int(11) NOT NULL DEFAULT 9,
`rate` int(11) DEFAULT NULL,
`workerBusinessCategoryFk` int(11) DEFAULT NULL,
`workerBusinessTypeFk` int(11) DEFAULT NULL,
`amount` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Importe pactado',
`workerBusinessAgreementFk` int(11) DEFAULT NULL,
`basicSalary` decimal(10,2) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `business_occupationCodeFk` (`occupationCodeFk`),
KEY `business_companyCodeFk` (`companyCodeFk`),
KEY `business_workerFk_idx` (`workerFk`),
KEY `business_departmentFk_idx` (`departmentFk`),
KEY `business_workerBusinessProfessionalCategoryFk_idx` (`workerBusinessProfessionalCategoryFk`),
KEY `business_calendarTypeFk_idx` (`calendarTypeFk`),
KEY `business_workerBusinessCategoryFk` (`workerBusinessCategoryFk`),
KEY `business_workerBusinessTypeFk_idx` (`workerBusinessTypeFk`),
KEY `business_workerBusinessAgreementFk_idx` (`workerBusinessAgreementFk`),
KEY `business_workcenterFk_idx` (`workcenterFk`),
KEY `business_fk_editor` (`editorFk`),
CONSTRAINT `business_FK` FOREIGN KEY (`workerBusinessProfessionalCategoryFk`) REFERENCES `professionalCategory` (`id`) ON UPDATE CASCADE,
CONSTRAINT `business_calendarTypeFk` FOREIGN KEY (`calendarTypeFk`) REFERENCES `calendarType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `business_departmentFk` FOREIGN KEY (`departmentFk`) REFERENCES `department` (`id`) ON UPDATE CASCADE,
CONSTRAINT `business_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `business_occupationCodeFk` FOREIGN KEY (`occupationCodeFk`) REFERENCES `occupationCode` (`code`) ON UPDATE CASCADE,
CONSTRAINT `business_workcenterFk` FOREIGN KEY (`workcenterFk`) REFERENCES `workCenter` (`id`) ON UPDATE CASCADE,
CONSTRAINT `business_workerBusinessAgreementFk` FOREIGN KEY (`workerBusinessAgreementFk`) REFERENCES `workerBusinessAgreement` (`id`) ON UPDATE CASCADE,
CONSTRAINT `business_workerBusinessCategoryFk` FOREIGN KEY (`workerBusinessCategoryFk`) REFERENCES `payrollCategories` (`id`) ON UPDATE CASCADE,
CONSTRAINT `business_workerBusinessTypeFk` FOREIGN KEY (`workerBusinessTypeFk`) REFERENCES `workerBusinessType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `business_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `businessCalendar`
--
DROP TABLE IF EXISTS `businessCalendar`;
/*!50001 DROP VIEW IF EXISTS `businessCalendar`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `businessCalendar` AS SELECT
1 AS `id`,
1 AS `businessFk`,
1 AS `absenceTypeFk`,
1 AS `dated` */;
SET character_set_client = @saved_cs_client;
--
-- 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) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `businessSchedule`
--
DROP TABLE IF EXISTS `businessSchedule`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `businessSchedule` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`weekday` smallint(6) NOT NULL DEFAULT 1 COMMENT 'Lunes = 1 \nDomingo = 7',
`started` time DEFAULT NULL,
`ended` time DEFAULT NULL,
`businessFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `day_id` (`weekday`,`started`,`ended`,`businessFk`),
KEY `journey_business_id_idx` (`businessFk`),
CONSTRAINT `journey_business_id` FOREIGN KEY (`businessFk`) REFERENCES `business` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `businessType`
--
DROP TABLE IF EXISTS `businessType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `businessType` (
`code` varchar(100) NOT NULL DEFAULT '',
`description` varchar(100) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,4) NOT NULL DEFAULT 0.0000,
`freightValue` decimal(10,3) NOT NULL DEFAULT 0.000,
`isIgnored` tinyint(1) NOT NULL DEFAULT 0,
`stickers` int(11) NOT NULL DEFAULT 0,
`packing` int(11) NOT NULL DEFAULT 1 CHECK (`packing` > 0),
`grouping` smallint(5) unsigned NOT NULL DEFAULT 1,
`groupingMode` enum('grouping','packing') DEFAULT NULL,
`containerFk` smallint(5) unsigned DEFAULT NULL,
`comissionValue` decimal(10,3) NOT NULL DEFAULT 0.000,
`packageValue` decimal(10,3) NOT NULL DEFAULT 0.000,
`location` varchar(5) DEFAULT NULL,
`packagingFk` varchar(10) 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,
`printedStickers` int(10) unsigned NOT NULL 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,
`deliveryFk` int(11) DEFAULT NULL,
`itemOriginalFk` int(11) DEFAULT NULL COMMENT 'Item original de la entrada',
`editorFk` int(10) unsigned DEFAULT NULL,
`buyerFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `CompresId_Trabajador` (`workerFk`),
KEY `Id_Cubo` (`packagingFk`),
KEY `Id_Entrada` (`entryFk`),
KEY `container_id` (`containerFk`),
KEY `buy_edi_id` (`ektFk`),
KEY `itemFk_entryFk` (`itemFk`,`entryFk`),
KEY `buy_fk_4_idx` (`deliveryFk`),
KEY `buy_FK` (`itemOriginalFk`),
KEY `buy_itemFk_IDX` (`itemFk`) USING BTREE,
KEY `buy_fk_editor` (`editorFk`),
CONSTRAINT `buy_FK` FOREIGN KEY (`itemOriginalFk`) REFERENCES `item` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `buy_FK_1` FOREIGN KEY (`containerFk`) REFERENCES `vn2008`.`container__` (`container_id`) ON UPDATE CASCADE,
CONSTRAINT `buy_ektFk` FOREIGN KEY (`ektFk`) REFERENCES `edi`.`ekt` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `buy_fk_4` FOREIGN KEY (`deliveryFk`) REFERENCES `edi`.`deliveryInformation` (`ID`) ON DELETE SET NULL ON UPDATE SET NULL,
CONSTRAINT `buy_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `buy_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE,
CONSTRAINT `buy_ibfk_2` FOREIGN KEY (`packagingFk`) 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci ROW_FORMAT=DYNAMIC;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `buyConfig`
--
DROP TABLE IF EXISTS `buyConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `buyConfig` (
`id` int(10) unsigned NOT NULL,
`monthsAgo` int(11) NOT NULL DEFAULT 6 COMMENT 'Meses desde la última compra',
PRIMARY KEY (`id`),
CONSTRAINT `buyConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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) 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=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `buyer`
--
DROP TABLE IF EXISTS `buyer`;
/*!50001 DROP VIEW IF EXISTS `buyer`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `buyer` AS SELECT
1 AS `userFk`,
1 AS `nickname` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `buyerSales`
--
DROP TABLE IF EXISTS `buyerSales`;
/*!50001 DROP VIEW IF EXISTS `buyerSales`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `buyerSales` AS SELECT
1 AS `importe`,
1 AS `comprador`,
1 AS `año`,
1 AS `semana` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `calendar`
--
DROP TABLE IF EXISTS `calendar`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `calendar` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`businessFk` int(11) NOT NULL,
`dayOffTypeFk` int(11) NOT NULL,
`dated` date NOT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `calendar_UN` (`businessFk`,`dated`),
KEY `calendar_employee_business_labour_id_idx` (`businessFk`),
KEY `calendar_employee_calendar_state_calendar_state_id_idx` (`dayOffTypeFk`),
KEY `id_index` (`id`),
CONSTRAINT `calendar_FK` FOREIGN KEY (`dayOffTypeFk`) REFERENCES `absenceType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `calendar_businessFk` FOREIGN KEY (`businessFk`) REFERENCES `business` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_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` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`calendarHolidaysTypeFk` int(11) NOT NULL,
`dated` date NOT NULL,
`calendarHolidaysNameFk` int(11) DEFAULT NULL,
`workCenterFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `calendarHolidays_UN` (`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=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `calendarHolidaysName`
--
DROP TABLE IF EXISTS `calendarHolidaysName`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `calendarHolidaysName` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `calendarHolidaysType`
--
DROP TABLE IF EXISTS `calendarHolidaysType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `calendarHolidaysType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`hexColour` char(7) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `calendarType`
--
DROP TABLE IF EXISTS `calendarType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `calendarType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(50) DEFAULT NULL,
`hoursWeek` smallint(6) unsigned DEFAULT NULL,
`isPartial` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `hours_labour_hours_labour_id_key` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `campaign`
--
DROP TABLE IF EXISTS `campaign`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `campaign` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` enum('mothersDay','allSaints','valentinesDay') NOT NULL,
`dated` datetime NOT NULL DEFAULT current_timestamp(),
`scopeDays` int(11) NOT NULL DEFAULT 15,
PRIMARY KEY (`id`),
UNIQUE KEY `campaign_dated_uindex` (`dated`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!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) NOT NULL,
`nick` varchar(3) NOT NULL,
`name` varchar(45) GENERATED ALWAYS AS (`description`) VIRTUAL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`rappel` decimal(5,2) NOT NULL DEFAULT 0.00,
`componentFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `chain_FK` (`componentFk`),
CONSTRAINT `chain_FK` FOREIGN KEY (`componentFk`) REFERENCES `component` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Grupos de clientes';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `chat`
--
DROP TABLE IF EXISTS `chat`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `chat` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`senderFk` int(10) unsigned DEFAULT NULL,
`recipient` varchar(50) DEFAULT NULL,
`dated` datetime DEFAULT NULL,
`checkUserStatus` tinyint(1) DEFAULT NULL,
`message` text DEFAULT NULL,
`status__` tinyint(1) DEFAULT NULL,
`attempts` int(1) DEFAULT NULL,
`error` text DEFAULT NULL,
`status` enum('pending','sent','error','sending') NOT NULL DEFAULT 'pending',
PRIMARY KEY (`id`),
KEY `chat_FK` (`senderFk`),
CONSTRAINT `chat_FK` FOREIGN KEY (`senderFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!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(10) unsigned NOT NULL,
`host` varchar(255) NOT NULL,
`api` varchar(255) NOT NULL,
`user` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `chatConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`claimStateFk` int(10) unsigned NOT NULL DEFAULT 1,
`observation` text DEFAULT NULL,
`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,
`pickup` enum('agency','delivery') DEFAULT NULL,
`packages` smallint(10) unsigned DEFAULT 0 COMMENT 'packages received by the client',
`rma__` varchar(100) DEFAULT NULL,
`responsabilityRate` decimal(3,2) GENERATED ALWAYS AS ((5 - `responsibility`) / 4) VIRTUAL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `cl_est_id` (`claimStateFk`),
KEY `Id_Cliente` (`clientFk`),
KEY `Id_Trabajador` (`workerFk`),
KEY `cl_main_ticketFk_idx` (`ticketFk`),
KEY `claim_fk_editor` (`editorFk`),
CONSTRAINT `cl_main_ticketFk` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON UPDATE CASCADE,
CONSTRAINT `claim_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `claim_ibfk_3` FOREIGN KEY (`claimStateFk`) REFERENCES `claimState` (`id`) ON UPDATE CASCADE,
CONSTRAINT `claim_ibfk_5` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`quantity` double DEFAULT 0,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `Id_Movimiento` (`saleFk`),
KEY `cl_main_id` (`claimFk`),
KEY `claimBeginning_fk_editor` (`editorFk`),
CONSTRAINT `claimBeginning_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Detalle de las reclamaciones';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `claimConfig`
--
DROP TABLE IF EXISTS `claimConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `claimConfig` (
`id` int(10) unsigned NOT NULL,
`maxResponsibility` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `claimConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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) 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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(10) unsigned 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,
`editorFk` int(10) unsigned DEFAULT NULL,
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`),
KEY `claimDevelopment_fk_editor` (`editorFk`),
CONSTRAINT `claimDevelopment_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`claimFk`,`dmsFk`),
KEY `dmsFk_idx` (`dmsFk`),
KEY `claimDms_fk_editor` (`editorFk`),
CONSTRAINT `claimDms_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
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=utf8mb3 COLLATE=utf8mb3_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(10) unsigned NOT NULL DEFAULT 20,
`claimDestinationFk` tinyint(4) DEFAULT NULL,
`isGreuge` tinyint(4) NOT NULL DEFAULT 0,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `cl_main_id` (`claimFk`),
KEY `Id_Trabajador` (`workerFk`),
KEY `Id_Movimiento` (`saleFk`),
KEY `cl_sol_id` (`claimDestinationFk`),
KEY `claimEnd_fk_editor` (`editorFk`),
CONSTRAINT `claimEnd_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` enum('Claim','ClaimBeginning','ClaimState','ClaimDevelopment','ClaimDms','ClaimEnd','ClaimObservation') NOT NULL DEFAULT 'Claim',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `userFk` (`userFk`),
KEY `claimLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `claimLog_claimLog` (`originFk`,`creationDate`),
CONSTRAINT `claimUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `claimObservation`
--
DROP TABLE IF EXISTS `claimObservation`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `claimObservation` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`claimFk` int(10) unsigned NOT NULL,
`workerFk` int(10) unsigned DEFAULT NULL,
`text` text NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `worker_key` (`workerFk`),
KEY `claim_key` (`claimFk`),
KEY `claimObservation_created_IDX` (`created`) USING BTREE,
KEY `claimObservation_fk_editor` (`editorFk`),
CONSTRAINT `claimObservation_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `claimObservation_ibfk_1` FOREIGN KEY (`claimFk`) REFERENCES `claim` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `claimObservation_ibfk_2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Todas las observaciones referentes a una reclamación';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `claimRatio`
--
DROP TABLE IF EXISTS `claimRatio`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `claimRatio` (
`clientFk` int(11) NOT NULL DEFAULT 0,
`yearSale` decimal(10,2) DEFAULT NULL,
`claimAmount` decimal(10,2) DEFAULT NULL,
`claimingRate` decimal(5,2) DEFAULT NULL,
`priceIncreasing` decimal(5,2) DEFAULT NULL,
`packingRate` decimal(5,2) NOT NULL DEFAULT 1.00,
PRIMARY KEY (`clientFk`),
CONSTRAINT `claimRatio_ibfk_1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 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) NOT NULL,
`isTired` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`responsability` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'if=1 >sensib >culpa',
`code` varchar(3) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `claimResponsible_UN` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Consecuencias de los motivos';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `claimRma__`
--
DROP TABLE IF EXISTS `claimRma__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `claimRma__` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`code` varchar(100) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`workerFk` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='kkeada el 2024-02-26 por Pablo';
/*!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,
`code` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`description` varchar(15) NOT NULL,
`roleFk` int(10) unsigned NOT NULL DEFAULT 1,
`priority` int(11) NOT NULL DEFAULT 1,
`hasToNotify` tinyint(4) DEFAULT 0,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `roleFgn_idx` (`roleFk`),
KEY `claimState_fk_editor` (`editorFk`),
CONSTRAINT `claimState_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `roleFgn` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`defaultAddressFk` int(11) DEFAULT NULL,
`street` longtext DEFAULT NULL,
`fi` varchar(18) DEFAULT NULL,
`phone` varchar(15) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`dueDay` smallint(6) NOT NULL DEFAULT 5,
`isTaxDataChecked` tinyint(1) NOT NULL DEFAULT 0,
`mobile` varchar(15) DEFAULT NULL,
`accountingAccount` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`isEqualizated` tinyint(1) NOT NULL DEFAULT 0,
`city` varchar(100) DEFAULT NULL,
`provinceFk` smallint(5) unsigned NOT NULL,
`postcode` varchar(8) DEFAULT NULL,
`socialName` varchar(60) DEFAULT NULL,
`contact` varchar(50) DEFAULT NULL,
`hasToInvoice` tinyint(1) NOT NULL DEFAULT 1,
`isFreezed` tinyint(1) NOT NULL DEFAULT 0,
`salesPersonFk` int(10) unsigned DEFAULT NULL,
`credit` decimal(10,2) unsigned NOT NULL DEFAULT 0.00,
`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,
`hasSepaVnl` tinyint(1) DEFAULT 0,
`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 COMMENT '@deprecated 2024-02-20 refs #6784',
`creditInsurance` int(11) DEFAULT NULL,
`eypbc` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Email\\nYesterday\\nPurchases\\nBy\\nConsigna',
`hasToInvoiceByAddress` tinyint(1) DEFAULT 0,
`isCreatedAsServed` tinyint(1) DEFAULT 0,
`hasInvoiceSimplified` tinyint(1) NOT NULL DEFAULT 0,
`hasElectronicInvoice` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Registro de facturas mediante FACe',
`iban` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`hasLcr` tinyint(1) NOT NULL DEFAULT 0,
`bankEntityFk` int(10) unsigned DEFAULT NULL,
`typeFk` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'normal',
`taxTypeSageFk` smallint(6) DEFAULT NULL COMMENT 'Tipo de Iva por defecto asociado al cliente en SAGE',
`transactionTypeSageFk` tinyint(4) DEFAULT NULL COMMENT 'Tipo de transacción por defecto asociado al cliente en SAGE',
`transferorFk` int(11) DEFAULT NULL COMMENT 'Cliente que le ha transmitido la titularidad de la empresa',
`lastSalesPersonFk` int(10) unsigned DEFAULT NULL COMMENT 'ultimo comercial que tuvo, para el calculo del peso en los rankings de equipo',
`businessTypeFk` varchar(20) NOT NULL DEFAULT 'florist',
`hasIncoterms` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Received incoterms authorization from client',
`rating` int(10) unsigned DEFAULT NULL COMMENT 'información proporcionada por Informa',
`recommendedCredit` int(10) unsigned DEFAULT NULL COMMENT 'información proporcionada por Informa',
`editorFk` int(10) unsigned DEFAULT NULL,
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 `fk_Clientes_entity_idx` (`bankEntityFk`),
KEY `typeFk` (`typeFk`),
KEY `client_taxTypeSageFk_idx` (`taxTypeSageFk`),
KEY `client_transactionTypeSageFk_idx` (`transactionTypeSageFk`),
KEY `client_FK` (`businessTypeFk`),
KEY `client_lastSalesPersonFk_IDX` (`lastSalesPersonFk`) USING BTREE,
KEY `client_FK_3` (`transferorFk`),
KEY `codpos` (`postcode`),
KEY `client_fk_editor` (`editorFk`),
KEY `client_isTaxDataChecked_IDX` (`isTaxDataChecked`) USING BTREE,
CONSTRAINT `canal_nuevo_cliente` FOREIGN KEY (`contactChannelFk`) REFERENCES `contactChannel` (`id`) ON UPDATE CASCADE,
CONSTRAINT `client_FK` FOREIGN KEY (`businessTypeFk`) REFERENCES `businessType` (`code`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `client_FK_1` FOREIGN KEY (`bankEntityFk`) REFERENCES `bankEntity` (`id`) ON UPDATE CASCADE,
CONSTRAINT `client_FK_2` FOREIGN KEY (`lastSalesPersonFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `client_FK_3` FOREIGN KEY (`transferorFk`) REFERENCES `client` (`id`),
CONSTRAINT `client_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
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 `client_taxTypeSageFk` FOREIGN KEY (`taxTypeSageFk`) REFERENCES `sage`.`TiposIva` (`CodigoIva`) ON UPDATE CASCADE,
CONSTRAINT `client_transactionTypeSageFk` FOREIGN KEY (`transactionTypeSageFk`) REFERENCES `sage`.`TiposTransacciones` (`CodigoTransaccion`) ON UPDATE CASCADE,
CONSTRAINT `typeFk` FOREIGN KEY (`typeFk`) REFERENCES `clientType` (`code`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `clientChain`
--
DROP TABLE IF EXISTS `clientChain`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientChain` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`clientFk` int(11) NOT NULL,
`chainFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `clientChain_fk1_idx` (`clientFk`),
KEY `clientChain_fk2_idx` (`chainFk`),
CONSTRAINT `clientChain_fk1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `clientChain_fk2` FOREIGN KEY (`chainFk`) REFERENCES `chain` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `clientConfig`
--
DROP TABLE IF EXISTS `clientConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientConfig` (
`id` int(10) unsigned NOT NULL,
`riskTolerance` int(11) DEFAULT NULL COMMENT 'Maximo riesgo de un cliente para preparar su pedido',
`maxCreditRows` int(11) DEFAULT NULL COMMENT 'Máximo número de registros a mantener en la tabla clientCredit',
`maxPriceIncreasingRatio` decimal(2,2) NOT NULL DEFAULT 0.25 COMMENT 'máximo recobro permitido',
`riskScope` int(11) NOT NULL DEFAULT 2 COMMENT 'Time range in months to calculating a customer''s risk',
`defaultPayMethodFk` tinyint(3) unsigned DEFAULT NULL,
`defaultDueDay` int(10) unsigned DEFAULT NULL,
`defaultCredit` decimal(10,2) DEFAULT NULL,
`defaultIsTaxDataChecked` tinyint(1) DEFAULT NULL,
`defaultHasCoreVnl` tinyint(1) DEFAULT NULL,
`defaultMandateTypeFk` smallint(5) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `clientNewConfigPayMethod_FK` (`defaultPayMethodFk`),
KEY `clientNewConfigMandateType_FK` (`defaultMandateTypeFk`),
CONSTRAINT `clientNewConfigMandateType_FK` FOREIGN KEY (`defaultMandateTypeFk`) REFERENCES `mandateType` (`id`),
CONSTRAINT `clientNewConfigPayMethod_FK` FOREIGN KEY (`defaultPayMethodFk`) REFERENCES `payMethod` (`id`),
CONSTRAINT `clientConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `clientConsumptionQueue`
--
DROP TABLE IF EXISTS `clientConsumptionQueue`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientConsumptionQueue` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`params` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL CHECK (json_valid(`params`)),
`queued` datetime NOT NULL DEFAULT current_timestamp(),
`printed` datetime DEFAULT NULL,
`status` varchar(50) DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queue for client consumption PDF mailing';
/*!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) DEFAULT NULL,
`phone` varchar(15) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `clientContact_fk_editor` (`editorFk`),
KEY `clientContact_FK` (`clientFk`),
CONSTRAINT `clientContact_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `clientContact_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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(10) unsigned 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 DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`dmsFk`),
KEY `gest_doc_id` (`dmsFk`),
KEY `fk_clientes_gestdoc_1_idx` (`clientFk`),
KEY `clientDms_fk_editor` (`editorFk`),
CONSTRAINT `clientDms_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `clientDms_ibfk_2` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_clientes_gestdoc_3` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `clientInforma`
--
DROP TABLE IF EXISTS `clientInforma`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientInforma` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`clientFk` int(11) NOT NULL,
`rating` int(10) unsigned DEFAULT NULL,
`recommendedCredit` int(10) unsigned DEFAULT NULL,
`workerFk` int(10) unsigned NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `informaWorkers_fk_idx` (`workerFk`),
KEY `informaClientFk` (`clientFk`),
CONSTRAINT `informa_ClienteFk` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `informa_workers_fk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='información proporcionada por Informa, se actualiza desde el hook de client (salix)';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `clientItemType`
--
DROP TABLE IF EXISTS `clientItemType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientItemType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`clientFk` int(11) NOT NULL,
`itemTypeFk` smallint(5) unsigned NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
UNIQUE KEY `clientFk_itemTypeFk_UNIQUE` (`clientFk`,`itemTypeFk`),
KEY `clientItemType_FK_1` (`itemTypeFk`),
CONSTRAINT `clientItemType_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `clientItemType_FK_1` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='son familias de productos que se quieren sustraer a la oferta del cliente';
/*!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) DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` enum('Client','Address','ClientContact','ClientDms','ClientObservation','ClientSample','Greuge','Recovery','TpvTransaction','WorkerDms','Sms') NOT NULL DEFAULT 'Client',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `userFk` (`userFk`),
KEY `clientLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `clientLog_clientLog` (`originFk`,`creationDate`),
CONSTRAINT `clientLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `clientLost`
--
DROP TABLE IF EXISTS `clientLost`;
/*!50001 DROP VIEW IF EXISTS `clientLost`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `clientLost` AS SELECT
1 AS `clientFk`,
1 AS `lastShipped`,
1 AS `notBuyingMonths` */;
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=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 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(10) unsigned DEFAULT NULL,
`text` text NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `Id_Trabajador` (`workerFk`),
KEY `Id_Cliente` (`clientFk`),
KEY `clientObservation_created_IDX` (`created`) USING BTREE,
KEY `clientObservation_fk_editor` (`editorFk`),
CONSTRAINT `clientObservation_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Todas las observaciones referentes a un ticket';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `clientPackagingGifts`
--
DROP TABLE IF EXISTS `clientPackagingGifts`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientPackagingGifts` (
`clientFk` int(11) NOT NULL,
`giftFk` int(11) NOT NULL,
`added` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`clientFk`,`giftFk`),
KEY `clientPackagingGifts_FK_1` (`giftFk`),
CONSTRAINT `clientPackagingGifts_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`),
CONSTRAINT `clientPackagingGifts_FK_1` FOREIGN KEY (`giftFk`) REFERENCES `packagingGifts` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `clientPhoneBook`
--
DROP TABLE IF EXISTS `clientPhoneBook`;
/*!50001 DROP VIEW IF EXISTS `clientPhoneBook`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `clientPhoneBook` AS SELECT
1 AS `clientFk`,
1 AS `phone` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `clientProtected`
--
DROP TABLE IF EXISTS `clientProtected`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientProtected` (
`clientFk` int(11) NOT NULL,
PRIMARY KEY (`clientFk`),
CONSTRAINT `clientProtected_fk1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 */;
--
-- Table structure for table `clientRisk`
--
DROP TABLE IF EXISTS `clientRisk`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientRisk` (
`clientFk` int(11) NOT NULL DEFAULT 0,
`companyFk` int(10) unsigned NOT NULL DEFAULT 0,
`amount` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`clientFk`,`companyFk`),
KEY `company_id` (`companyFk`),
CONSTRAINT `clientRiskCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `clientRisk_ibfk_1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Saldo de apertura < 2015-01-01';
/*!40101 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(11) 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` int(10) unsigned DEFAULT NULL,
`userFk` int(11) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `empresa_id` (`companyFk`),
KEY `clientSample_fk_editor` (`editorFk`),
KEY `clientSample_FK` (`clientFk`),
CONSTRAINT `clientSampleCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `clientSample_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `clientSample_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `clientSms`
--
DROP TABLE IF EXISTS `clientSms`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientSms` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`clientFk` int(11) NOT NULL,
`smsFk` mediumint(8) unsigned NOT NULL,
`ticketFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `clientSms_FK` (`clientFk`),
KEY `clientSms_FK_1` (`smsFk`),
KEY `clientSms_FK_2` (`ticketFk`),
CONSTRAINT `clientSms_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE,
CONSTRAINT `clientSms_FK_1` FOREIGN KEY (`smsFk`) REFERENCES `sms` (`id`) ON UPDATE CASCADE,
CONSTRAINT `clientSms_FK_2` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 COMMENT '@deprecated 2024-02-20 refs #6784',
`code` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`type` varchar(45) NOT NULL,
`isCreatedAsServed` tinyint(1) DEFAULT 0,
PRIMARY KEY (`code`),
UNIQUE KEY `code_UNIQUE` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Establece categorias para poder agrupar las ventas';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `clientUnpaid`
--
DROP TABLE IF EXISTS `clientUnpaid`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientUnpaid` (
`clientFk` int(11) NOT NULL,
`dated` date NOT NULL,
`amount` double DEFAULT 0,
PRIMARY KEY (`clientFk`),
CONSTRAINT `clientUnpaid_clientFk` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `clientYoke`
--
DROP TABLE IF EXISTS `clientYoke`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientYoke` (
`leftOx` int(11) NOT NULL,
`rightOx` int(11) NOT NULL,
PRIMARY KEY (`leftOx`,`rightOx`),
KEY `clientYoke_fk2_idx` (`rightOx`),
CONSTRAINT `clientYoke_fk1` FOREIGN KEY (`leftOx`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `clientYoke_fk2` FOREIGN KEY (`rightOx`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='emparejamiento de clientes a efectos de precios';
/*!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) DEFAULT NULL COMMENT '@deprecated 2023-10-20 refs #6092',
`truckPlate` varchar(30) DEFAULT NULL,
`observations` varchar(255) DEFAULT NULL,
`senderInstruccions` varchar(255) DEFAULT NULL,
`paymentInstruccions` varchar(255) DEFAULT NULL,
`specialAgreements` varchar(255) DEFAULT NULL,
`created` timestamp NULL DEFAULT current_timestamp(),
`companyFk` int(10) unsigned DEFAULT NULL,
`addressToFk` int(11) DEFAULT NULL,
`addressFromFk` int(11) DEFAULT NULL,
`supplierFk` int(10) unsigned DEFAULT NULL,
`packagesList` varchar(255) DEFAULT NULL,
`merchandiseDetail` varchar(255) DEFAULT NULL,
`state` varchar(100) DEFAULT NULL,
`landed` datetime DEFAULT NULL COMMENT 'Hora de llegada a destino',
`ead` datetime DEFAULT NULL COMMENT 'Estimated Arriving Date',
PRIMARY KEY (`id`),
KEY `cmr_fk1_idx` (`ticketFk__`),
KEY `cmr_fk2_idx` (`companyFk`),
KEY `cmr_fk3_idx` (`addressToFk`),
KEY `cm_fk4_idx` (`supplierFk`),
KEY `cmr_FK` (`addressFromFk`),
CONSTRAINT `cmrCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `cmr_FK` FOREIGN KEY (`addressFromFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE,
CONSTRAINT `cmr_fk1` FOREIGN KEY (`ticketFk__`) REFERENCES `ticket` (`id`),
CONSTRAINT `cmr_fk3` FOREIGN KEY (`addressToFk`) REFERENCES `address` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `cmr_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `cmrConfig`
--
DROP TABLE IF EXISTS `cmrConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cmrConfig` (
`dayOfMonth` int(11) DEFAULT NULL,
`landingDays` tinyint(4) NOT NULL DEFAULT 1
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `cmrPallet`
--
DROP TABLE IF EXISTS `cmrPallet`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cmrPallet` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cmrFk` int(11) NOT NULL,
`expeditionPalletFk` int(11) NOT NULL,
`scanned` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `cmr_expeditionPallet_fk1_idx` (`cmrFk`),
KEY `cmr_expeditionPallet_fk2_idx` (`expeditionPalletFk`),
CONSTRAINT `cmr_expeditionPallet_fk1` FOREIGN KEY (`cmrFk`) REFERENCES `cmr` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `cmr_expeditionPallet_fk2` FOREIGN KEY (`expeditionPalletFk`) REFERENCES `expeditionPallet` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='relaciona los cmr con los pallets de expediciones';
/*!40101 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(10) unsigned DEFAULT NULL,
`stateFk` tinyint(3) unsigned DEFAULT NULL,
`itemPackingTypeFk` varchar(1) DEFAULT NULL,
`saleTotalCount` int(11) NOT NULL DEFAULT 0,
`salePickedCount` int(11) NOT NULL DEFAULT 0,
`trainFk` int(11) NOT NULL DEFAULT 1,
`sectorFk` int(11) DEFAULT NULL,
`wagons` int(11) DEFAULT NULL,
`warehouseFk` smallint(6) unsigned NOT NULL DEFAULT 60,
PRIMARY KEY (`id`),
KEY `ticketCollection_idx` (`workerFk`),
KEY `collection_id2_idx` (`stateFk`),
KEY `collection_FK` (`itemPackingTypeFk`),
KEY `collectionTrain_Fk` (`trainFk`),
KEY `collectionSector_FK` (`sectorFk`),
KEY `collection_FK2` (`warehouseFk`),
CONSTRAINT `collectionSector_FK` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `collectionTrain_Fk` FOREIGN KEY (`trainFk`) REFERENCES `train` (`id`) ON UPDATE CASCADE,
CONSTRAINT `collection_FK2` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `collectionColors`
--
DROP TABLE IF EXISTS `collectionColors`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `collectionColors` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(20) NOT NULL,
`shelve` int(11) NOT NULL DEFAULT 1,
`wagon` int(11) NOT NULL DEFAULT 1,
`trainFk` int(11) NOT NULL DEFAULT 1,
`rgb` char(7) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `collectionColors_UN` (`shelve`,`wagon`,`trainFk`),
KEY `collectionColors_FK` (`trainFk`),
CONSTRAINT `collectionColors_FK` FOREIGN KEY (`trainFk`) REFERENCES `train` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Recoge los colores para las baldas de las colecciones';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `collectionHotbed`
--
DROP TABLE IF EXISTS `collectionHotbed`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `collectionHotbed` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userFk` int(11) NOT NULL,
`created` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 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,
`height` int(10) unsigned NOT NULL DEFAULT 20,
`itemPackingTypeFk` varchar(1) NOT NULL DEFAULT 'H',
`trainFk` int(11) NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
KEY `collectionVolumetry_FK` (`itemPackingTypeFk`),
KEY `collectionVolumetry_FK_1` (`trainFk`),
CONSTRAINT `collectionVolumetry_FK` FOREIGN KEY (`itemPackingTypeFk`) REFERENCES `itemPackingType` (`code`) ON UPDATE CASCADE,
CONSTRAINT `collectionVolumetry_FK_1` FOREIGN KEY (`trainFk`) REFERENCES `train` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `collectionWagon`
--
DROP TABLE IF EXISTS `collectionWagon`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `collectionWagon` (
`collectionFk` int(11) NOT NULL,
`wagonFk` varchar(6) NOT NULL,
`position` int(11) unsigned NOT NULL,
PRIMARY KEY (`collectionFk`,`position`),
UNIQUE KEY `collectionWagon_unique` (`collectionFk`,`wagonFk`),
KEY `collectionWagon_FK_1` (`wagonFk`),
CONSTRAINT `collectionWagon_FK_1` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE,
CONSTRAINT `collectionWagon_collection` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `collectionWagonTicket`
--
DROP TABLE IF EXISTS `collectionWagonTicket`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `collectionWagonTicket` (
`ticketFk` int(11) NOT NULL,
`wagonFk` varchar(6) NOT NULL,
`trayFk` int(11) unsigned NOT NULL,
`side` set('L','R') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`rgb` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT 'Color de la balda',
`height` int(11) DEFAULT NULL COMMENT 'altura de la balda',
PRIMARY KEY (`ticketFk`,`trayFk`),
KEY `collectionWagonTicket_tray` (`trayFk`),
KEY `collectionWagonTicket_FK_1` (`wagonFk`),
CONSTRAINT `collectionWagonTicket_FK` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON UPDATE CASCADE,
CONSTRAINT `collectionWagonTicket_FK_1` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE,
CONSTRAINT `collectionWagonTicket_tray` FOREIGN KEY (`trayFk`) REFERENCES `wagonTypeTray` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `commissionConfig`
--
DROP TABLE IF EXISTS `commissionConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `commissionConfig` (
`rate` decimal(5,4) NOT NULL DEFAULT 0.0000,
`plusTeamAmount` int(11) DEFAULT NULL,
`plusNewBornAmount` int(11) DEFAULT NULL,
`plusSalesAmount` int(11) DEFAULT NULL,
`minimumSalesByQuarter` int(11) DEFAULT NULL,
`plusTeamRange` int(11) DEFAULT NULL,
`plusNewBornRange` int(11) DEFAULT NULL,
`rankingSalesRange` int(11) DEFAULT NULL,
`minScoreForPlusTeam` int(11) DEFAULT NULL,
`minScoreForPlusBoss` int(11) DEFAULT NULL,
`plusTeam` int(11) DEFAULT NULL,
`plusBoss` int(11) DEFAULT NULL COMMENT 'Este campo se deberá multiplicar x el número de miembros del equipo',
`executionDay` smallint(6) DEFAULT NULL,
`salesPersonWithPlusNewClient` int(11) DEFAULT NULL,
`maxPlusNewClient` int(11) DEFAULT NULL,
`plusDifference` int(11) DEFAULT NULL,
`maxScoreNewClient` int(11) DEFAULT NULL,
`scoreDifference` int(11) DEFAULT NULL,
PRIMARY KEY (`rate`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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` int(10) unsigned NOT NULL AUTO_INCREMENT,
`code` char(3) DEFAULT NULL,
`register` varchar(120) NOT NULL,
`workerManagerFk` int(10) unsigned NOT NULL,
`registered` date NOT NULL,
`expired` date DEFAULT NULL,
`logo` longblob DEFAULT NULL,
`isOfficial` tinyint(1) unsigned NOT NULL DEFAULT 1,
`hasCyc` tinyint(1) unsigned zerofill NOT NULL DEFAULT 0,
`rgb` varchar(6) NOT NULL,
`email` varchar(30) NOT NULL,
`stamp` longblob DEFAULT NULL,
`created` timestamp NOT NULL ON UPDATE current_timestamp(),
`clientFk` int(11) DEFAULT NULL,
`sage200Company__` int(2) DEFAULT NULL COMMENT '@deprecated 06/03/2024',
`supplierAccountFk` mediumint(8) unsigned DEFAULT NULL COMMENT 'Cuenta por defecto para ingresos desde este pais',
`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',
`companyCodeTest` int(2) DEFAULT NULL,
`footnotes` longtext DEFAULT NULL COMMENT 'pie de paginas en las facturas',
`phytosanitary` longtext DEFAULT NULL,
`fhAdminNumber` int(11) DEFAULT NULL COMMENT 'número de cliente en FloraHolland',
`web` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `companyCode_UNIQUE` (`code`),
KEY `gerente_id` (`workerManagerFk`),
KEY `empresa_cliente_idx` (`clientFk`),
KEY `Id_Proveedores_account` (`supplierAccountFk`),
KEY `empresa_grupo_fk_idx` (`companyGroupFk`),
KEY `company_fhAdminNumber_IDX` (`fhAdminNumber`) USING BTREE,
CONSTRAINT `company_ibfk_1` FOREIGN KEY (`workerManagerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `company_supplierFk` FOREIGN KEY (`id`) REFERENCES `supplier` (`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=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `companyI18n`
--
DROP TABLE IF EXISTS `companyI18n`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `companyI18n` (
`companyFk` int(10) unsigned NOT NULL,
`lang` char(2) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`footnotes` longtext DEFAULT NULL,
PRIMARY KEY (`companyFk`,`lang`),
CONSTRAINT `companyI18nCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `companyL10n`
--
DROP TABLE IF EXISTS `companyL10n`;
/*!50001 DROP VIEW IF EXISTS `companyL10n`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `companyL10n` AS SELECT
1 AS `id`,
1 AS `footnotes` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `comparative`
--
DROP TABLE IF EXISTS `comparative`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `comparative` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`timePeriod` int(11) DEFAULT NULL,
`itemFk` int(11) DEFAULT NULL,
`warehouseFk` smallint(6) unsigned DEFAULT NULL,
`quantity` int(11) DEFAULT NULL,
`price` int(11) DEFAULT NULL,
`countryFk` mediumint(8) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `comparative_unique` (`timePeriod`,`itemFk`,`warehouseFk`,`countryFk`),
KEY `comparativeItem_FK` (`itemFk`),
KEY `comparativeWarehouse_FK` (`warehouseFk`),
KEY `comparativeCountry_FK` (`countryFk`),
CONSTRAINT `comparativeCountry_FK` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`),
CONSTRAINT `comparativeItem_FK` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`),
CONSTRAINT `comparativeWarehouse_FK` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `comparativeAddConfig`
--
DROP TABLE IF EXISTS `comparativeAddConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `comparativeAddConfig` (
`id` int(10) unsigned NOT NULL,
`period` int(10) unsigned DEFAULT NULL COMMENT 'The number of periods to be regressed for insertion in vn.comparative',
`week` int(10) unsigned DEFAULT NULL COMMENT 'The number of weeks to exceed for recalculating the last period',
PRIMARY KEY (`id`),
CONSTRAINT `comparativeAddConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `comparativeConfig`
--
DROP TABLE IF EXISTS `comparativeConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `comparativeConfig` (
`id` int(10) unsigned NOT NULL,
`defaultDayRange` int(10) unsigned DEFAULT NULL COMMENT 'Rango de días predeterminado si no se especifica',
`weekRange` int(10) unsigned DEFAULT NULL COMMENT 'La cantidad de semanas que se restarán y sumarán',
`maxDayRange` int(10) unsigned DEFAULT NULL COMMENT 'El rango máximo de días antes de utilizar el rango de días predeterminado',
`minDayRange` int(10) unsigned DEFAULT NULL COMMENT 'El rango mínimo de días antes de utilizar el rango de días predeterminado',
PRIMARY KEY (`id`),
CONSTRAINT `comparativeConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `comparativeFilter`
--
DROP TABLE IF EXISTS `comparativeFilter`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `comparativeFilter` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userFk` int(10) unsigned NOT NULL,
`name` varchar(100) NOT NULL,
`buyer` int(11) DEFAULT NULL,
`itemFilter` varchar(255) DEFAULT NULL,
`isFloramondo` tinyint(4) DEFAULT NULL,
`warehouseFk` smallint(6) unsigned DEFAULT NULL,
`tintaFk` varchar(100) DEFAULT NULL,
`hasType` tinyint(1) DEFAULT 0,
`producerFilter` varchar(255) DEFAULT NULL,
`supplierFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `comparativeFilter_FK` (`userFk`),
KEY `comparativeFilter_FK_1` (`warehouseFk`),
KEY `comparativeFilter_FK_2` (`supplierFk`),
CONSTRAINT `comparativeFilter_FK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `comparativeFilter_FK_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`),
CONSTRAINT `comparativeFilter_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `comparativeFilterType`
--
DROP TABLE IF EXISTS `comparativeFilterType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `comparativeFilterType` (
`comparativeFilterFk` int(11) NOT NULL,
`itemTypeFk` int(11) NOT NULL,
PRIMARY KEY (`comparativeFilterFk`,`itemTypeFk`),
CONSTRAINT `comparativeFilterType_FK` FOREIGN KEY (`comparativeFilterFk`) REFERENCES `comparativeFilter` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `component`
--
DROP TABLE IF EXISTS `component`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `component` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`typeFk` int(11) NOT NULL,
`classRate` smallint(6) DEFAULT NULL,
`tax` double DEFAULT NULL,
`isRenewable` tinyint(2) NOT NULL DEFAULT 1,
`code` varchar(45) DEFAULT NULL,
`isRequired` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Son componentes imprescindibles en toda venta',
PRIMARY KEY (`id`),
KEY `series_componentes_idx` (`typeFk`),
KEY `comp` (`classRate`),
CONSTRAINT `serie_componente` FOREIGN KEY (`typeFk`) REFERENCES `componentType` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `componentType`
--
DROP TABLE IF EXISTS `componentType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `componentType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` varchar(45) NOT NULL,
`isBase` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'Marca aquellas series que se utilizan para calcular el precio base de las ventas, a efectos estadisticos',
`isMargin` tinyint(4) NOT NULL DEFAULT 0,
`code` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `Serie_UNIQUE` (`type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Permite organizar de forma ordenada los distintos componentes';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `confectionType`
--
DROP TABLE IF EXISTS `confectionType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `confectionType` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`description` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`ochoa` int(10) unsigned NOT NULL,
`invoiceOutFk` int(11) DEFAULT 0,
`inventoried` datetime DEFAULT NULL,
`itemLog` int(11) DEFAULT 0,
`weekGoal` int(11) DEFAULT NULL,
`photosPath` varchar(255) DEFAULT NULL,
`cashBoxNumber` int(11) DEFAULT 0,
`redCode` varchar(50) 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) 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 0,
`mdbServer` varchar(255) NOT NULL,
`fakeEmail` varchar(255) 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,
`dayStartingHour` int(11) NOT NULL DEFAULT 3 COMMENT 'Hora a la que empieza una nueva jornada de producción',
`comparativeLastBuyScope` int(11) DEFAULT NULL COMMENT 'Rango en el que se busca la última entrada de un artículo',
`mainWarehouseFk` smallint(6) unsigned NOT NULL DEFAULT 60,
PRIMARY KEY (`id`),
KEY `fechainv_idx` (`inventoried`),
CONSTRAINT `config_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `continent`
--
DROP TABLE IF EXISTS `continent`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `continent` (
`id` tinyint(4) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`code` varchar(2) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `continent_name_uindex` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='World continents';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `conveyor`
--
DROP TABLE IF EXISTS `conveyor`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `conveyor` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`typeFk` int(11) NOT NULL,
`stratum` int(11) NOT NULL DEFAULT 0,
`length` int(11) DEFAULT NULL,
`width` int(11) DEFAULT NULL,
`height` int(11) DEFAULT NULL,
`x` int(11) DEFAULT NULL,
`y` int(11) DEFAULT NULL,
`freeSpace` int(11) NOT NULL DEFAULT 0,
`isBusy` tinyint(1) NOT NULL DEFAULT 0,
`tandem` int(11) DEFAULT NULL COMMENT 'agrupa conveyors para dividir las cajas por tipo en una misma ruta',
`conveyorBuildingClassFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `conveyor_fk1_idx` (`typeFk`),
CONSTRAINT `conveyor_fk1` FOREIGN KEY (`typeFk`) REFERENCES `conveyorType` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `conveyorBuildingClass`
--
DROP TABLE IF EXISTS `conveyorBuildingClass`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `conveyorBuildingClass` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(255) DEFAULT NULL,
`priority` int(11) NOT NULL DEFAULT 0,
`weightThreshold` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tipo de caja para el montaje de pallets';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `conveyorConfig`
--
DROP TABLE IF EXISTS `conveyorConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `conveyorConfig` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`itemName` varchar(45) NOT NULL,
`length` int(11) DEFAULT NULL,
`width` int(11) DEFAULT NULL,
`height` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `itemName_UNIQUE` (`itemName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `conveyorExpedition`
--
DROP TABLE IF EXISTS `conveyorExpedition`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `conveyorExpedition` (
`expeditionFk` int(11) NOT NULL,
`conveyorFk` int(11) DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`conveyorBuildingClassFk` int(11) NOT NULL DEFAULT 1,
`length` int(11) NOT NULL DEFAULT 1,
`width` int(11) NOT NULL DEFAULT 1,
`height` int(11) NOT NULL DEFAULT 1,
`x` int(11) NOT NULL DEFAULT 18100,
`y` int(11) NOT NULL DEFAULT 1,
`routeFk` int(11) NOT NULL,
`isIn` tinyint(4) NOT NULL DEFAULT 0,
`productionMinute` int(11) DEFAULT NULL,
`isOut` tinyint(4) NOT NULL DEFAULT 0,
`truck` varchar(20) DEFAULT NULL,
`criterion` int(11) DEFAULT NULL,
`isHeavy` tinyint(1) NOT NULL DEFAULT 1,
PRIMARY KEY (`expeditionFk`),
KEY `conveyorExpedition_fk1_idx` (`conveyorFk`),
KEY `conveyorExpedition_fk2_idx` (`conveyorBuildingClassFk`),
CONSTRAINT `conveyorExpedition_fk1` FOREIGN KEY (`conveyorFk`) REFERENCES `conveyor` (`id`) ON UPDATE CASCADE,
CONSTRAINT `conveyorExpedition_fk2` FOREIGN KEY (`conveyorBuildingClassFk`) REFERENCES `conveyorBuildingClass` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `conveyorMode`
--
DROP TABLE IF EXISTS `conveyorMode`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `conveyorMode` (
`code` varchar(20) NOT NULL,
`saturacion` int(11) NOT NULL,
`gap` int(11) NOT NULL,
`isActive` tinyint(4) NOT NULL DEFAULT 0,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `conveyorType`
--
DROP TABLE IF EXISTS `conveyorType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `conveyorType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(45) DEFAULT NULL,
`color` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `coolerPathDetail`
--
DROP TABLE IF EXISTS `coolerPathDetail`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `coolerPathDetail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`coolerPathFk` int(11) NOT NULL DEFAULT 1,
`hallway` varchar(3) NOT NULL,
PRIMARY KEY (`coolerPathFk`,`hallway`),
UNIQUE KEY `cooler_path_detail_id_UNIQUE` (`id`),
CONSTRAINT `coolerPathDetail_FK` FOREIGN KEY (`coolerPathFk`) REFERENCES `vn2008`.`cooler_path__` (`cooler_path_id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `corridor`
--
DROP TABLE IF EXISTS `corridor`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `corridor` (
`code` varchar(1) NOT NULL COMMENT 'letra que da nombre al pasillo',
`isAscendent` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'TRUE cuando se prepara de menor a mayor, FALSE cuando es a la inversa',
`prepOrder` int(10) unsigned NOT NULL COMMENT 'orden de preparacion de los pasillos',
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='establece el orden y sentido de preparacion de los pasillos del parking';
/*!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) NOT NULL,
`CEE` tinyint(1) NOT NULL DEFAULT 1,
`code` varchar(2) NOT NULL,
`currencyFk` tinyint(3) unsigned NOT NULL DEFAULT 1,
`politicalCountryFk__` mediumint(8) unsigned DEFAULT NULL COMMENT 'Pais Real(apaño por culpa del España Exento)',
`geoFk` int(11) DEFAULT NULL,
`hasDailyInvoice` tinyint(4) NOT NULL DEFAULT 0,
`isUeeMember` tinyint(4) NOT NULL DEFAULT 0,
`ibanLength` tinyint(4) DEFAULT NULL,
`continentFk` tinyint(4) DEFAULT NULL,
`a3Code` int(11) DEFAULT NULL COMMENT 'Código país para a3',
`isSocialNameUnique` tinyint(1) NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
UNIQUE KEY `country_unique` (`code`),
KEY `Id_Paisreal` (`politicalCountryFk__`),
KEY `currency_id_fk_idx` (`currencyFk`),
KEY `country_Ix4` (`country`),
KEY `continent_id_fk_idx` (`continentFk`),
KEY `country_FK_1` (`geoFk`),
CONSTRAINT `continent_id_fk` FOREIGN KEY (`continentFk`) REFERENCES `continent` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `country_FK` FOREIGN KEY (`politicalCountryFk__`) REFERENCES `country` (`id`) ON UPDATE CASCADE,
CONSTRAINT `country_FK_1` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON UPDATE CASCADE,
CONSTRAINT `currency_id_fk` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `cplusCorrectingType`
--
DROP TABLE IF EXISTS `cplusCorrectingType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cplusCorrectingType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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,
`creditClassificationFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `CreditInsurance_Fk1_idx` (`creditClassification`),
KEY `creditInsurance_creditClassificationFk` (`creditClassificationFk`),
CONSTRAINT `CreditInsurance_Fk1` FOREIGN KEY (`creditClassification`) REFERENCES `creditClassification` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `creditInsurance_creditClassificationFk` FOREIGN KEY (`creditClassificationFk`) REFERENCES `creditClassification` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Detalla los clientes que tienen seguro de credito';
/*!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` (
`id` tinyint(3) unsigned NOT NULL,
`code` varchar(3) NOT NULL,
`name` varchar(45) DEFAULT NULL,
`ratio` double NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
UNIQUE KEY `Moneda_UNIQUE` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `customsAgent`
--
DROP TABLE IF EXISTS `customsAgent`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `customsAgent` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fiscalName` varchar(50) NOT NULL,
`street` varchar(50) DEFAULT NULL,
`nif` varchar(50) NOT NULL,
`phone` varchar(16) DEFAULT NULL,
`email` varchar(150) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `nif_UNIQUE` (`nif`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_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=utf8mb3 COLLATE=utf8mb3_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`,
1 AS `country`,
1 AS `payMethod` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `delivery`
--
DROP TABLE IF EXISTS `delivery`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `delivery` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`longitude` decimal(11,7) DEFAULT NULL,
`latitude` decimal(11,7) DEFAULT NULL,
`dated` datetime DEFAULT NULL,
`ticketFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `delivery_ticketFk_FK` (`ticketFk`),
CONSTRAINT `delivery_ticketFk_FK` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Informa de los datos geográficos y temporales de las entregas de los repartidores';
/*!40101 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) DEFAULT NULL,
`code` varchar(45) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `deliveryNote`
--
DROP TABLE IF EXISTS `deliveryNote`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `deliveryNote` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ref` varchar(45) DEFAULT NULL,
`note` varchar(150) DEFAULT NULL,
`shipped` date NOT NULL,
`landed` date DEFAULT NULL,
`amount` double DEFAULT NULL,
`supplierFk` int(10) unsigned NOT NULL,
`companyFk` int(10) unsigned NOT NULL,
`warehouseFk` smallint(6) unsigned NOT NULL,
`stateFk` int(11) NOT NULL,
`workerFk` int(10) unsigned NOT NULL COMMENT 'Id_Trabajador hace referencia a la persona que ha introducido el albarán',
`supervisorFk` int(10) unsigned NOT NULL,
`departmentFk` int(11) NOT NULL,
`invoiceInFk` mediumint(8) unsigned DEFAULT NULL,
`farmingFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_albaran_Proveedores_idx` (`supplierFk`),
KEY `fk_albaran_empresa1_idx` (`companyFk`),
KEY `fk_albaran_warehouse1_idx` (`warehouseFk`),
KEY `fk_albaran_albaran_state1_idx` (`stateFk`),
KEY `fk_albaran_Trabajadores1_idx` (`workerFk`),
KEY `fk_albaran_Trabajadores2_idx` (`supervisorFk`),
KEY `fk_albaran_department1_idx` (`departmentFk`),
KEY `fk_albaran_recibida_idx` (`invoiceInFk`),
KEY `albaran_FK` (`farmingFk`),
CONSTRAINT `albaranCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `albaran_FK` FOREIGN KEY (`farmingFk`) REFERENCES `farming` (`id`),
CONSTRAINT `albaran_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE,
CONSTRAINT `fk_albaran_Trabajadores1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `fk_albaran_Trabajadores2` FOREIGN KEY (`supervisorFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `fk_albaran_albaran_state1` FOREIGN KEY (`stateFk`) REFERENCES `deliveryNoteState` (`id`) ON UPDATE CASCADE,
CONSTRAINT `fk_albaran_recibida` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_albaran_warehouse1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `deliveryNoteDms`
--
DROP TABLE IF EXISTS `deliveryNoteDms`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `deliveryNoteDms` (
`dmsFk` int(11) NOT NULL,
`deliveryNoteFk` int(11) NOT NULL,
PRIMARY KEY (`dmsFk`,`deliveryNoteFk`),
KEY `fk_albaran_gestdoc_gestdoc1_idx` (`dmsFk`),
KEY `fk_albaran_gestdoc_albaran1_idx` (`deliveryNoteFk`),
CONSTRAINT `albaran_gestdoc_FK` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_albaran_gestdoc_albaran1` FOREIGN KEY (`deliveryNoteFk`) REFERENCES `deliveryNote` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `deliveryNoteState`
--
DROP TABLE IF EXISTS `deliveryNoteState`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `deliveryNoteState` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`state` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`ubication` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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(2) NOT NULL,
`country_code` varchar(5) DEFAULT NULL,
`place_name` varchar(150) NOT NULL,
`admin_name1` varchar(150) NOT NULL,
`code_name1` varchar(150) DEFAULT NULL,
`admin_name2` varchar(150) DEFAULT NULL,
`code_name2` varchar(2) DEFAULT NULL,
`admin_name3` varchar(150) NOT NULL,
`code_name3` varchar(5) NOT NULL,
`latitude` varchar(10) NOT NULL,
`longitude` varchar(10) NOT NULL,
`accuracy` varchar(1) NOT NULL,
`delivery_zipPK` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`delivery_zipPK`),
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=utf8mb3 COLLATE=utf8mb3_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,
`code` varchar(45) DEFAULT NULL,
`name` varchar(45) NOT NULL,
`lft` int(11) DEFAULT NULL,
`rgt` int(11) DEFAULT NULL,
`workerFk` int(10) unsigned DEFAULT NULL COMMENT 'Id_Trabajador es el jefe del departamento',
`companyFk` int(11) NOT 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(11) DEFAULT 1,
`path` varchar(255) DEFAULT NULL,
`chatName` varchar(45) DEFAULT NULL,
`isTeleworking` tinyint(1) DEFAULT 0,
`notificationEmail` varchar(150) DEFAULT NULL,
`hasToRefill` tinyint(1) DEFAULT 0 COMMENT 'Rellenar días sin fichadas presenciales',
`hasToSendMail` tinyint(1) DEFAULT 0 COMMENT 'Para el envio de mail en el procedimiento workerTimeControl_sendMail()',
`hasToCheckLogin` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Para comprobar en el login de la app',
`hasToMistake` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Indica si al departamento pueden serles puestos errores',
`clientFk` int(11) DEFAULT NULL COMMENT 'Cuenta de cliente que se utiliza para los compras de consumo departamental',
`twoFactor` enum('email') DEFAULT NULL COMMENT 'Default user two-factor auth type',
`pbxQueue` varchar(128) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`workerActivityTypeFk` varchar(20) DEFAULT NULL COMMENT 'Indica la actitividad que desempeña por defecto ese departamento',
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`),
KEY `department_FK` (`clientFk`),
KEY `department_FK_1` (`parentFk`),
KEY `department_queue_FK` (`pbxQueue`),
KEY `department_workerActivityType_FK` (`workerActivityTypeFk`),
CONSTRAINT `department_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `department_FK_1` FOREIGN KEY (`parentFk`) REFERENCES `department` (`id`),
CONSTRAINT `department_queue_FK` FOREIGN KEY (`pbxQueue`) REFERENCES `pbx`.`queue` (`name`) ON UPDATE CASCADE,
CONSTRAINT `department_workerActivityType_FK` FOREIGN KEY (`workerActivityTypeFk`) REFERENCES `workerActivityType` (`code`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_department_Trabajadores1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`model` varchar(50) 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `deviceLog`
--
DROP TABLE IF EXISTS `deviceLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `deviceLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`android_id` varchar(64) NOT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`nameApp` varchar(45) DEFAULT NULL,
`versionApp` varchar(45) DEFAULT NULL,
`serialNumber` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `deviceLog_FK` (`userFk`),
CONSTRAINT `deviceLog_FK` FOREIGN KEY (`userFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`modelFk` varchar(50) NOT NULL,
`macWifi` varchar(45) DEFAULT NULL,
`serialNumber` varchar(45) DEFAULT NULL,
`android_id` varchar(64) DEFAULT NULL,
`purchased` date NOT NULL DEFAULT '1900-01-01' COMMENT 'Fecha de compra',
`stateFk` varchar(50) DEFAULT 'idle',
`isInScalefusion` tinyint(1) DEFAULT 0 COMMENT 'Para saber si esta en Scalefusion',
`description` varchar(100) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `device_id_UNIQUE` (`id`),
UNIQUE KEY `sn_UNIQUE` (`imei`),
UNIQUE KEY `serial_number_UN` (`serialNumber`),
UNIQUE KEY `deviceProduction_UN` (`android_id`),
KEY `deviceProductionModelsFgn` (`modelFk`),
KEY `deviceProduction_FK` (`stateFk`),
KEY `deviceProduction_fk_editor` (`editorFk`),
CONSTRAINT `deviceProductionModelsFgn` FOREIGN KEY (`modelFk`) REFERENCES `deviceProductionModels` (`code`) ON UPDATE CASCADE,
CONSTRAINT `deviceProduction_FK` FOREIGN KEY (`stateFk`) REFERENCES `deviceProductionState` (`code`),
CONSTRAINT `deviceProduction_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `deviceProduction_CHECK` CHECK (`android_id` regexp '[A-Za-z0-9]{16,}' or `android_id` is null)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `deviceProductionConfig`
--
DROP TABLE IF EXISTS `deviceProductionConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `deviceProductionConfig` (
`id` int(10) unsigned NOT NULL,
`isAllUsersallowed` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Permite que cualquier usuario pueda loguearse',
`isTractorHuntingMode` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Habilita el modo cazador para usuarios que no se han logeado un tractor para sacar',
PRIMARY KEY (`id`),
CONSTRAINT `deviceProductionConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `deviceProductionLog`
--
DROP TABLE IF EXISTS `deviceProductionLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `deviceProductionLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`originFk` int(11) DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` enum('DeviceProduction','DeviceProductionModels','DeviceProductionState','DeviceProductionUser') NOT NULL DEFAULT 'DeviceProduction',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `userFk` (`userFk`),
KEY `deviceProductionLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `deviceProductionLog_deviceProductionLog` (`originFk`,`creationDate`),
CONSTRAINT `deviceProductionUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!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) NOT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`code`),
KEY `deviceProductionModels_fk_editor` (`editorFk`),
CONSTRAINT `deviceProductionModels_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `deviceProductionState`
--
DROP TABLE IF EXISTS `deviceProductionState`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `deviceProductionState` (
`code` varchar(50) NOT NULL,
`description` varchar(50) NOT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`code`),
KEY `deviceProductionState_fk_editor` (`editorFk`),
CONSTRAINT `deviceProductionState_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`created` timestamp NULL DEFAULT current_timestamp(),
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`deviceProductionFk`),
UNIQUE KEY `deviceProductionUser_UN` (`userFk`),
KEY `userFgn_idx` (`userFk`),
KEY `deviceProductionUser_fk_editor` (`editorFk`),
CONSTRAINT `deviceProductionUser_FK` FOREIGN KEY (`deviceProductionFk`) REFERENCES `deviceProduction` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `deviceProductionUser_PK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `deviceProductionUser_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `disabilityGrade`
--
DROP TABLE IF EXISTS `disabilityGrade`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `disabilityGrade` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Grados de discapacidad Modelo 145 IRPF',
`description` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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(50) DEFAULT NULL,
`description` varchar(200) DEFAULT NULL,
`companyFk` int(10) unsigned NOT NULL DEFAULT 442,
`hardCopyNumber` mediumint(8) unsigned DEFAULT NULL,
`contentType` varchar(150) DEFAULT NULL,
`file` varchar(30) DEFAULT NULL,
`hasFile` tinyint(4) NOT NULL DEFAULT 0,
`workerFk` int(10) unsigned DEFAULT NULL,
`created` timestamp NULL DEFAULT current_timestamp(),
`warehouseFk` smallint(5) unsigned DEFAULT 60,
PRIMARY KEY (`id`),
UNIQUE KEY `emp_id` (`companyFk`,`hardCopyNumber`,`warehouseFk`),
UNIQUE KEY `dms_hardCopyNumber_IDX` (`hardCopyNumber`,`warehouseFk`) USING BTREE,
KEY `trabajador_id` (`workerFk`),
KEY `warehouse_id` (`warehouseFk`),
KEY `dms_dmsTypeFk_idx` (`dmsTypeFk`),
CONSTRAINT `dmsCompany_Fk` 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='document managment system';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `dmsStorageBox`
--
DROP TABLE IF EXISTS `dmsStorageBox`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dmsStorageBox` (
`id` int(11) NOT NULL,
`companyFk` int(10) unsigned NOT NULL,
`started` bigint(20) NOT NULL,
`ended` bigint(20) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`,`companyFk`),
KEY `dmsStorageBox_company_FK` (`companyFk`),
CONSTRAINT `dmsStorageBox_company_FK` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Caja en la que se guardan la documentacion fisica de dms';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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,
`code` varchar(45) NOT NULL,
`name` varchar(45) NOT NULL,
`path__` varchar(255) NOT NULL COMMENT '@deprecated 2024-01-08 refs #6410',
`writeRoleFk` int(10) unsigned DEFAULT NULL,
`readRoleFk` int(10) unsigned DEFAULT NULL,
`monthToDelete` int(10) unsigned DEFAULT NULL COMMENT 'Meses en el pasado para ir borrando registros, dejar a null para no borrarlos nunca',
PRIMARY KEY (`id`),
UNIQUE KEY `dmsType_unique` (`code`),
KEY `readRoleFk` (`readRoleFk`),
KEY `writeRoleFk` (`writeRoleFk`),
CONSTRAINT `readRoleFk` FOREIGN KEY (`readRoleFk`) REFERENCES `account`.`role` (`id`),
CONSTRAINT `writeRoleFk` FOREIGN KEY (`writeRoleFk`) REFERENCES `account`.`role` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `dock`
--
DROP TABLE IF EXISTS `dock`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dock` (
`code` varchar(10) NOT NULL DEFAULT '',
`description` varchar(50) DEFAULT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Se utiliza para el panel de grafana: https://grafana.verdnatura.es/d/w9w3Uo-7z/';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `docuware`
--
DROP TABLE IF EXISTS `docuware`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `docuware` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(50) NOT NULL,
`fileCabinetName` varchar(50) NOT NULL,
`action` varchar(255) NOT NULL,
`dialogName` varchar(100) NOT NULL,
`findById` varchar(50) DEFAULT NULL,
`dmsTypeFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `docuware_FK` (`dmsTypeFk`),
CONSTRAINT `docuware_FK` FOREIGN KEY (`dmsTypeFk`) REFERENCES `dmsType` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `docuwareConfig`
--
DROP TABLE IF EXISTS `docuwareConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `docuwareConfig` (
`id` int(10) unsigned NOT NULL,
`url` varchar(75) DEFAULT NULL,
`cookie` varchar(1000) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `docuwareConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `docuwareTablet`
--
DROP TABLE IF EXISTS `docuwareTablet`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `docuwareTablet` (
`tablet` varchar(100) NOT NULL,
`description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`tablet`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`awbFk__` smallint(11) unsigned DEFAULT NULL COMMENT '@Deprecated refs #5871 01/10/2023',
`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` int(10) unsigned NOT NULL DEFAULT 442,
`ASIEN` double DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`),
KEY `fk_awb_dua_awb_idx` (`awbFk__`),
KEY `fk_dua_gestdoc1_idx` (`gestdocFk`),
KEY `dua_fk4_idx` (`companyFk`),
CONSTRAINT `duaCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `dua_fk1` FOREIGN KEY (`gestdocFk`) REFERENCES `dms` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`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_fk3_idx` (`taxClassFk`),
CONSTRAINT `duaTax_fk1` FOREIGN KEY (`duaFk`) REFERENCES `dua` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `duaTax_fk3` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `educationLevel`
--
DROP TABLE IF EXISTS `educationLevel`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `educationLevel` (
`id` smallint(6) NOT NULL,
`name` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Nivel de formación mismo de a3';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ektEntryAssign`
--
DROP TABLE IF EXISTS `ektEntryAssign`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ektEntryAssign` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`kop` int(11) DEFAULT NULL,
`sub` mediumint(8) unsigned DEFAULT NULL,
`pro` mediumint(8) unsigned DEFAULT NULL,
`auction` int(11) DEFAULT NULL,
`warehouseOutFk` int(11) NOT NULL,
`warehouseInFk` int(11) NOT NULL,
`agencyModeFk` int(11) NOT NULL,
`supplierFk` int(11) NOT NULL,
`entryFk` int(11) DEFAULT NULL,
`ref` varchar(45) DEFAULT NULL,
`addressFk` int(11) DEFAULT NULL,
`companyFk` smallint(5) unsigned NOT NULL DEFAULT 442,
PRIMARY KEY (`id`),
UNIQUE KEY `ektEntryAssign_ix1` (`kop`,`sub`,`pro`),
KEY `ektEntryAssign_FK` (`addressFk`),
CONSTRAINT `ektEntryAssign_FK` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='define las condiciones para asignar entradas a los ekt';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `ektSubAddress`
--
DROP TABLE IF EXISTS `ektSubAddress`;
/*!50001 DROP VIEW IF EXISTS `ektSubAddress`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ektSubAddress` AS SELECT
1 AS `sub`,
1 AS `clientFk`,
1 AS `nickname`,
1 AS `addressFk` */;
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) DEFAULT NULL,
`value` varchar(45) DEFAULT NULL COMMENT 'Table to save all emergency phones',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`consumption` int(11) NOT NULL COMMENT 'Consumption in watts',
PRIMARY KEY (`input`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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(10) unsigned NOT NULL DEFAULT 644,
`dated` datetime NOT NULL,
`invoiceNumber` varchar(50) DEFAULT NULL,
`isBooked` tinyint(1) NOT NULL DEFAULT 0,
`isExcludedFromAvailable` tinyint(1) NOT NULL DEFAULT 0,
`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) DEFAULT NULL,
`travelFk` int(11) unsigned DEFAULT NULL,
`currencyFk` tinyint(3) unsigned DEFAULT 1,
`companyFk` int(10) unsigned NOT NULL DEFAULT 442,
`gestDocFk` int(11) DEFAULT NULL,
`invoiceInFk` mediumint(8) unsigned DEFAULT NULL,
`isBlocked__` tinyint(4) NOT NULL DEFAULT 0 COMMENT '@deprecated 27/03/2024',
`loadPriority` int(11) DEFAULT NULL,
`kop` int(11) DEFAULT NULL,
`sub` mediumint(8) unsigned DEFAULT NULL,
`pro` mediumint(8) unsigned DEFAULT NULL,
`auction` int(11) DEFAULT NULL,
`invoiceAmount` decimal(10,2) DEFAULT NULL,
`buyerFk` int(10) unsigned DEFAULT NULL,
`typeFk` varchar(100) DEFAULT NULL COMMENT 'Tipo de entrada',
`reference` varchar(50) DEFAULT NULL COMMENT 'Referencia para eti',
`observationEditorFk` int(10) unsigned DEFAULT NULL COMMENT 'Último usuario que ha modificado el campo evaNotes',
`clonedFrom` int(11) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
`lockerUserFk` int(10) unsigned DEFAULT NULL,
`locked` datetime DEFAULT current_timestamp(),
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`),
KEY `entry_FK` (`buyerFk`),
KEY `entry_FK_1` (`typeFk`),
KEY `entry_observationEditorFk` (`observationEditorFk`),
KEY `entry_fk_editor` (`editorFk`),
KEY `entryAccountFk` (`lockerUserFk`),
CONSTRAINT `Entradas_fk8` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `entryAccountFk` FOREIGN KEY (`lockerUserFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `entryCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `entry_FK` FOREIGN KEY (`buyerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `entry_FK_1` FOREIGN KEY (`typeFk`) REFERENCES `entryType` (`code`) ON UPDATE CASCADE,
CONSTRAINT `entry_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `entry_ibfk_6` FOREIGN KEY (`travelFk`) REFERENCES `travel` (`id`) ON UPDATE CASCADE,
CONSTRAINT `entry_observationEditorFk` FOREIGN KEY (`observationEditorFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE,
CONSTRAINT `entry_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='InnoDB free: 88064 kB; (`Id_Proveedor`) REFER `vn2008/Provee';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `entryConfig`
--
DROP TABLE IF EXISTS `entryConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `entryConfig` (
`defaultEntry` int(11) NOT NULL,
`mailToNotify` varchar(255) DEFAULT NULL,
`inventorySupplierFk` int(11) DEFAULT 4,
`maxLockTime` int(10) unsigned DEFAULT NULL COMMENT 'Tiempo máximo que puede estar una entrada bloqueada en segundos',
`defaultSupplierFk` int(11) DEFAULT 13,
PRIMARY KEY (`defaultEntry`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `entryDms`
--
DROP TABLE IF EXISTS `entryDms`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `entryDms` (
`entryFk` int(11) NOT NULL,
`dmsFk` int(11) NOT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`entryFk`,`dmsFk`),
KEY `gestdoc_id` (`dmsFk`),
KEY `entryDms_editor` (`editorFk`),
CONSTRAINT `entryDms_dms` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `entryDms_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `entryDms_entry` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `entryLog`
--
DROP TABLE IF EXISTS `entryLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `entryLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`originFk` int(11) DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` enum('Entry','Buy','EntryObservation') NOT NULL DEFAULT 'Entry',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `entryLog_ibfk_2` (`userFk`),
KEY `entryLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `entryLog_originFk` (`originFk`,`creationDate`),
CONSTRAINT `entryLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `entryObservation`
--
DROP TABLE IF EXISTS `entryObservation`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `entryObservation` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`entryFk` int(11) NOT NULL,
`observationTypeFk` tinyint(3) unsigned NOT NULL,
`description` text DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `entryFk_observationTypeFk_UNIQUE` (`entryFk`,`observationTypeFk`),
KEY `observationType_id_observationTypeFk` (`observationTypeFk`),
KEY `entryObservation_fk_editor` (`editorFk`),
CONSTRAINT `entryObservation_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `entry_id_entryFk` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `observationType_id_observationTypeFk` FOREIGN KEY (`observationTypeFk`) REFERENCES `observationType` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `entryOrder`
--
DROP TABLE IF EXISTS `entryOrder`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `entryOrder` (
`entryFk` int(11) NOT NULL,
`order` int(11) NOT NULL DEFAULT 1 COMMENT '1.- Ordenar por articulo\n2.- Ordenar por compra\n',
PRIMARY KEY (`entryFk`),
CONSTRAINT `entradas_entradas_orden` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `entryType`
--
DROP TABLE IF EXISTS `entryType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `entryType` (
`code` varchar(100) NOT NULL,
`description` varchar(100) NOT NULL,
`isInformal` tinyint(4) NOT NULL DEFAULT 0,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`route` varchar(3) DEFAULT NULL,
`agencyName` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`postalCode` varchar(255) NOT NULL,
`agencyFk` varchar(45) NOT NULL,
PRIMARY KEY (`id`),
KEY `agencyFk` (`agencyFk`),
KEY `postalCode` (`postalCode`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL DEFAULT '024' COMMENT 'Tipo de servicio en horas. 024 -> servicio las 24h',
`numBox` varchar(3) 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) 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=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `errorLogApp`
--
DROP TABLE IF EXISTS `errorLogApp`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `errorLogApp` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`error` varchar(55) DEFAULT NULL,
`date` datetime DEFAULT NULL,
`workerFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Guarda un registro de errores e la app de almacén';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `erte`
--
DROP TABLE IF EXISTS `erte`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `erte` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`workerFk` int(11) NOT NULL,
`started` date DEFAULT NULL,
`ended` date DEFAULT NULL,
`reduction` int(3) NOT NULL DEFAULT 1,
`monday` tinyint(1) DEFAULT NULL,
`tuesday` tinyint(1) DEFAULT NULL,
`wednesday` tinyint(1) DEFAULT NULL,
`thursday` tinyint(1) DEFAULT NULL,
`friday` tinyint(1) DEFAULT NULL,
`saturday` tinyint(1) DEFAULT NULL,
`sunday` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `especialPrice`
--
DROP TABLE IF EXISTS `especialPrice`;
/*!50001 DROP VIEW IF EXISTS `especialPrice`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `especialPrice` AS SELECT
1 AS `id`,
1 AS `clientFk`,
1 AS `itemFk`,
1 AS `value` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `exchangeInsurance`
--
DROP TABLE IF EXISTS `exchangeInsurance`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `exchangeInsurance` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`amount` decimal(10,2) NOT NULL,
`dated` date NOT NULL,
`dueDated` date NOT NULL,
`entityFk` int(10) unsigned NOT NULL,
`ref` varchar(45) DEFAULT NULL,
`rate` decimal(10,4) NOT NULL,
`companyFk` int(10) unsigned NOT NULL DEFAULT 442,
`financialProductTypefk` varchar(2) NOT NULL DEFAULT 'SC',
`pago_sdccol` varchar(45) DEFAULT NULL,
`upperBarrier` decimal(10,2) DEFAULT NULL,
`lowerBarrier` decimal(10,2) DEFAULT NULL,
`strike` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `empresa_sdc_idx` (`companyFk`),
KEY `financial_type_fk_idx` (`financialProductTypefk`),
KEY `pago_sdc_entity_fk_idx` (`entityFk`),
CONSTRAINT `financial_type_fk` FOREIGN KEY (`financialProductTypefk`) REFERENCES `financialProductType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `pago_sdcCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `pago_sdc_entity_fk` FOREIGN KEY (`entityFk`) REFERENCES `bankEntity` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Seguros de cambio';
/*!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 `exchangeInsuranceInPrevious`
--
DROP TABLE IF EXISTS `exchangeInsuranceInPrevious`;
/*!50001 DROP VIEW IF EXISTS `exchangeInsuranceInPrevious`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `exchangeInsuranceInPrevious` AS SELECT
1 AS `dated`,
1 AS `amount`,
1 AS `rate` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `exchangeInsuranceOut`
--
DROP TABLE IF EXISTS `exchangeInsuranceOut`;
/*!50001 DROP VIEW IF EXISTS `exchangeInsuranceOut`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `exchangeInsuranceOut` AS SELECT
1 AS `received`,
1 AS `divisa`,
1 AS `rate` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `exchangeReportSource`
--
DROP TABLE IF EXISTS `exchangeReportSource`;
/*!50001 DROP VIEW IF EXISTS `exchangeReportSource`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `exchangeReportSource` AS SELECT
1 AS `dated`,
1 AS `amountIn`,
1 AS `rateIn`,
1 AS `amountOut`,
1 AS `rateOut`,
1 AS `amountEntry`,
1 AS `rateEntry`,
1 AS `rateECB` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `exchangeReportSourcePrevious`
--
DROP TABLE IF EXISTS `exchangeReportSourcePrevious`;
/*!50001 DROP VIEW IF EXISTS `exchangeReportSourcePrevious`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `exchangeReportSourcePrevious` AS SELECT
1 AS `dated`,
1 AS `amountIn`,
1 AS `rateIn`,
1 AS `amountOut`,
1 AS `rateOut`,
1 AS `amountEntry`,
1 AS `rateEntry` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `excuse`
--
DROP TABLE IF EXISTS `excuse`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `excuse` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`txt` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
`date` datetime NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`freightItemFk` int(11) DEFAULT 1 COMMENT 'itemFk del artículo que nos va a facturar el proveedor de transporte.',
`created` timestamp NULL DEFAULT current_timestamp(),
`itemFk__` int(11) DEFAULT NULL COMMENT 'Si es necesario el itemFk del cubo, se obtiene mediante packagingFk, join packing.itemFk',
`counter` smallint(5) unsigned NOT NULL,
`workerFk` int(10) unsigned DEFAULT NULL,
`externalId` varchar(20) DEFAULT NULL,
`packagingFk` varchar(10) DEFAULT NULL,
`itemPackingTypeFk` varchar(1) DEFAULT NULL,
`hostFk` varchar(6) NOT NULL,
`stateTypeFk` int(11) DEFAULT NULL COMMENT 'Ultimo estado de la expedicion',
`hasNewRoute` tinyint(1) NOT NULL DEFAULT 0,
`isBox` int(11) GENERATED ALWAYS AS (`freightItemFk`) VIRTUAL COMMENT 'Columna virtual provisional para Salix',
`editorFk` int(10) unsigned DEFAULT NULL,
`packingSiteFk` int(11) DEFAULT NULL,
`monitorId` varchar(255) DEFAULT NULL,
`started` timestamp NOT NULL,
`ended` timestamp NOT NULL,
PRIMARY KEY (`id`),
KEY `index1` (`agencyModeFk`),
KEY `index2` (`freightItemFk`),
KEY `index3` (`created`),
KEY `index4` (`ticketFk`),
KEY `expedition_fk3_idx` (`packagingFk`),
KEY `expedition_itemPackingTypeFk` (`itemPackingTypeFk`),
KEY `workerFk` (`workerFk`),
KEY `expedition_FK` (`stateTypeFk`),
KEY `expedition_fk_editor` (`editorFk`),
KEY `expedition_FK_1` (`packingSiteFk`),
CONSTRAINT `expedition_FK` FOREIGN KEY (`stateTypeFk`) REFERENCES `expeditionStateType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `expedition_FK_1` FOREIGN KEY (`packingSiteFk`) REFERENCES `packingSite` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `expedition_fk1` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE,
CONSTRAINT `expedition_fk2` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `expedition_fk3` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE,
CONSTRAINT `expedition_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `expedition_ibfk_1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`),
CONSTRAINT `expedition_itemPackingTypeFk` FOREIGN KEY (`itemPackingTypeFk`) REFERENCES `itemPackingType` (`code`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `expeditionBoxVol`
--
DROP TABLE IF EXISTS `expeditionBoxVol`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expeditionBoxVol` (
`boxFk` int(11) NOT NULL,
`m3` double NOT NULL,
`ratio` double NOT NULL,
`code` varchar(45) DEFAULT NULL,
PRIMARY KEY (`boxFk`),
CONSTRAINT `expeditionBoxVol_FK` FOREIGN KEY (`boxFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Establece el volumen de cada servicio para poder comparar el teorico y el real en el control de portes';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `expeditionCommon`
--
DROP TABLE IF EXISTS `expeditionCommon`;
/*!50001 DROP VIEW IF EXISTS `expeditionCommon`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `expeditionCommon` AS SELECT
1 AS `truckFk`,
1 AS `eta`,
1 AS `description`,
1 AS `palletFk`,
1 AS `routeFk`,
1 AS `scanFk`,
1 AS `expeditionFk`,
1 AS `expeditionTruckFk`,
1 AS `warehouseFk`,
1 AS `lastPacked`,
1 AS `ticketFk` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `expeditionMistake`
--
DROP TABLE IF EXISTS `expeditionMistake`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expeditionMistake` (
`expeditionFk` int(11) NOT NULL,
`workerFk` int(10) unsigned NOT NULL COMMENT 'Quien marca el error',
`typeFk` varchar(15) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`expeditionFk`),
KEY `expeditionMistake_FK_1` (`workerFk`),
KEY `expeditionMistake_FK_2` (`typeFk`),
CONSTRAINT `expeditionMistake_FK` FOREIGN KEY (`expeditionFk`) REFERENCES `expedition` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `expeditionMistake_FK_1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `expeditionMistake_FK_2` FOREIGN KEY (`typeFk`) REFERENCES `expeditionMistakeType` (`code`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Errores de encajadores';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `expeditionMistakeType`
--
DROP TABLE IF EXISTS `expeditionMistakeType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expeditionMistakeType` (
`code` varchar(15) NOT NULL,
`description` varchar(45) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `expeditionPallet`
--
DROP TABLE IF EXISTS `expeditionPallet`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expeditionPallet` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`truckFk` int(11) NOT NULL,
`built` datetime NOT NULL DEFAULT current_timestamp(),
`position` int(11) DEFAULT NULL,
`isPrint` tinyint(4) NOT NULL DEFAULT 2,
PRIMARY KEY (`id`),
KEY `expeditionPallet_fk1_idx` (`truckFk`),
CONSTRAINT `expeditionPallet_fk1` FOREIGN KEY (`truckFk`) REFERENCES `expeditionTruck` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `expeditionPallet_Print`
--
DROP TABLE IF EXISTS `expeditionPallet_Print`;
/*!50001 DROP VIEW IF EXISTS `expeditionPallet_Print`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `expeditionPallet_Print` AS SELECT
1 AS `truck`,
1 AS `routeFk`,
1 AS `zone`,
1 AS `eti`,
1 AS `palletFk`,
1 AS `isMatch`,
1 AS `warehouseFk`,
1 AS `nombreDia` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `expeditionRoute_Monitor`
--
DROP TABLE IF EXISTS `expeditionRoute_Monitor`;
/*!50001 DROP VIEW IF EXISTS `expeditionRoute_Monitor`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `expeditionRoute_Monitor` AS SELECT
1 AS `routeFk`,
1 AS `tickets`,
1 AS `expeditions`,
1 AS `scanned`,
1 AS `lastPacked`,
1 AS `created` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `expeditionRoute_freeTickets`
--
DROP TABLE IF EXISTS `expeditionRoute_freeTickets`;
/*!50001 DROP VIEW IF EXISTS `expeditionRoute_freeTickets`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `expeditionRoute_freeTickets` AS SELECT
1 AS `routeFk`,
1 AS `ticket`,
1 AS `code`,
1 AS `almacen`,
1 AS `updated`,
1 AS `parkingCode` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `expeditionScan`
--
DROP TABLE IF EXISTS `expeditionScan`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expeditionScan` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`expeditionFk` int(11) NOT NULL,
`scanned` datetime NOT NULL DEFAULT current_timestamp(),
`palletFk` int(11) NOT NULL,
`workerFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `expeditionFk_UNIQUE` (`expeditionFk`),
KEY `expeditionScan_fk1_idx` (`expeditionFk`),
KEY `expeditionScan_fk2_idx` (`palletFk`),
KEY `expeditionScan_fk3_idx` (`workerFk`),
CONSTRAINT `expeditionScan_fk1` FOREIGN KEY (`expeditionFk`) REFERENCES `expedition` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `expeditionScan_fk2` FOREIGN KEY (`palletFk`) REFERENCES `expeditionPallet` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `expeditionScan_fk3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `expeditionScan_Monitor`
--
DROP TABLE IF EXISTS `expeditionScan_Monitor`;
/*!50001 DROP VIEW IF EXISTS `expeditionScan_Monitor`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `expeditionScan_Monitor` AS SELECT
1 AS `truckFk`,
1 AS `ETD`,
1 AS `description`,
1 AS `palletFk`,
1 AS `position`,
1 AS `built`,
1 AS `scanFk`,
1 AS `expeditionFk`,
1 AS `scanned` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `expeditionState`
--
DROP TABLE IF EXISTS `expeditionState`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expeditionState` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`expeditionFk` int(11) NOT NULL,
`typeFk` int(11) NOT NULL,
`userFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `expeditionState_FK` (`expeditionFk`),
KEY `expeditionState_FK_1` (`typeFk`),
CONSTRAINT `expeditionState_FK` FOREIGN KEY (`expeditionFk`) REFERENCES `expedition` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `expeditionState_FK_1` FOREIGN KEY (`typeFk`) REFERENCES `expeditionStateType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Historico de estados de las expediciones';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `expeditionStateType`
--
DROP TABLE IF EXISTS `expeditionStateType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expeditionStateType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(100) NOT NULL,
`code` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Posibles estados de una expedición';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `expeditionSticker`
--
DROP TABLE IF EXISTS `expeditionSticker`;
/*!50001 DROP VIEW IF EXISTS `expeditionSticker`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `expeditionSticker` AS SELECT
1 AS `expeditionFk`,
1 AS `ticketFk`,
1 AS `addressFk`,
1 AS `clientFk`,
1 AS `street`,
1 AS `postalCode`,
1 AS `city`,
1 AS `nickname`,
1 AS `routeFk`,
1 AS `beachFk`,
1 AS `zona`,
1 AS `province`,
1 AS `phone`,
1 AS `workerCode` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `expeditionTicket_NoBoxes`
--
DROP TABLE IF EXISTS `expeditionTicket_NoBoxes`;
/*!50001 DROP VIEW IF EXISTS `expeditionTicket_NoBoxes`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `expeditionTicket_NoBoxes` AS SELECT
1 AS `ticketFk`,
1 AS `warehouseFk`,
1 AS `routeFk`,
1 AS `description` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `expeditionTimeExpended`
--
DROP TABLE IF EXISTS `expeditionTimeExpended`;
/*!50001 DROP VIEW IF EXISTS `expeditionTimeExpended`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `expeditionTimeExpended` AS SELECT
1 AS `ticketFk`,
1 AS `started`,
1 AS `finished`,
1 AS `cajas`,
1 AS `code`,
1 AS `warehouseFk` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `expeditionTruck`
--
DROP TABLE IF EXISTS `expeditionTruck`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expeditionTruck` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`roadmapFk` int(10) unsigned DEFAULT NULL,
`warehouseFk` smallint(6) unsigned DEFAULT NULL,
`eta` datetime DEFAULT NULL COMMENT 'Estimated time of arrival',
`description` varchar(45) NOT NULL,
`bufferFk` int(11) DEFAULT NULL COMMENT 'buffer destino de las cajas',
`created` timestamp NULL DEFAULT current_timestamp(),
`userFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `expeditionTruck_idx1` (`eta`),
KEY `expeditionTruck_FK` (`bufferFk`),
KEY `expeditionTruck_FK_1` (`warehouseFk`),
KEY `expeditionTruck_FK_2` (`roadmapFk`),
KEY `expeditionTruck_FK_3` (`userFk`),
CONSTRAINT `expeditionTruck_FK` FOREIGN KEY (`bufferFk`) REFERENCES `srt`.`buffer` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `expeditionTruck_FK_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
CONSTRAINT `expeditionTruck_FK_2` FOREIGN KEY (`roadmapFk`) REFERENCES `roadmap` (`id`) ON UPDATE CASCADE,
CONSTRAINT `expeditionTruck_FK_3` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Distintas paradas que hacen los trocales';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `expeditionTruck_Control`
--
DROP TABLE IF EXISTS `expeditionTruck_Control`;
/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `expeditionTruck_Control` AS SELECT
1 AS `id`,
1 AS `ETD`,
1 AS `description`,
1 AS `ticketsSinBultos`,
1 AS `pallets`,
1 AS `routes`,
1 AS `scans`,
1 AS `expeditions`,
1 AS `fallos`,
1 AS `lastPacked` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `expeditionTruck_Control_Detail`
--
DROP TABLE IF EXISTS `expeditionTruck_Control_Detail`;
/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control_Detail`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `expeditionTruck_Control_Detail` AS SELECT
1 AS `id`,
1 AS `eta`,
1 AS `destino`,
1 AS `pallet`,
1 AS `routes`,
1 AS `scans`,
1 AS `destinos`,
1 AS `fallos`,
1 AS `lastPacked` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `expeditionTruck_Control_Detail_Pallet`
--
DROP TABLE IF EXISTS `expeditionTruck_Control_Detail_Pallet`;
/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control_Detail_Pallet`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `expeditionTruck_Control_Detail_Pallet` AS SELECT
1 AS `id`,
1 AS `eta`,
1 AS `destino`,
1 AS `pallet`,
1 AS `route`,
1 AS `scans`,
1 AS `destinos`,
1 AS `fallos`,
1 AS `expeditionTruckFk`,
1 AS `lastPacked` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `expense`
--
DROP TABLE IF EXISTS `expense`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expense` (
`id` varchar(10) NOT NULL,
`name` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`isWithheld` tinyint(4) NOT NULL DEFAULT 0,
`code` varchar(25) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `expence_UN` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `expenseManual`
--
DROP TABLE IF EXISTS `expenseManual`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expenseManual` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`year` int(4) NOT NULL,
`month` int(2) NOT NULL,
`amount` decimal(10,2) DEFAULT NULL,
`companyFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `expenseManual_unique` (`expenseFk`,`year`,`month`,`companyFk`),
KEY `expenseManual_company_FK` (`companyFk`),
CONSTRAINT `expenseManual_company_FK` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `expenseManual_expense_FK` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Sirve para resumir los gastos que se ponen a mano en el contaplus';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `farming`
--
DROP TABLE IF EXISTS `farming`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `farming` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`location` varchar(255) DEFAULT NULL,
`warehouseFk` smallint(6) unsigned DEFAULT NULL,
`description` text DEFAULT NULL,
`photo` blob DEFAULT NULL,
`isActive` tinyint(1) NOT NULL DEFAULT 1,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`companyFk` int(10) unsigned NOT NULL DEFAULT 442,
PRIMARY KEY (`id`),
KEY `farming_FK` (`warehouseFk`),
KEY `farmingCompany_Fk` (`companyFk`),
CONSTRAINT `farmingCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`),
CONSTRAINT `farming_FK` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `farmingDeliveryNote`
--
DROP TABLE IF EXISTS `farmingDeliveryNote`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `farmingDeliveryNote` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`farmingFk` int(10) unsigned NOT NULL,
`deliveryNoteFk` int(11) NOT NULL,
`amount` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `farmingDeliveryNoteFk_FK` (`deliveryNoteFk`),
KEY `farmingDeliveryNoteFk_FK_1` (`farmingFk`),
CONSTRAINT `farmingDeliveryNoteFk_FK` FOREIGN KEY (`deliveryNoteFk`) REFERENCES `deliveryNote` (`id`),
CONSTRAINT `farmingDeliveryNoteFk_FK_1` FOREIGN KEY (`farmingFk`) REFERENCES `farming` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `farmingDms`
--
DROP TABLE IF EXISTS `farmingDms`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `farmingDms` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`farmingFk` int(10) unsigned NOT NULL,
`dmsFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `farmingDms_FK` (`farmingFk`),
KEY `farmingDms_FK_1` (`dmsFk`),
CONSTRAINT `farmingDms_FK` FOREIGN KEY (`farmingFk`) REFERENCES `farming` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `farmingDms_FK_1` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `farmingInvoiceIn`
--
DROP TABLE IF EXISTS `farmingInvoiceIn`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `farmingInvoiceIn` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`farmingFk` int(10) unsigned NOT NULL,
`invoiceInFk` mediumint(8) unsigned NOT NULL,
`amount` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `farmingInvoiceIn_FK` (`invoiceInFk`),
KEY `farmingInvoiceIn_FK_1` (`farmingFk`),
CONSTRAINT `farmingInvoiceIn_FK` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`),
CONSTRAINT `farmingInvoiceIn_FK_1` FOREIGN KEY (`farmingFk`) REFERENCES `farming` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `farmingNotes`
--
DROP TABLE IF EXISTS `farmingNotes`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `farmingNotes` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`farmingFk` int(10) unsigned NOT NULL,
`note` text NOT NULL,
`userFk` int(10) unsigned NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `farmingNotes_FK_1` (`farmingFk`),
CONSTRAINT `farmingNotes_FK` FOREIGN KEY (`id`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `farmingNotes_FK_1` FOREIGN KEY (`farmingFk`) REFERENCES `farming` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `financialProductType`
--
DROP TABLE IF EXISTS `financialProductType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `financialProductType` (
`id` varchar(2) NOT NULL,
`description` varchar(45) NOT NULL,
`isAcumulattor` tinyint(4) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `description_UNIQUE` (`description`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Distintos tipos de productos financieros: seguros de cambio, polizas de credito, acumuladores....';
/*!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;
--
-- Table structure for table `flight`
--
DROP TABLE IF EXISTS `flight`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `flight` (
`id` varchar(10) NOT NULL,
`duration` tinyint(2) unsigned NOT NULL,
`flightPath` varchar(20) DEFAULT NULL,
`days` varchar(7) DEFAULT NULL,
`airlineFk` smallint(2) unsigned DEFAULT NULL,
`airportArrivalFk` varchar(3) NOT NULL,
`airportDepartureFk` varchar(3) NOT NULL,
PRIMARY KEY (`id`),
KEY `flight_airline_FK` (`airlineFk`),
CONSTRAINT `flight_airline_FK` FOREIGN KEY (`airlineFk`) REFERENCES `airline` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 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 `floramondoConfig`
--
DROP TABLE IF EXISTS `floramondoConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `floramondoConfig` (
`id` int(10) unsigned NOT NULL,
`nextLanded` datetime DEFAULT NULL,
`warehouseInFk` smallint(6) unsigned DEFAULT NULL,
`MaxLatestDeliveryHour` int(11) DEFAULT NULL,
`MaxLatestOrderHour` int(11) DEFAULT 12 COMMENT 'Hora máxima para aceptar pedidos hoy',
`LastUpdated` datetime DEFAULT NULL,
`itemMaxSize` int(11) DEFAULT NULL COMMENT 'tamaño maximo de los articulos a mostrar',
`daysToKeepItem` int(4) DEFAULT NULL COMMENT 'Número de dias para mantener artículos',
PRIMARY KEY (`id`),
KEY `floramondoConfigWarehouseIn_idx` (`warehouseInFk`),
CONSTRAINT `floramondoConfigWarehouseInFk` FOREIGN KEY (`warehouseInFk`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `floramondoConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `forecastedBalance`
--
DROP TABLE IF EXISTS `forecastedBalance`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `forecastedBalance` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(45) DEFAULT NULL,
`amount` double NOT NULL DEFAULT 0,
`dated` date NOT NULL,
`accountingFk` int(11) DEFAULT NULL,
`companyFk` int(10) unsigned NOT NULL DEFAULT 442,
PRIMARY KEY (`id`),
KEY `Fecha_indice` (`dated`),
KEY `banco_prevision_idx` (`accountingFk`),
KEY `empresa_prevision_idx` (`companyFk`),
CONSTRAINT `Saldos_PrevisionCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `banco_prevision` FOREIGN KEY (`accountingFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Aqui ponemos los gastos e ingresos pendientes de introducir ';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `franceExpressConfig`
--
DROP TABLE IF EXISTS `franceExpressConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `franceExpressConfig` (
`id` int(10) unsigned NOT NULL,
`path` varchar(100) DEFAULT '\\\\server\\agencies\\franceexpress\\expeditions',
PRIMARY KEY (`id`),
CONSTRAINT `franceExpressConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 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) NOT NULL,
`code` varchar(45) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `genericAllocation`
--
DROP TABLE IF EXISTS `genericAllocation`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `genericAllocation` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`itemFk` int(11) NOT NULL,
`typeFk` smallint(5) unsigned NOT NULL COMMENT ' vn.itemType.id',
`origin` varchar(50) DEFAULT NULL,
`color` varchar(50) DEFAULT NULL,
`quality` varchar(10) DEFAULT NULL,
`numFlores` varchar(10) DEFAULT NULL,
`category` varchar(50) DEFAULT NULL,
`productor` varchar(50) DEFAULT NULL,
`longName` varchar(100) DEFAULT NULL,
`size` int(11) DEFAULT NULL,
`startDated` date DEFAULT NULL,
`endDated` date DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `genericAllocation_FK` (`itemFk`),
KEY `genericAllocation_FK_1` (`typeFk`),
KEY `genericAllocation_origin_IDX` (`origin`) USING BTREE,
KEY `genericAllocation_color_IDX` (`color`) USING BTREE,
KEY `genericAllocation_quality_IDX` (`quality`) USING BTREE,
KEY `genericAllocation_numFlores_IDX` (`numFlores`) USING BTREE,
KEY `genericAllocation_category_IDX` (`category`) USING BTREE,
KEY `genericAllocation_productor_IDX` (`productor`) USING BTREE,
KEY `genericAllocation_longName_IDX` (`longName`) USING BTREE,
KEY `genericAllocation_size_IDX` (`size`) USING BTREE,
CONSTRAINT `genericAllocation_FK` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacena los filtros para asignar códigos genéricos a los items';
/*!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` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `genus_PK2` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `glsConfig`
--
DROP TABLE IF EXISTS `glsConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `glsConfig` (
`id` int(10) unsigned NOT NULL,
`service` int(1) DEFAULT NULL,
`schedule` int(1) DEFAULT NULL,
`token` varchar(45) DEFAULT NULL,
`labelType` varchar(3) DEFAULT NULL,
`supplierFk` int(11) DEFAULT NULL,
`package` int(1) DEFAULT NULL,
`refund` int(1) DEFAULT NULL,
`weight` int(1) DEFAULT NULL,
`density` int(11) NOT NULL DEFAULT 42,
PRIMARY KEY (`id`),
CONSTRAINT `glsConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `glsExpedition`
--
DROP TABLE IF EXISTS `glsExpedition`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `glsExpedition` (
`expeditionFk` int(11) NOT NULL,
`barcode` varchar(20) DEFAULT NULL,
`uid` varchar(45) DEFAULT NULL COMMENT 'Valor retornado por GLS al hacer pertición al webservice',
`codexp` int(11) DEFAULT NULL COMMENT 'Valor retornado por GLS al hacer pertición al webservice',
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`expeditionFk`),
CONSTRAINT `glsExpedition_FK` FOREIGN KEY (`expeditionFk`) REFERENCES `expedition` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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(11) NOT NULL,
`description` varchar(45) 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,
`userFk` int(10) unsigned DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`Id`),
KEY `greuges_type_fk_idx` (`greugeTypeFk`),
KEY `Id_Ticket_Greuge_Ticket_idx` (`ticketFk`),
KEY `Greuges_cliente_idx` (`clientFk`),
KEY `greuge_shipped_IDX` (`shipped`) USING BTREE,
KEY `greuge_FK` (`userFk`),
KEY `greuge_fk_editor` (`editorFk`),
CONSTRAINT `Id_Ticket_Greuge_Ticket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `greuge_FK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `greuge_FK_1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `greuge_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `greuges_type_fk` FOREIGN KEY (`greugeTypeFk`) REFERENCES `greugeType` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci ROW_FORMAT=COMPACT;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `greugeConfig`
--
DROP TABLE IF EXISTS `greugeConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `greugeConfig` (
`id` int(10) unsigned NOT NULL,
`freightPickUpPrice` decimal(10,2) NOT NULL,
`yearsToDelete` int(11) DEFAULT NULL,
`maxPercentToWrong` decimal(10,2) DEFAULT NULL COMMENT 'Porcentaje del precio del ticket que es considerado error',
`lastNotifyCheck` timestamp NULL DEFAULT NULL COMMENT 'Última ejecución del procedimiento que revisa los greuges anormales',
`daysAgoOffset` int(11) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `greugeConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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) NOT NULL,
`code` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `host`
--
DROP TABLE IF EXISTS `host`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `host` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`description` varchar(50) DEFAULT NULL,
`workerFk` int(10) unsigned DEFAULT NULL,
`windowsSerial` varchar(40) DEFAULT NULL,
`printerFk` int(10) unsigned DEFAULT NULL,
`warehouseFk` smallint(5) unsigned DEFAULT 60,
`companyFk` int(10) unsigned DEFAULT 442,
`bankFk` int(11) DEFAULT 13,
`routeDaysBefore` smallint(6) DEFAULT 2,
`routeDaysAfter` smallint(6) DEFAULT 1,
`updated` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
UNIQUE KEY `host_UN` (`code`),
KEY `configHost_FK_3` (`companyFk`),
KEY `configHost_FK` (`printerFk`),
KEY `configHost_FK_2` (`warehouseFk`),
KEY `configHost_FK_4` (`bankFk`),
KEY `configHost_FK_5` (`workerFk`),
CONSTRAINT `configHost_FK_2` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
CONSTRAINT `configHost_FK_4` FOREIGN KEY (`bankFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE,
CONSTRAINT `configHost_FK_5` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`),
CONSTRAINT `hostCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `host_FK` FOREIGN KEY (`printerFk`) REFERENCES `printer` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `improvedGeneralLog`
--
DROP TABLE IF EXISTS `improvedGeneralLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `improvedGeneralLog` (
`user` char(128) NOT NULL DEFAULT '',
`db` char(64) NOT NULL DEFAULT '',
`tables` char(64) NOT NULL DEFAULT '',
`type` set('Select','Insert','Update','Delete') DEFAULT NULL,
PRIMARY KEY (`user`,`db`,`tables`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `improvedGeneralLogProcedures`
--
DROP TABLE IF EXISTS `improvedGeneralLogProcedures`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `improvedGeneralLogProcedures` (
`user` char(128) NOT NULL DEFAULT '',
`db` varchar(250) NOT NULL DEFAULT '',
`routine` char(64) NOT NULL DEFAULT '',
`type` enum('FUNCTION','PROCEDURE') NOT NULL,
PRIMARY KEY (`user`,`db`,`routine`,`type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `incoterms`
--
DROP TABLE IF EXISTS `incoterms`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `incoterms` (
`code` varchar(3) NOT NULL DEFAULT '',
`name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Internacional Commercial Terms';
/*!40101 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) NOT NULL,
`name` varchar(50) DEFAULT NULL,
`picture` blob NOT NULL,
`showOrder` int(11) NOT NULL,
`ball` blob DEFAULT NULL,
`isCargex` tinyint(4) NOT NULL DEFAULT 0,
`dutchCode` varchar(3) DEFAULT NULL,
`hex` varchar(6) DEFAULT NULL,
`isRealColor` tinyint(1) NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
UNIQUE KEY `dutchCode_UNIQUE` (`dutchCode`),
CONSTRAINT `ink_fk1` FOREIGN KEY (`dutchCode`) REFERENCES `edi`.`feature` (`feature_value`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`lang` char(2) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`inkFk`,`lang`),
CONSTRAINT `inkI18n_FK` FOREIGN KEY (`inkFk`) REFERENCES `ink` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `integra2`
--
DROP TABLE IF EXISTS `integra2`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `integra2` (
`postCode` varchar(10) NOT NULL,
`frequency` decimal(10,2) NOT NULL,
`warehouseFk` smallint(6) unsigned NOT NULL,
PRIMARY KEY (`postCode`,`frequency`,`warehouseFk`),
KEY `postal_code` (`postCode`),
KEY `warehouse_id` (`warehouseFk`),
CONSTRAINT `integra2_warehouse_FK` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `integra2Province`
--
DROP TABLE IF EXISTS `integra2Province`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `integra2Province` (
`provinceFk` smallint(6) unsigned NOT NULL,
`franchise` varchar(65) NOT NULL,
PRIMARY KEY (`provinceFk`),
CONSTRAINT `integra2_province_id` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `intrastat`
--
DROP TABLE IF EXISTS `intrastat`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `intrastat` (
`id` int(8) unsigned zerofill NOT NULL,
`description` varchar(50) DEFAULT NULL,
`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=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `inventoryConfig`
--
DROP TABLE IF EXISTS `inventoryConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `inventoryConfig` (
`id` int(10) unsigned NOT NULL,
`maxRecentInventories` int(11) DEFAULT NULL COMMENT 'The maximum number of recent inventories to retain without deletion',
`daysInPastForInventory` int(11) DEFAULT NULL COMMENT 'The number of days in the past to consider for inventory calculations',
`warehouseOutFk` smallint(6) unsigned DEFAULT NULL COMMENT 'The identifier for the inventory output warehouse',
`agencyModeFk` int(11) DEFAULT NULL COMMENT 'The identifier for the default inventory agencyMode',
`supplierFk` int(10) unsigned DEFAULT NULL COMMENT 'The identifier for the default inventory supplier',
PRIMARY KEY (`id`),
KEY `inventoryConfig_supplier_FK` (`supplierFk`),
KEY `inventoryConfig_warehouse_FK` (`warehouseOutFk`),
KEY `inventoryConfig_agencyMode_FK` (`agencyModeFk`),
CONSTRAINT `inventoryConfig_agencyMode_FK` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`),
CONSTRAINT `inventoryConfig_supplier_FK` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`),
CONSTRAINT `inventoryConfig_warehouse_FK_1` FOREIGN KEY (`warehouseOutFk`) REFERENCES `warehouse` (`id`),
CONSTRAINT `inventoryConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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(10) unsigned DEFAULT NULL,
`guiltyFk` int(10) unsigned DEFAULT NULL,
`causeFk` int(11) DEFAULT NULL,
`explanation` varchar(250) 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`siiTypeInvoiceOutFk` 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` (`siiTypeInvoiceOutFk`),
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 `cplusRectificationType_FK` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `cplusRectificationType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceCorrectionType_FK` FOREIGN KEY (`invoiceCorrectionTypeFk`) REFERENCES `invoiceCorrectionType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `siiTypeInvoiceOut_FK` FOREIGN KEY (`siiTypeInvoiceOutFk`) REFERENCES `siiTypeInvoiceOut` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `description_UNIQUE` (`description`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `invoiceIn`
--
DROP TABLE IF EXISTS `invoiceIn`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceIn` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`serialNumber` mediumint(11) unsigned DEFAULT NULL COMMENT 'insertado por Trigger',
`serial` char(1) NOT NULL DEFAULT 'R',
`supplierFk` int(10) unsigned NOT NULL,
`issued` date DEFAULT NULL COMMENT 'Fecha de emision de la factura',
`supplierRef` varchar(50) DEFAULT NULL,
`isBooked` tinyint(1) NOT NULL DEFAULT 0,
`currencyFk` tinyint(3) unsigned NOT NULL DEFAULT 1,
`created` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`companyFk` int(10) unsigned NOT NULL DEFAULT 442,
`docFk` int(11) DEFAULT NULL,
`booked` date DEFAULT NULL COMMENT 'Fecha de contabilizacion',
`operated` date DEFAULT NULL COMMENT 'Fecha de entrega de la mercancia o el suministro',
`siiTypeInvoiceInFk` int(10) unsigned DEFAULT 1,
`cplusRectificationTypeFk` int(10) unsigned DEFAULT 1,
`cplusSubjectOpFk` int(10) unsigned DEFAULT 1,
`cplusTaxBreakFk` int(10) unsigned DEFAULT 1,
`siiTrascendencyInvoiceInFk` int(10) unsigned DEFAULT 1,
`bookEntried` date DEFAULT NULL COMMENT 'Fecha Asiento',
`isVatDeductible` tinyint(1) NOT NULL DEFAULT 1,
`withholdingSageFk` smallint(6) DEFAULT NULL COMMENT 'Tipos de retención SAGE',
`expenseFkDeductible` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `proveedor_id` (`supplierFk`),
KEY `empresa_id` (`companyFk`),
KEY `serie` (`serial`),
KEY `num_recibida_2` (`serialNumber`),
KEY `gestdoc_id` (`docFk`),
KEY `fecha` (`issued`),
KEY `recibida_ibfk_3_idx` (`cplusSubjectOpFk`),
KEY `recibida_ibfk_4_idx` (`cplusTaxBreakFk`),
KEY `recibida_ibfk_5_idx` (`siiTypeInvoiceInFk`),
KEY `recibida_ibfk_6` (`cplusRectificationTypeFk`),
KEY `recibida_ibfk_7` (`siiTrascendencyInvoiceInFk`),
KEY `invoiceIn_withholdingFk_idx` (`withholdingSageFk`),
KEY `invoiceIn_expenceFkDeductible_idx` (`expenseFkDeductible`),
KEY `invoiceIn_fk_editor` (`editorFk`),
KEY `invoiceIn_FK` (`currencyFk`),
CONSTRAINT `invoiceInCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_FK` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_expenceFkDeductible` FOREIGN KEY (`expenseFkDeductible`) REFERENCES `expense` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `invoiceIn_ibfk_3` FOREIGN KEY (`cplusSubjectOpFk`) REFERENCES `cplusSubjectOp` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_ibfk_4` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `cplusTaxBreak` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_ibfk_5` FOREIGN KEY (`siiTypeInvoiceInFk`) REFERENCES `siiTypeInvoiceIn` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_ibfk_6` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `cplusRectificationType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_ibfk_7` FOREIGN KEY (`siiTrascendencyInvoiceInFk`) REFERENCES `siiTrascendencyInvoiceIn` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_withholdingFk` FOREIGN KEY (`withholdingSageFk`) REFERENCES `sage`.`TiposRetencion` (`CodigoRetencion`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `invoiceInConfig`
--
DROP TABLE IF EXISTS `invoiceInConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceInConfig` (
`id` int(10) unsigned NOT NULL,
`retentionRate` int(3) NOT NULL,
`retentionName` varchar(25) NOT NULL,
`sageWithholdingFk` smallint(6) NOT NULL,
`daysAgo` int(10) unsigned DEFAULT 45 COMMENT 'Días en el pasado para mostrar facturas en invoiceIn series en salix',
`taxRowLimit` int(11) DEFAULT 4 COMMENT 'Número máximo de líneas de IVA que puede tener una factura',
PRIMARY KEY (`id`),
KEY `invoiceInConfig_sageWithholdingFk` (`sageWithholdingFk`),
CONSTRAINT `invoiceInConfig_sageWithholdingFk` FOREIGN KEY (`sageWithholdingFk`) REFERENCES `sage`.`TiposRetencion` (`CodigoRetencion`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `invoiceInConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `invoiceInCorrection`
--
DROP TABLE IF EXISTS `invoiceInCorrection`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceInCorrection` (
`correctingFk` mediumint(8) unsigned NOT NULL COMMENT 'Factura rectificativa',
`correctedFk` mediumint(8) unsigned NOT NULL COMMENT 'Factura rectificada',
`cplusRectificationTypeFk` int(10) unsigned NOT NULL,
`siiTypeInvoiceOutFk` int(10) unsigned NOT NULL,
`invoiceCorrectionTypeFk` int(11) NOT NULL DEFAULT 3,
PRIMARY KEY (`correctingFk`),
KEY `invoiceInCorrection_correctedFk` (`correctedFk`),
KEY `invoiceInCorrection_cplusRectificationTypeFk` (`cplusRectificationTypeFk`),
KEY `invoiceInCorrection_siiTypeInvoiceOut` (`siiTypeInvoiceOutFk`),
KEY `invoiceInCorrection_invoiceCorrectionTypeFk` (`invoiceCorrectionTypeFk`),
CONSTRAINT `invoiceInCorrection_correctedFk` FOREIGN KEY (`correctedFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `invoiceInCorrection_correctingFk` FOREIGN KEY (`correctingFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `invoiceInCorrection_cplusRectificationTypeFk` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `cplusRectificationType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInCorrection_invoiceCorrectionTypeFk` FOREIGN KEY (`invoiceCorrectionTypeFk`) REFERENCES `invoiceCorrectionType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInCorrection_siiTypeInvoiceOut` FOREIGN KEY (`siiTypeInvoiceOutFk`) REFERENCES `siiTypeInvoiceOut` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `invoiceInDueDay`
--
DROP TABLE IF EXISTS `invoiceInDueDay`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceInDueDay` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`invoiceInFk` mediumint(8) unsigned NOT NULL,
`dueDated` date NOT NULL,
`bankFk` int(11) NOT NULL DEFAULT 3117,
`amount` decimal(10,2) NOT NULL DEFAULT 0.00,
`foreignValue` decimal(10,2) DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `recibida_id` (`invoiceInFk`),
KEY `banco_id` (`bankFk`),
KEY `invoiceInDueDay_fk_editor` (`editorFk`),
CONSTRAINT `invoiceInDueDay_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `invoiceInDueDay_ibfk_6` FOREIGN KEY (`bankFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInDueDay_ibfk_7` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `invoiceInIntrastat`
--
DROP TABLE IF EXISTS `invoiceInIntrastat`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceInIntrastat` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`invoiceInFk` mediumint(8) unsigned NOT NULL,
`net` decimal(10,2) DEFAULT NULL,
`intrastatFk` int(8) unsigned zerofill NOT NULL DEFAULT 06049190,
`amount` double NOT NULL,
`stems` int(11) NOT NULL,
`countryFk` mediumint(8) unsigned DEFAULT NULL,
`dated` timestamp NOT NULL DEFAULT current_timestamp(),
`statisticalValue` double NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY `intrastat_id` (`intrastatFk`),
KEY `invoiceInIntrastat_FK` (`invoiceInFk`),
CONSTRAINT `invoiceInIntrastat_FK` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE,
CONSTRAINT `invoiceInIntrastat_ibfk_1` FOREIGN KEY (`intrastatFk`) REFERENCES `intrastat` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `invoiceInLog`
--
DROP TABLE IF EXISTS `invoiceInLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceInLog` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`originFk` mediumint(8) unsigned DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` enum('InvoiceIn','InvoiceInTax','InvoiceInDueDay') NOT NULL DEFAULT 'InvoiceIn',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `userFk` (`userFk`),
KEY `invoiceInLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `invoiceInLog_originFk` (`originFk`,`creationDate`),
CONSTRAINT `invoiceInLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `invoiceInSage`
--
DROP TABLE IF EXISTS `invoiceInSage`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceInSage` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`taxClassFk` varchar(1) NOT NULL,
`invoiceInSerialFk` varchar(2) NOT NULL,
`taxTypeSageFk` smallint(6) NOT NULL,
`transactionTypeSageFk` tinyint(4) NOT NULL,
`isService` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Para diferenciar producto de servicio',
`expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`withholdingSageFk` smallint(6) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `invoiceInSafe_unique` (`taxClassFk`,`invoiceInSerialFk`,`isService`,`withholdingSageFk`),
KEY `invoiceInSage_withholdingSageFk` (`withholdingSageFk`),
KEY `invoiceInSage_taxClassFk` (`taxClassFk`),
KEY `invoiceInSage_invoiceInSerialFk` (`invoiceInSerialFk`),
KEY `invoiceInSage_taxTypeSageFk` (`taxTypeSageFk`),
KEY `invoiceInSage_transactionTypeSageFk` (`transactionTypeSageFk`),
KEY `invoiceInSage_idx` (`expenseFk`),
CONSTRAINT `invoiceInSage_expenceFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInSage_invoiceInSerialFk` FOREIGN KEY (`invoiceInSerialFk`) REFERENCES `invoiceInSerial` (`code`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInSage_taxClassFk` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`code`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInSage_taxTypeSageFk` FOREIGN KEY (`taxTypeSageFk`) REFERENCES `sage`.`TiposIva` (`CodigoIva`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInSage_transactionTypeSageFk` FOREIGN KEY (`transactionTypeSageFk`) REFERENCES `sage`.`TiposTransacciones` (`CodigoTransaccion`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInSage_withholdingSageFk` FOREIGN KEY (`withholdingSageFk`) REFERENCES `sage`.`TiposRetencion` (`CodigoRetencion`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Relaciones de entrelas series de facturas recibidas y sus tipo de IVA con código Iva y codigo de Transación en Sage. Para precontabilizadar facturas recibidas';
/*!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) NOT NULL,
`description` varchar(45) DEFAULT NULL,
`cplusTerIdNifFk` int(11) NOT NULL DEFAULT 1,
`taxAreaFk` varchar(15) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci 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=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `invoiceInTax`
--
DROP TABLE IF EXISTS `invoiceInTax`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceInTax` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`invoiceInFk` mediumint(8) unsigned NOT NULL,
`taxCodeFk` int(10) DEFAULT NULL,
`taxableBase` decimal(10,2) NOT NULL,
`expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`foreignValue` decimal(10,2) DEFAULT NULL,
`taxTypeSageFk` smallint(6) DEFAULT NULL COMMENT 'Tipo de IVA SAGE',
`transactionTypeSageFk` tinyint(4) DEFAULT NULL COMMENT 'Tipo de transacción SAGE',
`created` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `recibida_id` (`invoiceInFk`),
KEY `recibida_iva_ibfk_2` (`taxCodeFk`),
KEY `recibida_iva_taxTypeSageFk` (`taxTypeSageFk`),
KEY `invoiceInTax_transactionTypeSageFk_idx` (`transactionTypeSageFk`),
KEY `invoiceInTax_idx` (`expenseFk`),
KEY `invoiceInTax_fk_editor` (`editorFk`),
CONSTRAINT `invoiceInTax_expenceFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInTax_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `invoiceInTax_ibfk_5` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `invoiceInTax_transactionTypeSageFk` FOREIGN KEY (`transactionTypeSageFk`) REFERENCES `sage`.`TiposTransacciones` (`CodigoTransaccion`) ON UPDATE CASCADE,
CONSTRAINT `recibida_iva_taxTypeSageFk` FOREIGN KEY (`taxTypeSageFk`) REFERENCES `sage`.`TiposIva` (`CodigoIva`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`taxAreaFk` varchar(15) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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(20) NOT NULL,
`serial` varchar(2) 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,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`companyFk` int(10) unsigned NOT NULL DEFAULT 442,
`hasPdf` tinyint(3) unsigned NOT NULL DEFAULT 0,
`booked` date DEFAULT NULL,
`siiTypeInvoiceOutFk` int(10) unsigned NOT NULL DEFAULT 1,
`cplusTaxBreakFk` int(10) unsigned NOT NULL DEFAULT 1,
`cplusSubjectOpFk` int(10) unsigned NOT NULL DEFAULT 1,
`siiTrascendencyInvoiceOutFk` 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 `empresa_id` (`companyFk`),
KEY `Fecha` (`issued`),
KEY `Facturas_ibfk_2_idx` (`siiTypeInvoiceOutFk`),
KEY `Facturas_ibfk_3_idx` (`cplusSubjectOpFk`),
KEY `Facturas_ibfk_4_idx` (`cplusTaxBreakFk`),
KEY `Facturas_ibfk_5_idx` (`siiTrascendencyInvoiceOutFk`),
KEY `Facturas_idx_Vencimiento` (`dued`),
KEY `invoiceOut_serial` (`serial`),
CONSTRAINT `invoiceOut_ibfk_2` FOREIGN KEY (`siiTypeInvoiceOutFk`) REFERENCES `siiTypeInvoiceOut` (`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 `invoiceOut_serial` FOREIGN KEY (`serial`) REFERENCES `invoiceOutSerial` (`code`),
CONSTRAINT `invoice_bank_id` FOREIGN KEY (`bankFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoice_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `invoiceOutConfig`
--
DROP TABLE IF EXISTS `invoiceOutConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceOutConfig` (
`id` int(10) unsigned NOT NULL,
`parallelism` int(10) unsigned NOT NULL DEFAULT 1,
`refLen` tinyint(3) unsigned NOT NULL DEFAULT 5 COMMENT 'Invoice reference identifier length',
PRIMARY KEY (`id`),
CONSTRAINT `invoiceOutConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `invoiceOutExpense`
--
DROP TABLE IF EXISTS `invoiceOutExpense`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceOutExpense` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`invoiceOutFk` int(10) unsigned NOT NULL,
`amount` decimal(10,2) NOT NULL DEFAULT 0.00,
`expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`created` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `invoiceOutExpence_FK_1_idx` (`invoiceOutFk`),
KEY `invoiceOutExpence_expenceFk_idx` (`expenseFk`),
CONSTRAINT `invoiceOutExpence_FK_1` FOREIGN KEY (`invoiceOutFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `invoiceOutExpence_expenceFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`description` varchar(45) DEFAULT NULL,
`isTaxed` tinyint(1) NOT NULL DEFAULT 1,
`taxAreaFk` varchar(15) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'NATIONAL',
`isCEE` tinyint(1) NOT NULL DEFAULT 0,
`cplusInvoiceType477Fk` int(10) unsigned DEFAULT 1,
`footNotes` longtext DEFAULT NULL,
`isRefEditable` tinyint(4) NOT NULL DEFAULT 0,
`type` enum('global','quick') DEFAULT NULL,
PRIMARY KEY (`code`),
KEY `taxAreaFk_idx` (`taxAreaFk`),
CONSTRAINT `invoiceOutSeriaTaxArea` FOREIGN KEY (`taxAreaFk`) REFERENCES `taxArea` (`code`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `invoiceOutTaxConfig`
--
DROP TABLE IF EXISTS `invoiceOutTaxConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceOutTaxConfig` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`taxClassCodeFk` varchar(1) DEFAULT NULL,
`taxTypeSageFk` smallint(6) DEFAULT NULL,
`transactionTypeSageFk` tinyint(4) DEFAULT NULL,
`isService` tinyint(1) DEFAULT 0,
`expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `invoiceOutTaxConfig_FK` (`taxClassCodeFk`),
KEY `invoiceOutTaxConfig_FK_1` (`taxTypeSageFk`),
KEY `invoiceOutTaxConfig_FK_2` (`transactionTypeSageFk`),
KEY `invoiceOutTaxConfig_expense_FK` (`expenseFk`),
CONSTRAINT `invoiceOutTaxConfig_FK` FOREIGN KEY (`taxClassCodeFk`) REFERENCES `taxClass` (`code`),
CONSTRAINT `invoiceOutTaxConfig_FK_1` FOREIGN KEY (`taxTypeSageFk`) REFERENCES `sage`.`TiposIva` (`CodigoIva`),
CONSTRAINT `invoiceOutTaxConfig_FK_2` FOREIGN KEY (`transactionTypeSageFk`) REFERENCES `sage`.`TiposTransacciones` (`CodigoTransaccion`),
CONSTRAINT `invoiceOutTaxConfig_expense_FK` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`size` int(10) unsigned DEFAULT NULL,
`stems` int(11) DEFAULT 1,
`minPrice` double DEFAULT 0,
`isToPrint` tinyint(1) NOT NULL DEFAULT 0,
`family` varchar(3) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'VT',
`box` tinyint(1) NOT NULL DEFAULT 0,
`category` varchar(3) DEFAULT NULL,
`originFk` tinyint(2) unsigned NOT NULL,
`doPhoto` tinyint(4) NOT NULL DEFAULT 0,
`image` varchar(255) DEFAULT NULL,
`inkFk` varchar(3) DEFAULT NULL,
`intrastatFk` int(8) unsigned zerofill NOT NULL DEFAULT 06039010,
`hasMinPrice` tinyint(1) NOT NULL DEFAULT 0,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`comment` varchar(150) DEFAULT NULL COMMENT 'referencia del proveedor',
`typeFk` smallint(5) unsigned NOT NULL,
`generic` tinyint(1) unsigned zerofill NOT NULL DEFAULT 0,
`producerFk` mediumint(3) unsigned DEFAULT NULL,
`description` varchar(1000) 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 COMMENT 'La web ordena de forma descendiente por este campo para mostrar los artículos',
`expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '7001000000',
`isActive` tinyint(1) NOT NULL DEFAULT 1,
`longName` varchar(50) DEFAULT NULL,
`subName` varchar(50) DEFAULT NULL,
`tag5` varchar(20) DEFAULT NULL,
`value5` varchar(50) DEFAULT NULL,
`tag6` varchar(20) DEFAULT NULL,
`value6` varchar(50) DEFAULT NULL,
`tag7` varchar(20) DEFAULT NULL,
`value7` varchar(50) DEFAULT NULL,
`tag8` varchar(20) DEFAULT NULL,
`value8` varchar(50) DEFAULT NULL,
`tag9` varchar(20) DEFAULT NULL,
`value9` varchar(50) DEFAULT NULL,
`tag10` varchar(20) DEFAULT NULL,
`value10` varchar(50) DEFAULT NULL,
`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 ',
`supplyResponseFk` int(11) DEFAULT NULL,
`hasKgPrice` tinyint(1) NOT NULL DEFAULT 0,
`isFloramondo` tinyint(1) NOT NULL DEFAULT 0,
`isFragile` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'articulos solo para recogidas por su fragilidad',
`numberOfItemsPerCask` int(11) DEFAULT NULL COMMENT 'Campo para Floramondo',
`embalageCode` int(11) DEFAULT NULL COMMENT 'Campo para Floramondo',
`quality` varchar(255) DEFAULT NULL COMMENT 'Campo para Floramondo',
`stemMultiplier` double NOT NULL DEFAULT 1 COMMENT 'este valor multiplica las unidades y divide los precios en el procedimiento edi.ekt_load',
`itemPackingTypeFk` varchar(1) DEFAULT NULL,
`packingOut` decimal(10,2) DEFAULT NULL COMMENT 'cantidad que cabe en una caja de verdnatura',
`genericFk` int(11) DEFAULT NULL COMMENT 'Item genérico',
`packingShelve__` int(11) DEFAULT NULL COMMENT '@deprecated 2024-31-01',
`isLaid` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Indica si el producto se puede tumbar a efectos del transporte desde Holanda',
`lastUsed` datetime DEFAULT current_timestamp(),
`weightByPiece` int(10) unsigned DEFAULT NULL COMMENT 'peso por defecto para un articulo por tallo/unidad',
`editorFk` int(10) unsigned DEFAULT NULL,
`recycledPlastic` int(11) DEFAULT NULL,
`nonRecycledPlastic` int(11) DEFAULT NULL,
`minQuantity` int(10) unsigned DEFAULT NULL COMMENT 'Cantidad mínima para una línea de venta',
`isBoxPickingMode` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'FALSE: using item.packingOut TRUE: boxPicking using itemShelving.packing',
PRIMARY KEY (`id`),
UNIQUE KEY `item_supplyResponseFk_idx` (`supplyResponseFk`),
KEY `Color` (`inkFk`),
KEY `id_origen` (`originFk`),
KEY `Codintrastat` (`intrastatFk`),
KEY `tipo_id` (`typeFk`),
KEY `producer_id` (`producerFk`),
KEY `ArticlesIsActive_idx` (`isActive`),
KEY `Article` (`name`,`subName`,`value5`,`value6`,`value7`,`value8`,`value9`,`value10`),
KEY `item_id10` (`embalageCode`),
KEY `item_id11` (`numberOfItemsPerCask`),
KEY `item_id12` (`quality`),
KEY `item_family` (`family`),
KEY `item_FK` (`genericFk`),
KEY `item_size_IDX` (`size`) USING BTREE,
KEY `item_size_IDX2` (`longName`) USING BTREE,
KEY `item_lastUsed_IDX` (`lastUsed`) USING BTREE,
KEY `item_expenceFk_idx` (`expenseFk`),
KEY `item_fk_editor` (`editorFk`),
CONSTRAINT `item_FK` FOREIGN KEY (`genericFk`) REFERENCES `item` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `item_FK_1` FOREIGN KEY (`typeFk`) REFERENCES `itemType` (`id`),
CONSTRAINT `item_expenceFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE,
CONSTRAINT `item_family` FOREIGN KEY (`family`) REFERENCES `itemFamily` (`code`) ON UPDATE CASCADE,
CONSTRAINT `item_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
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 `itemsupplyResponseFk` FOREIGN KEY (`supplyResponseFk`) REFERENCES `edi`.`supplyResponse` (`ID`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `producer_id` FOREIGN KEY (`producerFk`) REFERENCES `producer` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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) NOT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code` (`code`),
UNIQUE KEY `Id_Article_2` (`itemFk`,`code`),
KEY `Id_Article` (`itemFk`),
KEY `itemBarcode_fk_editor` (`editorFk`),
CONSTRAINT `itemBarcode_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `itemBarcode_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`genusFk` int(11) NOT NULL,
`specieFk` int(11) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`itemFk`),
KEY `genusFgn_idx` (`genusFk`),
KEY `specieFgn_idx` (`specieFk`),
KEY `itemBotanical_fk_editor` (`editorFk`),
CONSTRAINT `itemBotanicalItemFkFk` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `itemBotanical_FK` FOREIGN KEY (`specieFk`) REFERENCES `specie` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `itemBotanical_FK_1` FOREIGN KEY (`genusFk`) REFERENCES `genus` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `itemBotanical_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Sustituye a antiguo NomBotanic de Articles';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `itemBotanicalWithGenus`
--
DROP TABLE IF EXISTS `itemBotanicalWithGenus`;
/*!50001 DROP VIEW IF EXISTS `itemBotanicalWithGenus`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemBotanicalWithGenus` AS SELECT
1 AS `itemFk`,
1 AS `ediBotanic` */;
SET character_set_client = @saved_cs_client;
--
-- 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) NOT NULL,
`order` int(10) unsigned DEFAULT NULL,
`display` tinyint(4) NOT NULL DEFAULT 1,
`color` char(6) 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) DEFAULT NULL,
`code` varchar(45) DEFAULT NULL,
`isReclining` tinyint(4) NOT NULL DEFAULT 1,
`departmentFk` int(11) DEFAULT NULL COMMENT 'Departamento responsable del manufacturado de esta categoria',
PRIMARY KEY (`id`),
UNIQUE KEY `reino_UNIQUE` (`name`),
KEY `itemCategory_idx3` (`merchandise`),
KEY `itemCategoryDisplayIdx` (`display`),
KEY `itemCategory_FK` (`departmentFk`),
CONSTRAINT `itemCategory_FK` FOREIGN KEY (`departmentFk`) REFERENCES `department` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`categoryFk`,`lang`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `itemCleanLog`
--
DROP TABLE IF EXISTS `itemCleanLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemCleanLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`itemDeleted` int(11) DEFAULT NULL COMMENT 'Indica la cantidad de items que ha eliminado',
`created` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `itemColor`
--
DROP TABLE IF EXISTS `itemColor`;
/*!50001 DROP VIEW IF EXISTS `itemColor`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemColor` AS SELECT
1 AS `itemFk`,
1 AS `color` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `itemConfig`
--
DROP TABLE IF EXISTS `itemConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemConfig` (
`id` int(10) unsigned NOT NULL,
`isItemTagTriggerDisabled` tinyint(1) NOT NULL DEFAULT 1,
`monthToDeactivate` int(3) NOT NULL DEFAULT 24,
`wasteRecipients` varchar(50) NOT NULL COMMENT 'Weekly waste report schedule recipients',
`defaultTag` int(11) NOT NULL DEFAULT 56,
`validPriorities` varchar(50) NOT NULL DEFAULT '[1,2,3]',
`defaultPriority` int(11) NOT NULL DEFAULT 2,
`warehouseFk` smallint(6) unsigned DEFAULT NULL,
`downloadMaxAttempts` tinyint(3) DEFAULT NULL COMMENT 'Intentos máximos para que se borre',
PRIMARY KEY (`id`),
KEY `itemConfig_FK` (`defaultTag`),
CONSTRAINT `itemConfig_FK` FOREIGN KEY (`defaultTag`) REFERENCES `tag` (`id`),
CONSTRAINT `itemConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `itemCost`
--
DROP TABLE IF EXISTS `itemCost`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemCost` (
`itemFk` int(11) NOT NULL,
`warehouseFk` smallint(6) unsigned NOT NULL,
`quantity` int(10) NOT NULL DEFAULT 0,
`rotation` decimal(10,4) NOT NULL DEFAULT 0.0000,
`cm3` int(11) NOT NULL DEFAULT 0,
`storage` decimal(10,4) NOT NULL DEFAULT 0.0000,
`handling` decimal(10,4) NOT NULL DEFAULT 0.0000,
`extraCharge` decimal(10,4) NOT NULL DEFAULT 0.0000,
`wasted` decimal(10,4) NOT NULL DEFAULT 0.0000,
`cm3delivery` int(11) NOT NULL DEFAULT 0,
`grams` int(11) NOT NULL DEFAULT 0 COMMENT 'peso en gramos de una unidad de venta',
`created` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`itemFk`,`warehouseFk`),
KEY `warehouse_id_rotacion_idx` (`warehouseFk`),
CONSTRAINT `id_article_rotaci` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `warehouse_id_rotaci` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacena los valores de rotacion en los ultimos 365 dias';
/*!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 `itemFamily`
--
DROP TABLE IF EXISTS `itemFamily`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemFamily` (
`code` varchar(3) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`description` varchar(45) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `itemImageQueue`
--
DROP TABLE IF EXISTS `itemImageQueue`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemImageQueue` (
`itemFk` int(11) NOT NULL,
`url` varchar(255) NOT NULL,
`error` text DEFAULT NULL,
`attempts` int(11) DEFAULT 0,
`created` timestamp NULL DEFAULT current_timestamp(),
`updated` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`priority` int(11) DEFAULT 99,
PRIMARY KEY (`itemFk`),
CONSTRAINT `itemImageQueueItemIdx` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Cola para añadir las imagenes al campo vn.item.image a partir de una url';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `itemInk`
--
DROP TABLE IF EXISTS `itemInk`;
/*!50001 DROP VIEW IF EXISTS `itemInk`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemInk` AS SELECT
1 AS `longName`,
1 AS `inkFk`,
1 AS `color` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `itemLabel`
--
DROP TABLE IF EXISTS `itemLabel`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemLabel` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`itemFk` int(11) DEFAULT NULL,
`itemName` varchar(20) DEFAULT NULL,
`price` decimal(10,2) DEFAULT NULL,
`labels` int(11) DEFAULT NULL COMMENT 'Tabla hecha para Ruben Espinosa, para sacar etiquetas en Holanda para un cliente.',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` enum('Item','ItemBarcode','ItemBotanical','ItemNiche','ItemTag','ItemTaxCountry') NOT NULL DEFAULT 'Item',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `itemLogUserFk_idx` (`userFk`),
KEY `itemLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `itemLog_originFk` (`originFk`,`creationDate`),
CONSTRAINT `itemLogUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `itemMatchProperties`
--
DROP TABLE IF EXISTS `itemMatchProperties`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemMatchProperties` (
`itemFk` int(11) NOT NULL,
`name` varchar(80) NOT NULL,
`producer` varchar(80) NOT NULL,
`size` int(11) NOT NULL,
PRIMARY KEY (`itemFk`,`name`,`producer`,`size`),
CONSTRAINT `itemFk___fk` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Propiedades para encontrar articulos equivalentes en verdnatura';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `itemPackingType`
--
DROP TABLE IF EXISTS `itemPackingType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemPackingType` (
`code` varchar(1) NOT NULL,
`description` varchar(100) NOT NULL,
`isActive` tinyint(1) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Define la linea de encajado para cada producto';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `itemPlacementSupply`
--
DROP TABLE IF EXISTS `itemPlacementSupply`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemPlacementSupply` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`itemFk` int(11) NOT NULL,
`quantity` decimal(10,0) NOT NULL DEFAULT 0,
`priority` int(10) unsigned NOT NULL DEFAULT 0,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`userFk` int(10) unsigned NOT NULL COMMENT 'Persona que crea la orden',
`repoUserFk` int(10) unsigned DEFAULT NULL COMMENT 'Reponedor que la tiene asignada',
`sectorFk` int(11) DEFAULT NULL,
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `sectorFk` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `itemProductor`
--
DROP TABLE IF EXISTS `itemProductor`;
/*!50001 DROP VIEW IF EXISTS `itemProductor`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemProductor` AS SELECT
1 AS `itemFk`,
1 AS `productor` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `itemProposal`
--
DROP TABLE IF EXISTS `itemProposal`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemProposal` (
`itemFk` int(11) NOT NULL,
`mateFk` int(11) NOT NULL,
`counter` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`itemFk`,`mateFk`),
KEY `itemProposal_fk2_idx` (`mateFk`),
CONSTRAINT `itemProposal_fk1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `itemProposal_fk2` FOREIGN KEY (`mateFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='almacena los cambios realizados de unos items por otros, cuando faltaban los primeros';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `itemSearch`
--
DROP TABLE IF EXISTS `itemSearch`;
/*!50001 DROP VIEW IF EXISTS `itemSearch`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemSearch` AS SELECT
1 AS `itemFk`,
1 AS `concept`,
1 AS `quantity`,
1 AS `nickname`,
1 AS `shipped` */;
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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`visible` int(11) NOT NULL DEFAULT 0,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`grouping` smallint(5) unsigned DEFAULT NULL,
`packing` int(11) NOT NULL DEFAULT 1 CHECK (`packing` > 0),
`packagingFk` varchar(10) DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`isChecked` tinyint(1) DEFAULT NULL COMMENT 'Este valor cambia al escanear un carro. True: Existe. False: Nuevo. Null: No escaneado',
`buyFk` int(11) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `itemShelving_UN` (`buyFk`,`shelvingFk`),
KEY `itemShelving_fk1_idx` (`itemFk`),
KEY `itemShelving_fk2_idx` (`shelvingFk`),
KEY `itemShelving_fk3_idx` (`packagingFk`),
KEY `itemShelving_fk3_idx1` (`userFk`),
CONSTRAINT `itemShelvingBuy_FK` FOREIGN KEY (`buyFk`) REFERENCES `buy` (`id`),
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla utilizada para localizar los artículos dentro de los carros. Usado para la gestión del almacén en el altillo ';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `itemShelvingAvailable`
--
DROP TABLE IF EXISTS `itemShelvingAvailable`;
/*!50001 DROP VIEW IF EXISTS `itemShelvingAvailable`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemShelvingAvailable` AS SELECT
1 AS `saleFk`,
1 AS `Modificado`,
1 AS `ticketFk`,
1 AS `isPicked`,
1 AS `itemFk`,
1 AS `quantity`,
1 AS `concept`,
1 AS `size`,
1 AS `Estado`,
1 AS `sectorProdPriority`,
1 AS `available`,
1 AS `sectorFk`,
1 AS `matricula`,
1 AS `parking`,
1 AS `itemShelving`,
1 AS `Agency`,
1 AS `shipped`,
1 AS `grouping`,
1 AS `packing`,
1 AS `hour`,
1 AS `isPreviousPreparable`,
1 AS `physicalVolume`,
1 AS `warehouseFk` */;
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`,
1 AS `sectorFk` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `itemShelvingLog`
--
DROP TABLE IF EXISTS `itemShelvingLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemShelvingLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`itemShelvingFk` int(10) unsigned DEFAULT NULL,
`workerFk` int(11) DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`accion` varchar(20) DEFAULT NULL,
`itemFk` int(11) DEFAULT NULL,
`shelvingFk` varchar(10) DEFAULT NULL,
`quantity` int(11) DEFAULT NULL,
`visible` int(11) DEFAULT NULL,
`available` int(11) DEFAULT NULL,
`grouping` int(11) DEFAULT NULL,
`packing` int(11) DEFAULT NULL,
`stars` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `itemShelving_Log_FK` (`itemShelvingFk`),
KEY `itemShelvingLog_itemFk_IDX` (`itemFk`) USING BTREE,
KEY `itemShelvingLog_shelvingFk_IDX` (`shelvingFk`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `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;
--
-- 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,
`isPicked` tinyint(1) NOT NULL DEFAULT 0,
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Detalle del producto que se retira de los carros, relacionando la linea de movimiento correspondiente';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `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`,
1 AS `isPreviousPrepared` */;
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) DEFAULT NULL,
`intValue` int(11) DEFAULT NULL,
`priority` int(2) NOT NULL DEFAULT 0,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `itemTagItemUq` (`itemFk`,`tagFk`),
UNIQUE KEY `itemTagItemPriority` (`itemFk`,`priority`),
KEY `tagFk` (`tagFk`,`value`),
KEY `priorityItem` (`priority`,`itemFk`),
KEY `value` (`value`),
KEY `itemFk_2` (`itemFk`,`tagFk`,`intValue`),
KEY `itemTag_fk_editor` (`editorFk`),
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,
CONSTRAINT `itemTag_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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(),
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `itemFk_UNIQUE` (`itemFk`,`countryFk`),
KEY `taxClassFK_idx` (`taxClassFk`),
KEY `countryFK_paises_idx` (`countryFk`),
KEY `itemTaxCountry_fk_editor` (`editorFk`),
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 `itemTaxCountry_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `taxClassFK_Iva_Group` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Define la clase de iva por artículo y pais';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `itemTaxCountrySpain`
--
DROP TABLE IF EXISTS `itemTaxCountrySpain`;
/*!50001 DROP VIEW IF EXISTS `itemTaxCountrySpain`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `itemTaxCountrySpain` AS SELECT
1 AS `id`,
1 AS `name`,
1 AS `typeFk`,
1 AS `stems`,
1 AS `description`,
1 AS `intrastatFk`,
1 AS `expenseFk`,
1 AS `comment`,
1 AS `relevancy`,
1 AS `image`,
1 AS `generic`,
1 AS `taxClassFk` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `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) NOT NULL,
`name` varchar(30) NOT NULL,
`gramsMax` int(11) DEFAULT NULL,
`order` int(11) DEFAULT 0,
`categoryFk` int(10) unsigned NOT NULL,
`workerFk` int(10) unsigned 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(),
`transaction__` tinyint(4) NOT NULL DEFAULT 0,
`making` int(10) unsigned DEFAULT NULL COMMENT 'Son productos de confección propia',
`location__` varchar(10) 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,
`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,
`isPackaging` tinyint(1) NOT NULL DEFAULT 0,
`hasComponents__` tinyint(1) NOT NULL DEFAULT 1,
`warehouseFk__` smallint(6) unsigned NOT NULL DEFAULT 60,
`compression__` decimal(5,2) DEFAULT 1.00,
`itemPackingTypeFk` varchar(1) DEFAULT NULL,
`temperatureFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`isUnconventionalSize` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'familia con productos cuyas medidas no son aptas para la cinta transportadora o paletizar',
`isLaid` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Indica si el producto se puede tumbar a efectos del transporte desde Holanda',
`maxRefs` int(10) unsigned DEFAULT NULL COMMENT 'Indica el número máximo de referencias',
`isMergeable` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'Articulos que al mergear los tickets se fusionara la linea',
`isFragile` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `Tipo_UNIQUE` (`name`,`categoryFk`),
UNIQUE KEY `itemType_UN` (`code`),
KEY `Trabajador` (`workerFk`),
KEY `reino_id` (`categoryFk`),
KEY `Tipos_fk3_idx` (`making`),
KEY `warehouseFk5_idx` (`warehouseFk__`),
KEY `temperatureFk` (`temperatureFk`),
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 `temperatureFk` FOREIGN KEY (`temperatureFk`) REFERENCES `temperature` (`code`),
CONSTRAINT `warehouseFk5` FOREIGN KEY (`warehouseFk__`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 */;
--
-- 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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`typeFk`,`lang`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `itemTypeRestriction`
--
DROP TABLE IF EXISTS `itemTypeRestriction`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemTypeRestriction` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`itemTypeFk` smallint(5) unsigned NOT NULL,
`dated` date NOT NULL,
`minAmount` decimal(10,2) NOT NULL COMMENT 'importe mínimo en la linea de venta',
PRIMARY KEY (`id`),
UNIQUE KEY `itemTypeRestriction_UN` (`itemTypeFk`,`dated`),
KEY `itemTypeRestriction_dated_IDX` (`dated`,`itemTypeFk`) USING BTREE,
CONSTRAINT `itemTypeRestriction_FK` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 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 `itemTypeTag_FK` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `item_Free_Id`
--
DROP TABLE IF EXISTS `item_Free_Id`;
/*!50001 DROP VIEW IF EXISTS `item_Free_Id`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `item_Free_Id` AS SELECT
1 AS `newId` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `labelInfo`
--
DROP TABLE IF EXISTS `labelInfo`;
/*!50001 DROP VIEW IF EXISTS `labelInfo`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `labelInfo` AS SELECT
1 AS `itemId`,
1 AS `itemName`,
1 AS `stickers`,
1 AS `life`,
1 AS `colorCode`,
1 AS `stems`,
1 AS `category`,
1 AS `productor`,
1 AS `packing`,
1 AS `warehouse_id`,
1 AS `size`,
1 AS `isPickedOff`,
1 AS `notes`,
1 AS `wh_in`,
1 AS `entryId`,
1 AS `buyId` */;
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) 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=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `lastHourProduction`
--
DROP TABLE IF EXISTS `lastHourProduction`;
/*!50001 DROP VIEW IF EXISTS `lastHourProduction`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `lastHourProduction` AS SELECT
1 AS `warehouseFk`,
1 AS `m3` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `lastPurchases`
--
DROP TABLE IF EXISTS `lastPurchases`;
/*!50001 DROP VIEW IF EXISTS `lastPurchases`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `lastPurchases` AS SELECT
1 AS `landed`,
1 AS `warehouseFk`,
1 AS `warehouse`,
1 AS `longName`,
1 AS `subName`,
1 AS `entryFk`,
1 AS `stickers`,
1 AS `packing`,
1 AS `ref`,
1 AS `itemFk`,
1 AS `pro`,
1 AS `ektRef`,
1 AS `agj` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `lastTopClaims`
--
DROP TABLE IF EXISTS `lastTopClaims`;
/*!50001 DROP VIEW IF EXISTS `lastTopClaims`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `lastTopClaims` AS SELECT
1 AS `itemFk`,
1 AS `itemName`,
1 AS `itemTypeName`,
1 AS `claimsNumber`,
1 AS `claimedAmount`,
1 AS `totalAmount` */;
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,
`maxTolerance` decimal(10,2) NOT NULL,
PRIMARY KEY (`lastBookEntry`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `lungSize`
--
DROP TABLE IF EXISTS `lungSize`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `lungSize` (
`hora` time NOT NULL,
`size` decimal(5,0) NOT NULL,
`dia` date NOT NULL,
PRIMARY KEY (`hora`,`size`,`dia`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `machine`
--
DROP TABLE IF EXISTS `machine`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `machine` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`plate` varchar(20) DEFAULT NULL,
`serialNumber` varchar(30) DEFAULT NULL,
`maker` varchar(50) DEFAULT NULL,
`model` varchar(20) DEFAULT NULL,
`purchased` date DEFAULT NULL,
`warehouseFk` int(11) DEFAULT NULL,
`departmentFk` int(11) DEFAULT NULL,
`type` varchar(100) DEFAULT NULL,
`use` varchar(100) DEFAULT NULL,
`productionYear` int(11) DEFAULT NULL,
`photo` blob DEFAULT NULL,
`workerFk` int(10) unsigned DEFAULT NULL,
`companyFk` smallint(5) unsigned NOT NULL DEFAULT 442,
`ppeFk` int(11) DEFAULT NULL,
`supplierFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `plate` (`plate`),
UNIQUE KEY `serialNumber` (`serialNumber`),
KEY `machine_FK` (`ppeFk`),
KEY `machine_FK_1` (`workerFk`),
KEY `machine_supplierFk` (`supplierFk`),
CONSTRAINT `machine_FK` FOREIGN KEY (`ppeFk`) REFERENCES `ppe` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `machine_FK_1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `machine_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Maquinaria industrial, vehículos y demás elementos amortizables';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `machineDetail`
--
DROP TABLE IF EXISTS `machineDetail`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `machineDetail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`machineFk` int(11) NOT NULL,
`dated` date NOT NULL,
`action` varchar(100) NOT NULL,
`value` decimal(10,2) DEFAULT NULL,
`workerFk` int(10) unsigned NOT NULL,
`dmsFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `machineDetail_FK` (`machineFk`),
KEY `machineDetail_FK_2` (`dmsFk`),
KEY `machineDetail_FK_1` (`workerFk`),
CONSTRAINT `machineDetail_FK` FOREIGN KEY (`machineFk`) REFERENCES `machine` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `machineDetail_FK_1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `machineDetail_FK_2` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `machineDms`
--
DROP TABLE IF EXISTS `machineDms`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `machineDms` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`machineFk` int(11) NOT NULL,
`dmsFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `machineDms_UN` (`machineFk`,`dmsFk`),
KEY `machineDms_FK` (`dmsFk`),
CONSTRAINT `machineDms_FK` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `machineDms_FK_1` FOREIGN KEY (`machineFk`) REFERENCES `machine` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `machineWorker`
--
DROP TABLE IF EXISTS `machineWorker`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `machineWorker` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`workerFk` int(10) unsigned NOT NULL,
`machineFk` int(11) NOT NULL,
`inTimed` datetime NOT NULL DEFAULT current_timestamp(),
`outTimed` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `machineWorker_FK_1` (`machineFk`),
KEY `machineWorker_FK` (`workerFk`),
CONSTRAINT `machineWorker_FK` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `machineWorker_FK_1` FOREIGN KEY (`machineFk`) REFERENCES `machine` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Registros horarios de vehículos de almacén por empleado';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `machineWorkerConfig`
--
DROP TABLE IF EXISTS `machineWorkerConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `machineWorkerConfig` (
`id` int(10) unsigned NOT NULL,
`maxHours` smallint(5) unsigned NOT NULL COMMENT 'Indicates how many hours a user record is reviewed to update or insert',
PRIMARY KEY (`id`),
CONSTRAINT `machineWorkerConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`receiver` varchar(255) DEFAULT NULL,
`sender` varchar(255) DEFAULT NULL,
`replyTo` varchar(50) DEFAULT NULL,
`subject` varchar(100) NOT NULL,
`body` text NOT NULL,
`sent` tinyint(2) NOT NULL DEFAULT 0,
`creationDate` timestamp NOT NULL DEFAULT current_timestamp(),
`attachment` varchar(100) DEFAULT NULL,
`status` varchar(255) NOT NULL DEFAULT 'OK',
`senderFk` int(10) unsigned DEFAULT NULL,
`recipientFk` int(10) unsigned DEFAULT NULL,
`plainTextBody` text DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `sent_idx` (`sent`),
KEY `creation_idx` (`creationDate`),
KEY `mail_FK_1` (`recipientFk`),
KEY `mail_FK` (`senderFk`),
CONSTRAINT `mail_FK` FOREIGN KEY (`senderFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE,
CONSTRAINT `mail_FK_1` FOREIGN KEY (`recipientFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`attachmentPath` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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` int(10) unsigned NOT NULL,
`code` varchar(32) 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 `mandateCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `mandato_fgkey1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`description` text DEFAULT NULL,
`enabled` tinyint(1) NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `mdbApp`
--
DROP TABLE IF EXISTS `mdbApp`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mdbApp` (
`app` varchar(100) NOT NULL,
`baselineBranchFk` varchar(255) NOT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`locked` datetime DEFAULT NULL,
PRIMARY KEY (`app`),
KEY `mdbApp_FK` (`userFk`),
KEY `mdbApp_FK_1` (`baselineBranchFk`),
CONSTRAINT `mdbApp_FK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `mdbApp_FK_1` FOREIGN KEY (`baselineBranchFk`) REFERENCES `mdbBranch` (`name`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `mdbBranch`
--
DROP TABLE IF EXISTS `mdbBranch`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mdbBranch` (
`name` varchar(255) NOT NULL DEFAULT '',
`dsName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `mdbConfig`
--
DROP TABLE IF EXISTS `mdbConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mdbConfig` (
`id` int(10) unsigned NOT NULL,
`issueTrackerUrl` varchar(255) NOT NULL,
`issueNumberRegex` varchar(255) NOT NULL,
`chatDestination` varchar(255) NOT NULL COMMENT 'User (@) or channel (#) to send the message',
PRIMARY KEY (`id`),
CONSTRAINT `mdbConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Global configuration parameters for Access';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `mdbVersion`
--
DROP TABLE IF EXISTS `mdbVersion`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mdbVersion` (
`app` varchar(255) NOT NULL,
`branchFk` varchar(255) NOT NULL,
`version` int(11) DEFAULT NULL,
PRIMARY KEY (`app`,`branchFk`),
KEY `mdbVersion_branchFk` (`branchFk`),
CONSTRAINT `mdbVersion_branchFk` FOREIGN KEY (`branchFk`) REFERENCES `mdbBranch` (`name`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `mdbVersionTree`
--
DROP TABLE IF EXISTS `mdbVersionTree`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mdbVersionTree` (
`app` varchar(255) NOT NULL,
`version` int(10) unsigned NOT NULL,
`branchFk` varchar(255) NOT NULL,
`fromVersion` int(10) unsigned NOT NULL,
`userFk` int(10) unsigned NOT NULL,
`description` text DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`app`,`version`),
KEY `mdbVersionTree_FK` (`userFk`),
KEY `mdbVersionTree_FK_2` (`branchFk`),
CONSTRAINT `mdbVersionTree_FK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE,
CONSTRAINT `mdbVersionTree_FK_2` FOREIGN KEY (`branchFk`) REFERENCES `mdbBranch` (`name`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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(10) unsigned NOT NULL,
`centerFk` int(11) NOT NULL,
`date` date DEFAULT NULL,
`time` varchar(5) DEFAULT NULL,
`isFit` tinyint(1) DEFAULT NULL,
`amount` double DEFAULT NULL,
`invoice` varchar(10) DEFAULT NULL,
`remark` longtext DEFAULT NULL,
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`sender` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`recipient` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`message` longtext CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`sendDate` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `sender` (`sender`),
KEY `recipient` (`recipient`),
KEY `uuid` (`uuid`(8))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`sender` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`recipient` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`finalRecipient` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`message` longtext CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`sendDate` timestamp NULL DEFAULT current_timestamp(),
`read` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `uuid` (`uuid`(8)),
KEY `finalRecipient` (`finalRecipient`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `mistake`
--
DROP TABLE IF EXISTS `mistake`;
/*!50001 DROP VIEW IF EXISTS `mistake`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `mistake` AS SELECT
1 AS `revisador`,
1 AS `concept`,
1 AS `sacador`,
1 AS `firstName`,
1 AS `lastName`,
1 AS `description`,
1 AS `created`,
1 AS `workerFk` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `mistakeRatio`
--
DROP TABLE IF EXISTS `mistakeRatio`;
/*!50001 DROP VIEW IF EXISTS `mistakeRatio`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `mistakeRatio` AS SELECT
1 AS `revisador`,
1 AS `sacador`,
1 AS `firstName`,
1 AS `lastName`,
1 AS `description`,
1 AS `created`,
1 AS `workerFk`,
1 AS `saleFk` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `mistakeType`
--
DROP TABLE IF EXISTS `mistakeType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mistakeType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`version` varchar(45) NOT NULL DEFAULT '0',
`isVersionCritical` tinyint(1) DEFAULT 0,
`urlProduction` varchar(100) DEFAULT NULL,
`urlBeta` varchar(100) DEFAULT NULL,
`versionBeta` varchar(45) DEFAULT NULL,
`isVersionBetaCritical` tinyint(1) DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `mrw`
--
DROP TABLE IF EXISTS `mrw`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mrw` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ticketFk` int(11) NOT NULL,
`counter` smallint(5) unsigned DEFAULT NULL,
`shipped` date DEFAULT NULL,
`price` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `mrwConfig`
--
DROP TABLE IF EXISTS `mrwConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mrwConfig` (
`id` int(10) unsigned NOT NULL,
`url` varchar(100) DEFAULT NULL,
`user` varchar(100) DEFAULT NULL,
`password` varchar(100) DEFAULT NULL,
`franchiseCode` varchar(100) DEFAULT NULL,
`subscriberCode` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `mrwConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `mrwService`
--
DROP TABLE IF EXISTS `mrwService`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mrwService` (
`agencyModeCodeFk` varchar(45) NOT NULL,
`clientType` int(11) unsigned NOT NULL,
`serviceType` int(11) unsigned DEFAULT NULL,
`kg` int(11) DEFAULT NULL,
PRIMARY KEY (`agencyModeCodeFk`),
CONSTRAINT `mrwService_agencyModeCodeFk` FOREIGN KEY (`agencyModeCodeFk`) REFERENCES `agencyMode` (`code`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Configuración de los servicios de MRW';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `mrwServiceWeekday`
--
DROP TABLE IF EXISTS `mrwServiceWeekday`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mrwServiceWeekday` (
`agencyModeCodeFk` varchar(45) NOT NULL,
`weekdays` set('mon','tue','wed','thu','fri','sat','sun') NOT NULL,
`serviceType` int(11) unsigned NOT NULL,
`params` varchar(255) DEFAULT NULL,
PRIMARY KEY (`agencyModeCodeFk`),
CONSTRAINT `mrwServiceWeekday_agencyModeCodeFk` FOREIGN KEY (`agencyModeCodeFk`) REFERENCES `agencyMode` (`code`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Configuración de los servicios en relación con el día de la semana para MRW';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `negativeOrigin`
--
DROP TABLE IF EXISTS `negativeOrigin`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `negativeOrigin` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`itemFk` int(11) NOT NULL,
`type` enum('FALTAS','CONTENEDOR','ENTRADAS','OVERBOOKING') NOT NULL,
`dated` date DEFAULT curdate(),
`quantity` decimal(10,2) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_constraint` (`itemFk`,`type`,`dated`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `newBornSales`
--
DROP TABLE IF EXISTS `newBornSales`;
/*!50001 DROP VIEW IF EXISTS `newBornSales`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `newBornSales` AS SELECT
1 AS `amount`,
1 AS `clientFk`,
1 AS `userFk`,
1 AS `dated`,
1 AS `firstShipped` */;
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) DEFAULT NULL,
`name` varchar(50) NOT NULL,
`subject` varchar(50) DEFAULT NULL,
`description` text DEFAULT NULL,
`isEnabled` tinyint(1) NOT NULL DEFAULT 1,
`requiredRole` int(11) NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
UNIQUE KEY `keyName_UNIQUE` (`keyName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`code` varchar(45) NOT NULL,
`hasNewBornMessage` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Indica aquellos que deben de recibir un mensaje advirtiendo de un cliente nuevo',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `occupationCode`
--
DROP TABLE IF EXISTS `occupationCode`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `occupationCode` (
`code` varchar(1) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`name` varchar(100) DEFAULT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Código de ocupación de la seguridad social';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `operator`
--
DROP TABLE IF EXISTS `operator`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `operator` (
`workerFk` int(10) unsigned NOT NULL,
`numberOfWagons` int(11) DEFAULT 2,
`trainFk` int(11) NOT NULL DEFAULT 1,
`itemPackingTypeFk` varchar(1) NOT NULL DEFAULT 'H',
`warehouseFk` smallint(6) unsigned NOT NULL DEFAULT 60,
`sectorFk` int(11) DEFAULT NULL,
`labelerFk` int(10) unsigned DEFAULT NULL,
`linesLimit` int(11) DEFAULT 20 COMMENT 'Límite de lineas en una colección para la asignación de pedidos',
`volumeLimit` decimal(10,6) DEFAULT 0.500000 COMMENT 'Límite de volumen en una colección para la asignación de pedidos',
PRIMARY KEY (`workerFk`),
KEY `operator_FK` (`workerFk`),
KEY `operator_FK_1` (`trainFk`),
KEY `operator_FK_2` (`itemPackingTypeFk`),
KEY `operator_FK_3` (`warehouseFk`),
KEY `operator_FK_5` (`labelerFk`),
KEY `operator_FK_4` (`sectorFk`),
CONSTRAINT `operator_FK` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `operator_FK_1` FOREIGN KEY (`trainFk`) REFERENCES `train` (`id`) ON UPDATE CASCADE,
CONSTRAINT `operator_FK_2` FOREIGN KEY (`itemPackingTypeFk`) REFERENCES `itemPackingType` (`code`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `operator_FK_3` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `operator_FK_4` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `operatorWorkerCode`
--
DROP TABLE IF EXISTS `operatorWorkerCode`;
/*!50001 DROP VIEW IF EXISTS `operatorWorkerCode`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `operatorWorkerCode` AS SELECT
1 AS `workerFk`,
1 AS `fullName`,
1 AS `code`,
1 AS `numberOfWagons` */;
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`),
CONSTRAINT `hedera_id` FOREIGN KEY (`orderFk`) REFERENCES `hedera`.`order` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `idTicketFk` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`name` varchar(20) NOT NULL,
`warehouseFk` smallint(5) unsigned DEFAULT 4,
`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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`originFk`,`lang`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `osTicketConfig`
--
DROP TABLE IF EXISTS `osTicketConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `osTicketConfig` (
`id` int(10) unsigned NOT NULL,
`host` varchar(100) DEFAULT NULL,
`user` varchar(100) DEFAULT NULL,
`password` varchar(100) DEFAULT NULL,
`oldStatus` varchar(100) DEFAULT NULL,
`newStatusId` int(11) DEFAULT NULL,
`day` int(11) DEFAULT NULL,
`comment` varchar(100) DEFAULT NULL,
`hostDb` varchar(100) DEFAULT NULL,
`userDb` varchar(100) DEFAULT NULL,
`passwordDb` varchar(100) DEFAULT NULL,
`portDb` int(11) DEFAULT NULL,
`responseType` varchar(100) DEFAULT NULL,
`fromEmailId` int(11) DEFAULT NULL,
`replyTo` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `osTicketConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `outgoingInvoiceVat`
--
DROP TABLE IF EXISTS `outgoingInvoiceVat`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `outgoingInvoiceVat` (
`outgoingInvoice` mediumint(8) NOT NULL,
`taxBase` decimal(12,2) DEFAULT NULL,
`equalizationTax` decimal(12,2) DEFAULT NULL,
`Vat` decimal(12,2) DEFAULT NULL,
PRIMARY KEY (`outgoingInvoice`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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` (
`packagingFk` varchar(10) NOT NULL,
`equivalentFk` varchar(10) NOT NULL,
PRIMARY KEY (`packagingFk`,`equivalentFk`),
KEY `packageEquivalent_fk2_idx` (`equivalentFk`),
CONSTRAINT `packageEquivalent_fk1` FOREIGN KEY (`packagingFk`) 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=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`volume` decimal(10,2) DEFAULT NULL CHECK (`volume` >= coalesce(`width`,1) * coalesce(`depth`,1) * coalesce(`height`,1)),
`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) NOT NULL DEFAULT 0.00,
`itemFk` int(11) DEFAULT NULL,
`price` decimal(10,2) NOT NULL DEFAULT 0.00,
`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) DEFAULT NULL,
`freightItemFk` int(11) DEFAULT NULL,
`hasCompressionVariations` tinyint(1) DEFAULT 0 COMMENT 'Floramondo puede servirlos no llenos del todo',
`conveyorBuildingClassFk` int(11) DEFAULT NULL,
`isTrolley` tinyint(1) NOT NULL DEFAULT 0,
`isPallet` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY `packaging_fk1` (`itemFk`),
KEY `packaging_fk2_idx` (`freightItemFk`),
KEY `packaging_FK` (`conveyorBuildingClassFk`),
KEY `packaging_FK_1` (`packagingReturnFk`),
CONSTRAINT `packaging_FK` FOREIGN KEY (`conveyorBuildingClassFk`) REFERENCES `conveyorBuildingClass` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `packaging_FK_1` FOREIGN KEY (`packagingReturnFk`) REFERENCES `returnBuckets` (`id`) ON UPDATE CASCADE,
CONSTRAINT `packaging_fk1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE,
CONSTRAINT `packaging_fk2` FOREIGN KEY (`freightItemFk`) REFERENCES `item` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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(10) unsigned NOT NULL,
`upperGap` int(11) NOT NULL,
`previousPreparationMinimumSize` int(11) NOT NULL,
`defaultConveyorBuildingClass` int(11) NOT NULL,
`palletPackaging` varchar(10) DEFAULT 'pallet USA',
`carryPackaging` varchar(10) DEFAULT 'cc',
`freightItemPackaging` int(11) DEFAULT 71,
`defaultSmallPackageFk` varchar(10) NOT NULL DEFAULT '94p' COMMENT 'bulto pequeño',
`defaultBigPackageFk` varchar(10) NOT NULL DEFAULT '94m' COMMENT 'bulto grande',
PRIMARY KEY (`id`),
KEY `packagingConfig_FK` (`defaultSmallPackageFk`),
KEY `packagingConfig_FK_1` (`defaultBigPackageFk`),
CONSTRAINT `packagingConfig_FK` FOREIGN KEY (`defaultSmallPackageFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE,
CONSTRAINT `packagingConfig_FK_1` FOREIGN KEY (`defaultBigPackageFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE,
CONSTRAINT `packagingConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Altura mínima para preparar pedidos en preparacion previa';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `packagingGifts`
--
DROP TABLE IF EXISTS `packagingGifts`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `packagingGifts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(255) NOT NULL,
`photo` blob DEFAULT NULL,
`started` date NOT NULL,
`ended` date NOT NULL,
`warehouseFk` smallint(5) unsigned DEFAULT NULL,
`provinceFk` smallint(5) unsigned DEFAULT NULL,
`countryFk` mediumint(8) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `PackagingGifts_FK_2` (`countryFk`),
KEY `PackagingGifts_FK` (`provinceFk`),
KEY `PackagingGifts_FK_1` (`warehouseFk`),
CONSTRAINT `PackagingGifts_FK` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`),
CONSTRAINT `PackagingGifts_FK_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`),
CONSTRAINT `PackagingGifts_FK_2` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `packagingWithFreight`
--
DROP TABLE IF EXISTS `packagingWithFreight`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `packagingWithFreight` (
`packagingFk` varchar(10) NOT NULL,
`priority` int(11) NOT NULL,
PRIMARY KEY (`packagingFk`),
UNIQUE KEY `packagingWithFreight_UN` (`priority`),
CONSTRAINT `packagingWithFreight_FK` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Embalajes con porte para encajado';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `packagingWithoutFreight`
--
DROP TABLE IF EXISTS `packagingWithoutFreight`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `packagingWithoutFreight` (
`packagingFk` varchar(10) NOT NULL,
`priority` int(11) NOT NULL,
PRIMARY KEY (`packagingFk`),
UNIQUE KEY `packagingWithoutFreight_UN` (`priority`),
CONSTRAINT `packagingWithoutFreight_FK` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Embalajes sin porte para encajar';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `packingSite`
--
DROP TABLE IF EXISTS `packingSite`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `packingSite` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(10) DEFAULT NULL,
`hostFk` int(11) DEFAULT NULL,
`printerRfidFk` int(10) unsigned DEFAULT NULL,
`printerFk` int(10) unsigned DEFAULT NULL,
`collectionFk` int(11) DEFAULT NULL COMMENT 'Last collection packed on this site',
`monitorId` varchar(255) DEFAULT NULL,
`parkingFk` int(11) DEFAULT NULL,
`scannerFk` int(11) DEFAULT NULL,
`screenFk` int(11) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
`hasNewLabelMrwMethod` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `packingSite_UN` (`code`),
UNIQUE KEY `printerRfidFk` (`printerRfidFk`),
UNIQUE KEY `scannerFk` (`scannerFk`),
UNIQUE KEY `screenFk` (`screenFk`),
UNIQUE KEY `packingSite_UNI` (`hostFk`),
KEY `packingSite_FK_1` (`printerFk`),
KEY `packingSite_FK_2` (`collectionFk`),
KEY `packingSite_FK_3` (`parkingFk`),
CONSTRAINT `packingSite_FK` FOREIGN KEY (`hostFk`) REFERENCES `host` (`id`),
CONSTRAINT `packingSite_FK_1` FOREIGN KEY (`printerFk`) REFERENCES `printer` (`id`),
CONSTRAINT `packingSite_FK_2` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `packingSite_FK_3` FOREIGN KEY (`parkingFk`) REFERENCES `parking` (`id`) ON DELETE CASCADE ON UPDATE SET NULL,
CONSTRAINT `packingSite_FK_4` FOREIGN KEY (`printerRfidFk`) REFERENCES `printer` (`id`) ON UPDATE CASCADE,
CONSTRAINT `packingSite_FK_5` FOREIGN KEY (`scannerFk`) REFERENCES `scanner` (`id`) ON UPDATE CASCADE,
CONSTRAINT `packingSite_FK_6` FOREIGN KEY (`screenFk`) REFERENCES `screen` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `packingSiteAdvanced`
--
DROP TABLE IF EXISTS `packingSiteAdvanced`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `packingSiteAdvanced` (
`ticketFk` int(11) NOT NULL,
`workerFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`ticketFk`),
KEY `packingSiteAdvanced_FK_1` (`workerFk`),
CONSTRAINT `packingSiteAdvanced_FK` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `packingSiteAdvanced_FK_1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `packingSiteConfig`
--
DROP TABLE IF EXISTS `packingSiteConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `packingSiteConfig` (
`id` int(10) unsigned NOT NULL,
`shinobiUrl` varchar(255) NOT NULL,
`shinobiToken` varchar(255) NOT NULL,
`shinobiGroupKey` varchar(255) NOT NULL,
`avgBoxingTime` int(3) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `packingSiteConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `packingSiteDeviceLog`
--
DROP TABLE IF EXISTS `packingSiteDeviceLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `packingSiteDeviceLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`originFk` int(11) DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` enum('PackingSite') NOT NULL DEFAULT 'PackingSite',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `userFk` (`userFk`),
KEY `packingSiteDeviceLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `packingSiteDeviceLog_packingSiteDeviceLog` (`originFk`,`creationDate`),
CONSTRAINT `packingSiteDeviceLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `packingSiteLog`
--
DROP TABLE IF EXISTS `packingSiteLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `packingSiteLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`packingSiteFk` varchar(10) DEFAULT NULL,
`hostFk` varchar(15) NOT NULL,
`workerFk` int(10) unsigned NOT NULL,
`printerModelFk` varchar(50) DEFAULT NULL,
`typeErrorFk` varchar(30) DEFAULT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `packingSiteLog_UN` (`id`),
KEY `packingSiteLog_FK` (`workerFk`),
KEY `packingSiteLog_FK_4` (`typeErrorFk`),
KEY `packingSiteLog_FK_1` (`printerModelFk`),
KEY `packingSiteLog_FK_2` (`packingSiteFk`),
CONSTRAINT `packingSiteLog_FK` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`),
CONSTRAINT `packingSiteLog_FK_1` FOREIGN KEY (`printerModelFk`) REFERENCES `printerModel` (`code`) ON UPDATE CASCADE,
CONSTRAINT `packingSiteLog_FK_2` FOREIGN KEY (`packingSiteFk`) REFERENCES `packingSite` (`code`) ON UPDATE CASCADE,
CONSTRAINT `packingSiteLog_FK_4` FOREIGN KEY (`typeErrorFk`) REFERENCES `packingSiteTypeError` (`code`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `packingSiteTypeError`
--
DROP TABLE IF EXISTS `packingSiteTypeError`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `packingSiteTypeError` (
`code` varchar(30) NOT NULL,
`description` varchar(100) DEFAULT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `paperSize`
--
DROP TABLE IF EXISTS `paperSize`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `paperSize` (
`code` varchar(100) NOT NULL,
`color` varchar(100) NOT NULL,
`alias` varchar(100) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci DEFAULT '--',
`row` varchar(5) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT '--',
`sectorFk` int(11) NOT NULL,
`code` varchar(8) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`pickingOrder` int(11) DEFAULT NULL,
`editorFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
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,
CONSTRAINT `chkParkingCodeFormat` CHECK (char_length(`code`) > 4 and `code` like '%-%')
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla con los parkings del altillo';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `parkingLog`
--
DROP TABLE IF EXISTS `parkingLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `parkingLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`originFk` int(11) DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete','select') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` enum('Parking','SaleGroup','SaleGroupDetail') NOT NULL DEFAULT 'Parking',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `logParkinguserFk` (`userFk`),
KEY `parkingLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `parkingLog_originFk` (`originFk`,`creationDate`),
CONSTRAINT `parkingOriginFk` FOREIGN KEY (`originFk`) REFERENCES `parking` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `parkingUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `payDemDetail`
--
DROP TABLE IF EXISTS `payDemDetail`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payDemDetail` (
`id` tinyint(3) unsigned NOT NULL,
`detail` tinyint(3) unsigned NOT NULL,
PRIMARY KEY (`id`,`detail`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`name` varchar(20) NOT NULL,
`solution` varchar(1) DEFAULT NULL,
`outstandingDebt` tinyint(3) unsigned zerofill NOT NULL DEFAULT 000,
`graceDays` int(11) unsigned NOT NULL DEFAULT 0,
`isIbanRequiredForClients` tinyint(3) DEFAULT 0,
`isIbanRequiredForSuppliers` tinyint(3) DEFAULT 0,
`isNotified` tinyint(3) NOT NULL DEFAULT 1,
`hasVerified` tinyint(1) DEFAULT 0,
`graceMonthsDisableChecked` int(11) unsigned NOT NULL DEFAULT 0 COMMENT 'Deshabilita la comprobación de los datos bancarios de todos aquellos proveedores que no hayan recibido un pago en los meses especificados',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `payment`
--
DROP TABLE IF EXISTS `payment`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payment` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`received` date NOT NULL,
`supplierFk` int(10) unsigned NOT NULL,
`amount` decimal(10,2) NOT NULL DEFAULT 0.00,
`currencyFk` tinyint(3) unsigned NOT NULL DEFAULT 1,
`divisa` decimal(10,2) DEFAULT NULL,
`bankFk` int(11) NOT NULL DEFAULT 0,
`payMethodFk` tinyint(3) unsigned NOT NULL,
`bankingFees` double(6,2) unsigned NOT NULL DEFAULT 0.00,
`concept` varchar(30) DEFAULT NULL,
`companyFk` int(10) unsigned NOT NULL DEFAULT 442,
`created` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`isConciliated` tinyint(1) unsigned zerofill NOT NULL DEFAULT 0,
`dueDated` date DEFAULT NULL,
`workerFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `empresa_id` (`companyFk`),
KEY `id_banco` (`bankFk`),
KEY `id_moneda` (`currencyFk`),
KEY `pay_met` (`payMethodFk`),
KEY `pagoDueDatedIdx` (`dueDated`),
KEY `payment_FK` (`workerFk`),
KEY `payment_supplierFk` (`supplierFk`),
CONSTRAINT `pago_moneda_1` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON UPDATE CASCADE,
CONSTRAINT `pago_pay_met` FOREIGN KEY (`payMethodFk`) REFERENCES `payMethod` (`id`) ON UPDATE CASCADE,
CONSTRAINT `paymentCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `payment_FK` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`),
CONSTRAINT `payment_ibfk_2` FOREIGN KEY (`bankFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE,
CONSTRAINT `payment_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `paymentExchangeInsurance`
--
DROP TABLE IF EXISTS `paymentExchangeInsurance`;
/*!50001 DROP VIEW IF EXISTS `paymentExchangeInsurance`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `paymentExchangeInsurance` AS SELECT
1 AS `pago_sdc_id`,
1 AS `importe`,
1 AS `fecha`,
1 AS `vencimiento`,
1 AS `entity_id`,
1 AS `ref`,
1 AS `rate`,
1 AS `empresa_id`,
1 AS `financialProductTypefk`,
1 AS `upperBarrier`,
1 AS `lowerBarrier`,
1 AS `strike` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `payrollCategories`
--
DROP TABLE IF EXISTS `payrollCategories`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payrollCategories` (
`id` int(11) NOT NULL,
`description` varchar(255) NOT NULL,
`rate` tinyint(4) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `payrollCenter`
--
DROP TABLE IF EXISTS `payrollCenter`;
/*!50001 DROP VIEW IF EXISTS `payrollCenter`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `payrollCenter` AS SELECT
1 AS `codCenter`,
1 AS `companyCode` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `payrollComponent`
--
DROP TABLE IF EXISTS `payrollComponent`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payrollComponent` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`isSalaryAgreed` tinyint(1) NOT NULL DEFAULT 0,
`isVariable` tinyint(1) NOT NULL,
`isException` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Excepciones a tener en cuenta al importar conceptos en el proceso de importación de ficheros A3.',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `payrollWorkCenter`
--
DROP TABLE IF EXISTS `payrollWorkCenter`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payrollWorkCenter` (
`workCenterFkA3` int(11) NOT NULL COMMENT 'Columna que hace referencia a A3.',
`Centro__` varchar(255) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
`nss_cotizacion__` varchar(15) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
`domicilio__` varchar(255) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
`poblacion__` varchar(45) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
`cp__` varchar(5) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
`empresa_id__` int(10) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
`companyFkA3` int(11) DEFAULT NULL COMMENT 'Columna que hace referencia a A3.',
PRIMARY KEY (`workCenterFkA3`,`empresa_id__`),
KEY `payroll_centros_ix1` (`empresa_id__`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `payrollWorker`
--
DROP TABLE IF EXISTS `payrollWorker`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payrollWorker` (
`workerFkA3` int(11) NOT NULL COMMENT 'Columna que hace referencia a A3.',
`nss__` varchar(23) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
`codpuesto__` int(10) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
`companyFkA3` int(10) NOT NULL COMMENT 'Columna que hace referencia a A3.',
`codcontrato__` int(10) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
`FAntiguedad__` date NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
`grupotarifa__` int(10) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
`codcategoria__` int(10) NOT NULL COMMENT '@Deprecated refs #6738 15/03/2024',
`ContratoTemporal__` tinyint(1) NOT NULL DEFAULT 0 COMMENT '@Deprecated refs #6738 15/03/2024',
`workerFk` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`workerFkA3`,`companyFkA3`),
KEY `sajvgfh_idx` (`codpuesto__`),
KEY `payroll_employee_workerFk_idx` (`workerFk`),
CONSTRAINT `payroll_employee_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `pcs`
--
DROP TABLE IF EXISTS `pcs`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `pcs` (
`created` timestamp NULL DEFAULT current_timestamp(),
`routeFk` int(10) unsigned DEFAULT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`pallet` int(11) DEFAULT NULL,
`box` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `pcs_graf`
--
DROP TABLE IF EXISTS `pcs_graf`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `pcs_graf` (
`id` int(11) NOT NULL DEFAULT 0,
`dia` date DEFAULT NULL,
`created` datetime DEFAULT NULL,
`box` decimal(4,0) DEFAULT NULL,
`pallet` decimal(2,0) DEFAULT NULL,
`routeFk` int(10) unsigned DEFAULT NULL,
`hh` int(11) DEFAULT NULL,
`mm` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `pcs_graf_index1` (`hh`),
KEY `pcs_graf_index2` (`mm`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `periodicityType`
--
DROP TABLE IF EXISTS `periodicityType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `periodicityType` (
`code` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`description` varchar(45) DEFAULT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `personalProtectionEquipment`
--
DROP TABLE IF EXISTS `personalProtectionEquipment`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `personalProtectionEquipment` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `pgc`
--
DROP TABLE IF EXISTS `pgc`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `pgc` (
`code` varchar(10) NOT NULL,
`rate` decimal(10,2) NOT NULL,
`name` varchar(45) DEFAULT NULL,
`cplusTaxBreakFk` int(10) unsigned DEFAULT 1,
`mod340` tinyint(1) NOT NULL DEFAULT 0,
`mod347` tinyint(1) NOT NULL DEFAULT 0,
`siiTrascendencyInvoiceOutFk` int(10) unsigned DEFAULT 1,
`isEqualizated` tinyint(1) DEFAULT 0,
PRIMARY KEY (`code`),
KEY `pgc_fk1_idx` (`cplusTaxBreakFk`),
KEY `pgc_fk2_idx` (`siiTrascendencyInvoiceOutFk`),
CONSTRAINT `pgc_fk1` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `cplusTaxBreak` (`id`) ON UPDATE CASCADE,
CONSTRAINT `pgc_fk2` FOREIGN KEY (`siiTrascendencyInvoiceOutFk`) REFERENCES `siiTrascendencyInvoiceOut` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL COMMENT 'Cuenta de IVA',
`equFk` varchar(10) 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=utf8mb3 COLLATE=utf8mb3_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 `pgcMaster`
--
DROP TABLE IF EXISTS `pgcMaster`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `pgcMaster` (
`code` varchar(10) NOT NULL,
`description` varchar(100) DEFAULT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='tan solo tiene las cuentas de contaplus';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `phoneBook`
--
DROP TABLE IF EXISTS `phoneBook`;
/*!50001 DROP VIEW IF EXISTS `phoneBook`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `phoneBook` AS SELECT
1 AS `Tipo`,
1 AS `Id`,
1 AS `Cliente`,
1 AS `Telefono` */;
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 utf8mb3 COLLATE utf8mb3_general_ci 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=utf8mb3 COLLATE=utf8mb3_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) 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=utf8mb3 COLLATE=utf8mb3_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) 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=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ppe`
--
DROP TABLE IF EXISTS `ppe`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ppe` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`amortization` decimal(10,2) NOT NULL DEFAULT 0.00,
`firstAmortizated` date DEFAULT NULL,
`lastAmortizated` date DEFAULT NULL,
`finished` date DEFAULT NULL,
`value` decimal(10,2) NOT NULL DEFAULT 0.00,
`planFk` int(11) NOT NULL,
`groupFk` int(11) DEFAULT NULL,
`account` varchar(10) DEFAULT NULL,
`endowment` varchar(10) DEFAULT NULL,
`elementAccount` varchar(10) DEFAULT NULL,
`nature` varchar(30) DEFAULT NULL,
`location` varchar(10) DEFAULT NULL,
`discharged` date DEFAULT NULL,
`cause` varchar(45) DEFAULT NULL,
`photo` blob DEFAULT NULL,
`isInvestmentAsset` tinyint(4) NOT NULL DEFAULT 0,
`workerFk` int(10) unsigned DEFAULT NULL,
`companyFk` int(10) unsigned NOT NULL DEFAULT 442,
`description` varchar(45) DEFAULT NULL,
`isDone` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `ppe_fk1_idx` (`workerFk`),
KEY `ppe_fk2_idx` (`planFk`),
KEY `ppe_fk3_idx` (`groupFk`),
KEY `ppe_fk4_idx` (`companyFk`),
KEY `ppe_fk5_idx` (`account`),
KEY `ppe_fk6` (`endowment`),
KEY `ppe_fk7` (`elementAccount`),
KEY `ppe_FK` (`location`),
CONSTRAINT `ppeCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `ppe_FK` FOREIGN KEY (`location`) REFERENCES `ppeLocation` (`code`) ON UPDATE CASCADE,
CONSTRAINT `ppe_fk1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `ppe_fk2` FOREIGN KEY (`planFk`) REFERENCES `ppePlan` (`id`) ON UPDATE CASCADE,
CONSTRAINT `ppe_fk3` FOREIGN KEY (`groupFk`) REFERENCES `ppeGroup` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `ppe_fk5` FOREIGN KEY (`account`) REFERENCES `pgcMaster` (`code`) ON UPDATE CASCADE,
CONSTRAINT `ppe_fk6` FOREIGN KEY (`endowment`) REFERENCES `pgcMaster` (`code`) ON UPDATE CASCADE,
CONSTRAINT `ppe_fk7` FOREIGN KEY (`elementAccount`) REFERENCES `pgcMaster` (`code`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Property, plant & equipment\nInmvolizado, en español';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ppeComponent`
--
DROP TABLE IF EXISTS `ppeComponent`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ppeComponent` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ppeFk` int(11) NOT NULL,
`invoiceInFk` mediumint(8) unsigned NOT NULL,
`amount` decimal(10,2) NOT NULL DEFAULT 0.00,
PRIMARY KEY (`id`),
KEY `ppeComponent_fk1_idx` (`ppeFk`),
KEY `ppeComponent_fk2_idx` (`invoiceInFk`),
CONSTRAINT `ppeComponent_fk1` FOREIGN KEY (`ppeFk`) REFERENCES `ppe` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `ppeComponent_fk2` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ppeDMS`
--
DROP TABLE IF EXISTS `ppeDMS`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ppeDMS` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dmsFk` int(11) NOT NULL,
`ppeFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `ppeDMS_fk1_idx` (`dmsFk`),
KEY `ppeDMS_fk2_idx` (`ppeFk`),
CONSTRAINT `ppeDMS_fk1` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `ppeDMS_fk2` FOREIGN KEY (`ppeFk`) REFERENCES `ppe` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ppeGroup`
--
DROP TABLE IF EXISTS `ppeGroup`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ppeGroup` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tipo de inmovilizado';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ppeLocation`
--
DROP TABLE IF EXISTS `ppeLocation`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ppeLocation` (
`code` varchar(10) NOT NULL DEFAULT '',
`description` varchar(100) DEFAULT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ppePlan`
--
DROP TABLE IF EXISTS `ppePlan`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ppePlan` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`rate` decimal(3,2) NOT NULL DEFAULT 1.00,
`days` int(11) NOT NULL DEFAULT 365,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Plan de amortizacion para la tabla ppe';
/*!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,
CONSTRAINT `priceFixed_ibfk_2` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `printQueue`
--
DROP TABLE IF EXISTS `printQueue`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `printQueue` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`printerFk` int(10) unsigned DEFAULT NULL,
`priorityFk` tinyint(3) unsigned NOT NULL DEFAULT 3 COMMENT '1 - high, 2 - normal, 3 - low',
`reportFk` tinyint(3) unsigned DEFAULT NULL,
`statusCode` enum('queued','error','printing','printed') NOT NULL DEFAULT 'queued',
`started` datetime DEFAULT NULL,
`finished` datetime DEFAULT NULL,
`workerFk` int(11) DEFAULT NULL,
`error` text DEFAULT NULL,
`errorNumber` int(11) DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`serverId` varchar(255) DEFAULT NULL COMMENT 'Indica el identificador de los servidores de impresión',
PRIMARY KEY (`id`),
KEY `statusCode` (`statusCode`),
KEY `printerFk` (`printerFk`),
KEY `priorityFk` (`priorityFk`),
KEY `workerFk` (`workerFk`),
KEY `printQueue_report` (`reportFk`),
CONSTRAINT `printQueue_FK` FOREIGN KEY (`printerFk`) REFERENCES `printer` (`id`) ON UPDATE CASCADE,
CONSTRAINT `printQueue_priorityFk` FOREIGN KEY (`priorityFk`) REFERENCES `queuePriority` (`id`) ON UPDATE CASCADE,
CONSTRAINT `printQueue_report` FOREIGN KEY (`reportFk`) REFERENCES `report` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `printQueueArgs`
--
DROP TABLE IF EXISTS `printQueueArgs`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `printQueueArgs` (
`printQueueFk` int(10) unsigned NOT NULL,
`name` varchar(255) NOT NULL,
`value` varchar(255) DEFAULT NULL,
PRIMARY KEY (`printQueueFk`,`name`),
KEY `printQueueArgs_printQueueFk_idx` (`printQueueFk`),
CONSTRAINT `printQueueArgs_printQueueFk` FOREIGN KEY (`printQueueFk`) REFERENCES `printQueue` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Argumentos que se pasarán al informe para generarlos';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `printQueueConfig`
--
DROP TABLE IF EXISTS `printQueueConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `printQueueConfig` (
`networkDrive` varchar(10) NOT NULL DEFAULT 'X:\\',
`dmsPath` varchar(45) NOT NULL DEFAULT ' \\\\server\\dms',
`printQueueLimit` int(11) NOT NULL DEFAULT 30 COMMENT 'Número máximo de filas de la cola de impresión a mostrar al enviar correo a través del evento vn.printQueue_check'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `printer`
--
DROP TABLE IF EXISTS `printer`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `printer` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`path` varchar(50) DEFAULT NULL,
`modelFk` varchar(50) DEFAULT NULL,
`macWifi` varchar(20) DEFAULT NULL,
`ipAddress` varchar(15) DEFAULT NULL,
`reference` varchar(50) DEFAULT NULL,
`isLabeler` tinyint(1) DEFAULT 0 COMMENT 'Indica si es impresora de etiquetas',
`sectorFk` int(11) DEFAULT NULL,
`paperSizeFk` varchar(100) DEFAULT NULL,
`isRfid` tinyint(4) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `printer_UN` (`reference`),
UNIQUE KEY `printer_UN1` (`macWifi`),
UNIQUE KEY `printer_UN2` (`name`),
KEY `printer_FK` (`modelFk`),
KEY `printer_sectorFk_idx` (`id`,`sectorFk`),
KEY `printer_sectorFk` (`sectorFk`),
KEY `printer_FK_1` (`paperSizeFk`),
CONSTRAINT `printer_FK` FOREIGN KEY (`modelFk`) REFERENCES `printerModel` (`code`) ON UPDATE CASCADE,
CONSTRAINT `printer_FK_1` FOREIGN KEY (`paperSizeFk`) REFERENCES `paperSize` (`code`),
CONSTRAINT `printer_sectorFk` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `printerModel`
--
DROP TABLE IF EXISTS `printerModel`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `printerModel` (
`code` varchar(50) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`isVisible` tinyint(1) NOT NULL DEFAULT 1,
`created` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `productionConfig`
--
DROP TABLE IF EXISTS `productionConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `productionConfig` (
`id` int(10) unsigned NOT NULL,
`isPreviousPreparationRequired` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Impide que los sacadores reciban tickets que tengan productos de prep previa',
`ticketPrintedMax` int(10) unsigned NOT NULL DEFAULT 8 COMMENT 'numero máxido de tickets por carro que se ponen en impreso al pedir colección',
`ticketTrolleyMax` int(10) unsigned NOT NULL DEFAULT 4 COMMENT 'numero máximo de tickets por carro para asignar baldas en una colección',
`rookieDays` int(11) NOT NULL DEFAULT 3 COMMENT 'dias en que se cuida con especial cuidado los pedidos de un cliente por ser nuevo o recuperado',
`notBuyingMonths` int(11) NOT NULL DEFAULT 3 COMMENT 'numero de meses que han de pasar desde su ultima compra para considerar nueva la siguiente compra',
`isZoneClosedByExpeditionActivated` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'activa el procedimiento vn.zone_getClosed',
`maxNotReadyCollections` int(11) NOT NULL DEFAULT 5,
`minTicketsToCloseZone` int(11) DEFAULT 15 COMMENT 'mínimo numero de tickets que deben de tener expediciones para cerrar una zona',
`movingTicketDelRoute` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'Si está activo, al cambiar la fecha de un ticket desde el F11, le quita la ruta',
`defaultZone` int(11) NOT NULL DEFAULT 697,
`defautlAgencyMode` int(11) NOT NULL DEFAULT 1328 COMMENT 'SENDING',
`hasUniqueCollectionTime` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Determina si los tickets de una colección deben de tener la misma hora y minuto',
`maxCollectionWithoutUser` int(11) NOT NULL DEFAULT 1 COMMENT 'Número máximo de colecciones que pueden estar sin usuario, haciendo de caché....',
`pendingCollectionsOrder` tinyint(3) unsigned DEFAULT 8,
`pendingCollectionsAge` tinyint(3) unsigned DEFAULT 6,
`maxNotAssignedCollectionLifeTime` time NOT NULL DEFAULT '00:10:00' COMMENT 'Tiempo de vida de las colecciones sin asignar. Cuando se supera son eliminadas',
`maxProductionScopeDays` int(11) NOT NULL DEFAULT 1 COMMENT 'maximo numero de dias en F11',
`orderMode` enum('Location','Age') NOT NULL DEFAULT 'Location',
`stockScopeDays` int(11) DEFAULT 1 COMMENT 'Días a futuro al revisar el stock',
`shortageAddressFk` int(11) DEFAULT NULL COMMENT 'Consignatario por defecto para añadir un item de alta',
`clientSelfConsumptionFk` int(11) DEFAULT NULL COMMENT 'Cliente para crear el ticket de autoconsumo',
`itemPreviousDefaultSize` int(11) DEFAULT NULL COMMENT 'Altura por defecto para los artículos de previa',
`addressSelfConsumptionFk` int(11) DEFAULT 2613 COMMENT 'Consignatario para crear el ticket de autoconsumo',
`defaultFreightItemFk` int(10) unsigned NOT NULL DEFAULT 71 COMMENT 'Default value for expedition table',
`backupPrinterNotificationDelay` int(10) unsigned DEFAULT NULL COMMENT 'Minimum seconds Interval to Prevent Spam from Same-Type Notifications',
`collection_new_lockname` varchar(100) NOT NULL DEFAULT 'collection_new' COMMENT 'Lockname value for proc vn.collection_new',
`collection_assign_lockname` varchar(100) DEFAULT 'collection_assign' COMMENT 'Lockname value for proc vn.collection_new',
`defaultSectorFk` int(10) unsigned NOT NULL DEFAULT 37 COMMENT 'Default sector',
`scannableCodeType` enum('qr','barcode') NOT NULL DEFAULT 'barcode',
PRIMARY KEY (`id`),
KEY `productionConfig_FK` (`shortageAddressFk`),
KEY `productionConfig_FK_1` (`clientSelfConsumptionFk`),
KEY `productionConfig_FK_2` (`addressSelfConsumptionFk`),
CONSTRAINT `productionConfig_FK` FOREIGN KEY (`shortageAddressFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE,
CONSTRAINT `productionConfig_FK_1` FOREIGN KEY (`clientSelfConsumptionFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `productionConfig_FK_2` FOREIGN KEY (`addressSelfConsumptionFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE,
CONSTRAINT `productionConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Recoge los parámetros que condicionan la producción';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `productionError`
--
DROP TABLE IF EXISTS `productionError`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `productionError` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userFk` int(11) DEFAULT NULL,
`firstname` varchar(100) DEFAULT NULL,
`lastname` varchar(100) DEFAULT NULL,
`rol` varchar(100) DEFAULT NULL,
`ticketNumber` int(11) DEFAULT NULL,
`lineNumber` int(11) DEFAULT NULL,
`error` int(11) DEFAULT NULL,
`volume` double DEFAULT NULL,
`hourStart` varchar(100) DEFAULT NULL,
`hourEnd` varchar(100) DEFAULT NULL,
`hourWorked` varchar(100) DEFAULT NULL,
`dated` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `productionVolume`
--
DROP TABLE IF EXISTS `productionVolume`;
/*!50001 DROP VIEW IF EXISTS `productionVolume`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `productionVolume` AS SELECT
1 AS `hora`,
1 AS `minuto`,
1 AS `cm3`,
1 AS `warehouseFk`,
1 AS `created` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `productionVolume_LastHour`
--
DROP TABLE IF EXISTS `productionVolume_LastHour`;
/*!50001 DROP VIEW IF EXISTS `productionVolume_LastHour`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `productionVolume_LastHour` AS SELECT
1 AS `m3`,
1 AS `warehouseFk` */;
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 AUTO_INCREMENT,
`description` varchar(50) NOT NULL,
`code` varchar(25) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `prefessionalCategory_UN` (`description`),
UNIQUE KEY `code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `project`
--
DROP TABLE IF EXISTS `project`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `project` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`name` varchar(100) NOT NULL,
`photo` blob DEFAULT NULL,
`started` date DEFAULT NULL,
`finished` date DEFAULT NULL,
`userFk` int(11) unsigned NOT NULL,
`departmentFk` int(11) DEFAULT NULL,
`companyFk` int(10) unsigned NOT NULL DEFAULT 442,
`location` varchar(100) DEFAULT NULL,
`amount` decimal(15,2) DEFAULT NULL,
`stateFk` varchar(25) DEFAULT 'open',
PRIMARY KEY (`id`),
KEY `project_FK` (`userFk`),
KEY `project_FK_1` (`departmentFk`),
KEY `project_FK_3` (`stateFk`),
KEY `projectCompany_Fk` (`companyFk`),
CONSTRAINT `projectCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `project_FK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `project_FK_1` FOREIGN KEY (`departmentFk`) REFERENCES `department` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `project_FK_3` FOREIGN KEY (`stateFk`) REFERENCES `projectState` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla master de proyectos';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `projectNotes`
--
DROP TABLE IF EXISTS `projectNotes`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `projectNotes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`txt` varchar(255) NOT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`projectFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `projectNotes_FK` (`projectFk`),
KEY `projectNotes_FK_1` (`userFk`),
CONSTRAINT `projectNotes_FK` FOREIGN KEY (`projectFk`) REFERENCES `project` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `projectNotes_FK_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Historico de notas para project';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `projectState`
--
DROP TABLE IF EXISTS `projectState`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `projectState` (
`code` varchar(25) NOT NULL,
`description` varchar(100) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `promissoryNote`
--
DROP TABLE IF EXISTS `promissoryNote`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `promissoryNote` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`issued` timestamp NOT NULL DEFAULT current_timestamp(),
`Concept` varchar(50) DEFAULT NULL,
`paymentFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `pago_id` (`paymentFk`),
CONSTRAINT `promissoryNote_ibfk_2` FOREIGN KEY (`paymentFk`) REFERENCES `payment` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `property`
--
DROP TABLE IF EXISTS `property`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `property` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(250) NOT NULL,
`cadaster` varchar(200) DEFAULT NULL,
`smallholding` int(11) DEFAULT NULL,
`area` varchar(100) DEFAULT NULL,
`townFk` int(11) NOT NULL,
`registry` varchar(200) DEFAULT NULL,
`volume` int(11) DEFAULT NULL,
`book` int(11) DEFAULT NULL,
`page` int(11) DEFAULT NULL,
`farm` int(11) DEFAULT NULL,
`registration` int(11) DEFAULT NULL,
`value` int(11) DEFAULT NULL,
`propertyGroupFk` int(11) NOT NULL,
`companyFk` int(10) unsigned NOT NULL,
`photo` blob DEFAULT NULL,
`allocation` varchar(200) DEFAULT NULL,
`m2` decimal(10,2) DEFAULT NULL,
`tome` int(11) DEFAULT NULL,
`url` varchar(250) DEFAULT NULL,
`protocol` varchar(100) DEFAULT NULL COMMENT 'numero de protocolo notarial de la escritura de compra venta',
`purchased` date NOT NULL DEFAULT curdate() COMMENT 'date of purchase of the property',
`booked` date DEFAULT NULL COMMENT 'date of completion of property registration',
`supplierFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `property_FK` (`propertyGroupFk`),
KEY `property_FK_1` (`townFk`),
KEY `property_company` (`companyFk`),
KEY `propertySupplierFk` (`supplierFk`),
CONSTRAINT `propertyCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `propertySupplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE,
CONSTRAINT `property_FK` FOREIGN KEY (`propertyGroupFk`) REFERENCES `propertyGroup` (`id`) ON UPDATE CASCADE,
CONSTRAINT `property_FK_1` FOREIGN KEY (`townFk`) REFERENCES `town` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `propertyDms`
--
DROP TABLE IF EXISTS `propertyDms`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `propertyDms` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dmsFk` int(11) NOT NULL,
`propertyFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `propertyDms_FK` (`dmsFk`),
KEY `propertyDms_FK_1` (`propertyFk`),
CONSTRAINT `propertyDms_FK` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `propertyDms_FK_1` FOREIGN KEY (`propertyFk`) REFERENCES `property` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `propertyGroup`
--
DROP TABLE IF EXISTS `propertyGroup`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `propertyGroup` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `propertyNotes`
--
DROP TABLE IF EXISTS `propertyNotes`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `propertyNotes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`propertyFk` int(11) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`note` text NOT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `propertyNotes_FK_1` (`userFk`),
KEY `propertyNotes_FK` (`propertyFk`),
CONSTRAINT `propertyNotes_FK` FOREIGN KEY (`propertyFk`) REFERENCES `property` (`id`),
CONSTRAINT `propertyNotes_FK_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) 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,
`geoFk` int(11) DEFAULT NULL,
`autonomyFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `countryName_UN` (`countryFk`,`name`),
KEY `Paises_Id` (`countryFk`),
KEY `warehouse_Id` (`warehouseFk`),
KEY `provicne_zone_fk_idx` (`zoneFk`),
KEY `province_FK` (`autonomyFk`),
CONSTRAINT `province_FK` FOREIGN KEY (`autonomyFk`) REFERENCES `autonomy` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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 1,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`workerFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Table for storing punches that have cars with errors';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `quality`
--
DROP TABLE IF EXISTS `quality`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `quality` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`isVisible` tinyint(1) NOT NULL DEFAULT 1,
`created` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Valores usados en el tag calidad';
/*!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) DEFAULT NULL,
`code` varchar(6) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `rankBonus`
--
DROP TABLE IF EXISTS `rankBonus`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `rankBonus` (
`rank` int(11) DEFAULT NULL,
`bonus` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `rate`
--
DROP TABLE IF EXISTS `rate`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `rate` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dated` date NOT NULL,
`warehouseFk` smallint(6) unsigned NOT NULL,
`rate0` double NOT NULL,
`rate1` double NOT NULL,
`rate2` double NOT NULL,
`rate3` double NOT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `tarifa_warehouse` (`warehouseFk`),
KEY `rate_fk_editor` (`editorFk`),
CONSTRAINT `rate_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `tarifa_warehouse` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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(10) unsigned 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`),
CONSTRAINT `rateConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `rateLog`
--
DROP TABLE IF EXISTS `rateLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `rateLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`originFk` int(11) DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete','select') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` enum('Rate') NOT NULL DEFAULT 'Rate',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `logRateuserFk` (`userFk`),
KEY `rateLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `rateLog_originFk` (`originFk`,`creationDate`),
CONSTRAINT `rateUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL COMMENT 'nombre incorrecto, renombrar a description',
`amountPaid` decimal(10,2) NOT NULL DEFAULT 0.00,
`payed` datetime DEFAULT NULL,
`workerFk` int(10) unsigned DEFAULT NULL,
`bankFk` int(11) DEFAULT 0,
`clientFk` int(11) DEFAULT 0,
`created` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`companyFk` int(10) 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`),
KEY `payed` (`payed`),
CONSTRAINT `receiptCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `receiptWorkerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `receipt_ibfk_2` FOREIGN KEY (`bankFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE,
CONSTRAINT `recibo_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `recipe`
--
DROP TABLE IF EXISTS `recipe`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `recipe` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`itemFk` int(11) NOT NULL COMMENT 'bouquet al que hace referencia la receta',
`name` varchar(50) DEFAULT NULL,
`size` int(10) unsigned DEFAULT NULL,
`originFk` tinyint(2) unsigned DEFAULT NULL,
`typeFk` smallint(5) unsigned DEFAULT NULL,
`longName` varchar(50) DEFAULT NULL,
`quantity` int(11) NOT NULL DEFAULT 1,
`element` varchar(45) DEFAULT NULL,
`inkFk` varchar(3) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `recipe_ix_1` (`element`),
KEY `recipe_ix_2` (`itemFk`),
KEY `recipe_FK` (`inkFk`),
CONSTRAINT `recipe_FK` FOREIGN KEY (`inkFk`) REFERENCES `ink` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `recipe_log`
--
DROP TABLE IF EXISTS `recipe_log`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `recipe_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`recipe_ItemFk` int(11) NOT NULL,
`element` varchar(45) NOT NULL,
`selected_ItemFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `recipe_log_ix1` (`recipe_ItemFk`),
KEY `recipe_log_ix2` (`element`),
KEY `recipe_log_ix3` (`selected_ItemFk`),
CONSTRAINT `recipe_log_FK` FOREIGN KEY (`recipe_ItemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE,
CONSTRAINT `recipe_log_FK_1` FOREIGN KEY (`selected_ItemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacena las decisiones tomadas al generar recetas';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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',
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `cliente_idx` (`clientFk`),
KEY `recovery_fk_editor` (`editorFk`),
CONSTRAINT `cliente333` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE,
CONSTRAINT `cliente_cliente` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE,
CONSTRAINT `recovery_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 DEFAULT current_timestamp(),
`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=utf8mb3 COLLATE=utf8mb3_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` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`currencyFk` tinyint(3) unsigned NOT NULL,
`dated` date NOT NULL,
`value` float unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `referenceRate_currencyFk_IDX` (`currencyFk`,`dated`) USING BTREE,
KEY `date` (`dated`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `remittance`
--
DROP TABLE IF EXISTS `remittance`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `remittance` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dated` datetime DEFAULT NULL,
`accountingFk` int(11) DEFAULT 0,
`companyFk` int(10) unsigned NOT NULL DEFAULT 442,
PRIMARY KEY (`id`),
KEY `Id_Banco` (`accountingFk`),
KEY `empresa_id` (`companyFk`),
CONSTRAINT `RemesasCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `remittance_ibfk_2` FOREIGN KEY (`accountingFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `report`
--
DROP TABLE IF EXISTS `report`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `report` (
`id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`paperSizeFk` varchar(100) DEFAULT NULL,
`method` varchar(255) DEFAULT NULL COMMENT 'Salix method',
PRIMARY KEY (`id`),
KEY `report_FK` (`paperSizeFk`),
CONSTRAINT `report_FK` FOREIGN KEY (`paperSizeFk`) REFERENCES `paperSize` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `returnBuckets`
--
DROP TABLE IF EXISTS `returnBuckets`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `returnBuckets` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`freightContainerType` varchar(15) NOT NULL,
`freightPackagingEmpty` double NOT NULL DEFAULT 0,
`freightPackagingFull` double NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `roadmap`
--
DROP TABLE IF EXISTS `roadmap`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `roadmap` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`tractorPlate` varchar(10) DEFAULT NULL,
`trailerPlate` varchar(12) DEFAULT NULL,
`phone` varchar(15) DEFAULT NULL,
`supplierFk` int(10) unsigned DEFAULT NULL,
`etd` datetime NOT NULL,
`observations` varchar(255) DEFAULT NULL,
`created` timestamp NULL DEFAULT current_timestamp(),
`userFk` int(10) unsigned DEFAULT NULL,
`price` decimal(10,2) DEFAULT NULL,
`driverName` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `userFk` (`userFk`),
KEY `roadmap_supplierFk` (`supplierFk`),
CONSTRAINT `roadmap_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE,
CONSTRAINT `roadmap_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Troncales diarios que se contratan';
/*!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 `roleCreditLimit`
--
DROP TABLE IF EXISTS `roleCreditLimit`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `roleCreditLimit` (
`id` int(11) NOT NULL,
`maxAmount` int(10) unsigned NOT NULL,
`roleFk` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `clientCreditLimit_FK_idx` (`roleFk`),
CONSTRAINT `roleCreditLimit_FK` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `route`
--
DROP TABLE IF EXISTS `route`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `route` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`workerFk` int(10) unsigned DEFAULT NULL,
`firstEditorFk` int(10) unsigned NOT NULL COMMENT 'Usuario creador de la ruta',
`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) DEFAULT NULL,
`kmEnd` mediumint(9) DEFAULT 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 DEFAULT NULL,
`zoneFk` int(11) DEFAULT NULL,
`priority` int(11) NOT NULL DEFAULT 0,
`invoiceInFk` mediumint(8) unsigned DEFAULT NULL,
`beachFk` int(11) DEFAULT NULL,
`commissionWorkCenterFk` int(11) DEFAULT NULL COMMENT 'WorkerCenter que gestiona la ruta',
`editorFk` int(10) unsigned 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`),
KEY `asdfasdf_idx` (`invoiceInFk`),
KEY `route_idxIsOk` (`isOk`),
KEY `route_WorkCenterFk_idx` (`commissionWorkCenterFk`),
KEY `route_fk_editor` (`editorFk`),
CONSTRAINT `fk_route_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `route_WorkCenterFk` FOREIGN KEY (`commissionWorkCenterFk`) REFERENCES `workCenter` (`id`) ON UPDATE CASCADE,
CONSTRAINT `route_fk5` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `route_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
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,
CONSTRAINT `route_invoiceInFk` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `routeAction`
--
DROP TABLE IF EXISTS `routeAction`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `routeAction` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`price` decimal(10,2) DEFAULT NULL,
`isMainlineDelivered` tinyint(4) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `routeCommission`
--
DROP TABLE IF EXISTS `routeCommission`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `routeCommission` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`routeFk` int(10) unsigned NOT NULL,
`workCenterFk` int(11) DEFAULT NULL,
`firstEditorFk` int(10) unsigned NOT NULL COMMENT 'Usuario creador de la ruta',
`km` decimal(5,2) DEFAULT NULL,
`m3` decimal(5,2) DEFAULT NULL,
`yearlyKm` decimal(5,2) DEFAULT NULL,
`yearlyM3` decimal(5,2) DEFAULT NULL,
`cat4m3` decimal(5,2) DEFAULT NULL,
`cat5m3` decimal(5,2) DEFAULT NULL,
`freelanceYearlyM3` decimal(5,2) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `routeCommission_routeFk_idx` (`routeFk`),
KEY `routeCommission_workCenterFk_idx` (`workCenterFk`),
KEY `routeCommission_firstEditorFk` (`firstEditorFk`),
CONSTRAINT `routeCommission_routeFk` FOREIGN KEY (`routeFk`) REFERENCES `route` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `routeCommission_workCenterFk` FOREIGN KEY (`workCenterFk`) REFERENCES `workCenter` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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(10) unsigned 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `routeConfig`
--
DROP TABLE IF EXISTS `routeConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `routeConfig` (
`id` int(10) unsigned NOT NULL,
`m3Distribution` decimal(10,4) DEFAULT NULL,
`m3Management` decimal(10,2) DEFAULT NULL,
`m3Palletization` 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,
`rateHoliday` decimal(5,2) DEFAULT NULL,
`plusCategory1` decimal(5,2) DEFAULT NULL,
`plusCategory2` decimal(5,2) DEFAULT NULL,
`maxSalaryCategory1` decimal(6,2) DEFAULT NULL,
`maxSalaryCategory2` decimal(6,2) DEFAULT NULL,
`distributionM3Category1` decimal(5,2) DEFAULT NULL,
`distributionM3Category2` decimal(5,2) DEFAULT NULL,
`plusCategory1Concept` varchar(45) DEFAULT NULL,
`plusCategory2Concept` varchar(45) DEFAULT NULL,
`defaultCompanyFk` int(10) unsigned DEFAULT 442,
`kmHeavy` decimal(5,2) DEFAULT NULL COMMENT 'Comisión por kilometro vehículo pesado',
`kmLight` decimal(5,2) DEFAULT NULL COMMENT 'Comisión por kilometro vehículo ligero',
`kmYearly` decimal(5,2) DEFAULT NULL COMMENT 'Comisión por kilometro objetivo anual',
`m3Yearly` decimal(5,2) DEFAULT NULL COMMENT 'Comisión por m3 objetivo anual',
`deliveryM3Cat4` decimal(5,2) DEFAULT NULL COMMENT 'Comisión por m3 repartido Cat.IV',
`deliveryM3Cat5` decimal(5,2) DEFAULT NULL COMMENT 'Comisión por m3 repartido Cat. V',
`plusCat2Fixed` decimal(5,2) DEFAULT NULL COMMENT 'Plus fijo Cat.II vehículo ligero',
`plusCat2Variable` decimal(5,2) DEFAULT NULL COMMENT 'Plus variable Cat.II vehículo ligero',
`plusCat3Fixed` decimal(5,2) DEFAULT NULL COMMENT 'Plus fijo Cat.III vehículo pesado',
`plusCat3Variable` decimal(5,2) DEFAULT NULL COMMENT 'Plus variable Cat.III vehículo pesado',
`distributionCat4M3` decimal(5,2) DEFAULT NULL COMMENT 'Comisión por gestión de la distribución Cat IV',
`distributionCat5M3` decimal(5,2) DEFAULT NULL COMMENT 'Comisión por gestión de la distribución Cat V',
`rateCat4` decimal(5,2) DEFAULT NULL COMMENT 'Ratio aplicado a la media de venta de los repartidores para el cálculo de las comisiones de enrutadores Cat IV',
`rateCat5` decimal(5,2) DEFAULT NULL COMMENT 'Ratio aplicado a la media de venta de los repartidores para el cálculo de las comisiones de enrutadores Cat V',
`freelanceM3` decimal(5,2) DEFAULT NULL COMMENT 'Comisión para enrutadores sobre rutas de autónomos',
`freelanceMinM3` decimal(5,2) DEFAULT NULL COMMENT 'Metros mínimos para considerar las rutas de autónomos',
`mainlineDelivered` decimal(5,2) DEFAULT NULL COMMENT 'Comisión para entregas troncales',
`cutoffDated` date DEFAULT NULL COMMENT 'Fecha a partir de la cual se autoriza calcular la comisión',
`defaultWorkCenterFk` int(11) DEFAULT 9 COMMENT 'Para el cálculo de las comisiones, en caso de el creador de la ruta no tenga workCenter',
`kmMax` int(11) DEFAULT 4000 COMMENT 'Máximo número de km validos para una ruta',
`truckerBusinessProfessionalCategoryFk` int(11) NOT NULL DEFAULT 42,
PRIMARY KEY (`id`),
KEY `routeConfigCompany_Fk` (`defaultCompanyFk`),
CONSTRAINT `routeConfigCompany_Fk` FOREIGN KEY (`defaultCompanyFk`) REFERENCES `company` (`id`),
CONSTRAINT `routeConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `routeDefaultAgencyMode`
--
DROP TABLE IF EXISTS `routeDefaultAgencyMode`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `routeDefaultAgencyMode` (
`id` int(11) NOT NULL DEFAULT 0,
`workcenterFk` int(11) DEFAULT NULL,
`agencyModeFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `workcenterFk` (`workcenterFk`),
KEY `routeDefaultAgencyMode_FK` (`agencyModeFk`),
CONSTRAINT `routeDefaultAgencyMode_FK` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`),
CONSTRAINT `routeDefaultAgencyMode_FK_1` FOREIGN KEY (`workcenterFk`) REFERENCES `workCenter` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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(10) unsigned NOT NULL,
PRIMARY KEY (`routeFk`,`workerFk`),
KEY `frmWorker_idx` (`workerFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Table deprecated on 26/04/23';
/*!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 DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` enum('Route','RoutesMonitor') NOT NULL DEFAULT 'Route',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `userFk` (`userFk`),
KEY `routeLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `routeLog_originFk` (`originFk`,`creationDate`),
CONSTRAINT `routeLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `routeMaster`
--
DROP TABLE IF EXISTS `routeMaster`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `routeMaster` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`warehouseFk` smallint(6) unsigned DEFAULT NULL,
`km` int(11) NOT NULL DEFAULT 0,
`packages` int(11) NOT NULL DEFAULT 0,
`vehicleCost` decimal(10,2) NOT NULL DEFAULT 0.00,
`staffCost` decimal(10,2) NOT NULL DEFAULT 0.00,
`vehicle` decimal(10,2) NOT NULL DEFAULT 0.00,
`staff` decimal(10,2) NOT NULL DEFAULT 0.00,
`fuel` int(11) NOT NULL DEFAULT 0,
`freelancers` decimal(10,2) NOT NULL DEFAULT 0.00,
`year` int(11) NOT NULL DEFAULT 0,
`month` int(11) NOT NULL DEFAULT 0,
`expense` decimal(10,2) NOT NULL DEFAULT 0.00,
`freelancersPackages` int(11) NOT NULL DEFAULT 0,
`kmCost` decimal(10,2) NOT NULL DEFAULT 0.00,
`packageCost` decimal(10,2) NOT NULL DEFAULT 0.00,
`freelancerPackageCost` decimal(10,2) NOT NULL DEFAULT 0.00,
`created` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `fk_rutas_warehouse_id_idx` (`warehouseFk`),
CONSTRAINT `routeMaster_FK` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `routeRecalc`
--
DROP TABLE IF EXISTS `routeRecalc`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `routeRecalc` (
`routeFk` int(11) NOT NULL,
PRIMARY KEY (`routeFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_bin COMMENT='Queue of changed volume to recalc route volumen';
/*!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(10) unsigned 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `routesControl`
--
DROP TABLE IF EXISTS `routesControl`;
/*!50001 DROP VIEW IF EXISTS `routesControl`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `routesControl` AS SELECT
1 AS `routeFk`,
1 AS `expeditions`,
1 AS `scanned`,
1 AS `pallets`,
1 AS `lastScanned`,
1 AS `description`,
1 AS `eta` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `routesMonitor`
--
DROP TABLE IF EXISTS `routesMonitor`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `routesMonitor` (
`routeFk` int(10) unsigned NOT NULL,
`name` varchar(45) DEFAULT NULL,
`beachFk` varchar(45) DEFAULT NULL,
`ticketPacked` int(11) DEFAULT NULL,
`ticketFree` int(11) DEFAULT NULL,
`ticketProduction` int(11) DEFAULT NULL,
`packages` int(11) DEFAULT NULL,
`note` varchar(255) DEFAULT NULL,
`dated` date DEFAULT NULL,
`dockFk` varchar(10) DEFAULT NULL,
`m3` decimal(10,1) DEFAULT NULL,
`priority` int(11) NOT NULL DEFAULT 0,
`etd` time DEFAULT NULL,
`expeditionTruckFk` int(11) DEFAULT NULL,
`m3boxes` decimal(10,1) DEFAULT NULL,
`bufferFk` int(11) DEFAULT NULL COMMENT 'Buffer del sorter por el que se quiere sacar esa ruta',
`isPickingAllowed` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Los tickets de esta ruta se pueden preparar',
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`routeFk`),
KEY `routesMonitor_FK` (`bufferFk`),
KEY `routesMonitor_FK_2` (`beachFk`),
KEY `routesMonitor_FK_1` (`dockFk`),
KEY `routesMonitor_FK_3` (`expeditionTruckFk`),
KEY `routesMonitor_fk_editor` (`editorFk`),
CONSTRAINT `routesMonitor_FK` FOREIGN KEY (`bufferFk`) REFERENCES `srt`.`buffer` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `routesMonitor_FK_1` FOREIGN KEY (`dockFk`) REFERENCES `dock` (`code`) ON UPDATE CASCADE,
CONSTRAINT `routesMonitor_FK_2` FOREIGN KEY (`beachFk`) REFERENCES `beach` (`code`) ON UPDATE CASCADE,
CONSTRAINT `routesMonitor_FK_3` FOREIGN KEY (`expeditionTruckFk`) REFERENCES `expeditionTruck` (`id`) ON UPDATE CASCADE,
CONSTRAINT `routesMonitor_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`quantity` decimal(10,2) NOT NULL DEFAULT 0.00,
`originalQuantity` double(9,1) DEFAULT NULL COMMENT 'Se utiliza para notificar a través de rocket los cambios de quantity',
`price` decimal(10,2) NOT NULL 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(),
`isAdded` tinyint(1) NOT NULL DEFAULT 0,
`total` decimal(10,2) GENERATED ALWAYS AS (`price` * `quantity` * (100 - `discount`) / 100) VIRTUAL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `Id_Ticket` (`ticketFk`),
KEY `itemFk_ticketFk` (`itemFk`,`ticketFk`),
KEY `sale_fk_editor` (`editorFk`),
KEY `sale_created_IDX` (`created`) USING BTREE,
CONSTRAINT `movement_ticket_id` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sale_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `sale_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `saleBuy`
--
DROP TABLE IF EXISTS `saleBuy`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `saleBuy` (
`saleFk` int(11) NOT NULL,
`buyFk` int(11) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`workerFk` int(11) DEFAULT NULL,
PRIMARY KEY (`saleFk`),
KEY `saleBuy_FK` (`buyFk`),
CONSTRAINT `saleBuy_FK` FOREIGN KEY (`buyFk`) REFERENCES `buy` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `saleBuy_FK_1` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `saleCloned`
--
DROP TABLE IF EXISTS `saleCloned`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `saleCloned` (
`saleClonedFk` int(11) NOT NULL,
`saleOriginalFk` int(11) NOT NULL,
PRIMARY KEY (`saleClonedFk`),
KEY `saleOriginalFk_idx` (`saleOriginalFk`),
CONSTRAINT `saleClonedFk_fk2` FOREIGN KEY (`saleClonedFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `saleOriginalFk_fk1` FOREIGN KEY (`saleOriginalFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 COMMENT 'Indica si ya se ha tenido en cuenta para calcular el greuge',
`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 `component` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `saleCost`
--
DROP TABLE IF EXISTS `saleCost`;
/*!50001 DROP VIEW IF EXISTS `saleCost`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `saleCost` AS SELECT
1 AS `itemFk`,
1 AS `ticketFk`,
1 AS `concept`,
1 AS `quantity`,
1 AS `discount`,
1 AS `price`,
1 AS `component`,
1 AS `coste` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `saleGoal`
--
DROP TABLE IF EXISTS `saleGoal`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `saleGoal` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`month` int(11) DEFAULT NULL,
`year` int(11) DEFAULT NULL,
`rank` smallint(6) NOT NULL,
`walletWeightFrom` int(11) NOT NULL,
`walletWeightTo` int(11) DEFAULT NULL,
`goal` decimal(10,2) DEFAULT NULL,
`goalType` smallint(6) DEFAULT NULL COMMENT 'grado',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `saleGroup`
--
DROP TABLE IF EXISTS `saleGroup`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `saleGroup` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`userFk` int(10) unsigned DEFAULT NULL,
`parkingFk` int(11) DEFAULT NULL,
`sectorFk` int(11) DEFAULT NULL,
`ticketFk` int(11) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `saleGroup_FK` (`ticketFk`),
KEY `saleGroup_userFK` (`userFk`),
KEY `saleGroup_parkingFK` (`parkingFk`),
KEY `saleGroup_sectorFK` (`sectorFk`),
CONSTRAINT `saleGroup_FK` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `saleGroup_parkingFK` FOREIGN KEY (`parkingFk`) REFERENCES `parking` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `saleGroup_sectorFK` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `saleGroup_userFK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='agrupa lineas de venta';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `saleGroupDetail`
--
DROP TABLE IF EXISTS `saleGroupDetail`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `saleGroupDetail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`saleFk` int(11) NOT NULL,
`saleGroupFk` int(11) NOT NULL,
`editorFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `saleGroupDetail_UN` (`saleFk`),
KEY `saleGroupDetail_FK_1` (`saleGroupFk`),
CONSTRAINT `saleGroupDetail_ibfk_1` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='relaciona sale y saleGroup';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `saleLabel`
--
DROP TABLE IF EXISTS `saleLabel`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `saleLabel` (
`saleFk` int(11) NOT NULL,
`label` mediumint(8) unsigned NOT NULL,
`stem` mediumint(8) unsigned NOT NULL,
`created` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`saleFk`),
CONSTRAINT `saleLabel_sale_FK` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `saleMistake`
--
DROP TABLE IF EXISTS `saleMistake`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `saleMistake` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`saleFk` int(11) NOT NULL,
`userFk` int(10) unsigned NOT NULL COMMENT 'Controlador',
`typeFk` int(11) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `saleMistake_fk1_idx` (`saleFk`),
KEY `saleMistake_fk2_idx` (`userFk`),
KEY `saleMistake_fk3_idx` (`typeFk`),
CONSTRAINT `saleMistake_fk1` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `saleMistake_fk2` FOREIGN KEY (`userFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `saleMistake_fk3` FOREIGN KEY (`typeFk`) REFERENCES `mistakeType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `saleMistakeList`
--
DROP TABLE IF EXISTS `saleMistakeList`;
/*!50001 DROP VIEW IF EXISTS `saleMistakeList`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `saleMistakeList` AS SELECT
1 AS `saleFk`,
1 AS `workerFk`,
1 AS `sacador`,
1 AS `created`,
1 AS `revisador`,
1 AS `description`,
1 AS `controlled` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `saleMistake_list__2`
--
DROP TABLE IF EXISTS `saleMistake_list__2`;
/*!50001 DROP VIEW IF EXISTS `saleMistake_list__2`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `saleMistake_list__2` AS SELECT
1 AS `saleFk`,
1 AS `workerFk`,
1 AS `sacador`,
1 AS `created`,
1 AS `revisador`,
1 AS `description`,
1 AS `controlled` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `saleSaleTracking`
--
DROP TABLE IF EXISTS `saleSaleTracking`;
/*!50001 DROP VIEW IF EXISTS `saleSaleTracking`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `saleSaleTracking` AS SELECT
1 AS `saleFk` */;
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=utf8mb3 COLLATE=utf8mb3_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(10) unsigned NOT NULL,
`actionFk__` int(11) DEFAULT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`stateFk` tinyint(3) unsigned NOT NULL,
`isScanned` tinyint(1) DEFAULT NULL COMMENT 'TRUE: se ha escaneado. FALSE: escrito a mano. NULL:demás casos',
PRIMARY KEY (`id`),
UNIQUE KEY `saleTracking_UN` (`saleFk`,`workerFk`,`stateFk`),
KEY `Id_Movimiento` (`saleFk`),
KEY `fgnStateFk_idx` (`stateFk`),
KEY `saleTracking_idx5` (`created`),
KEY `saleTracking_fk2_idx` (`actionFk__`),
KEY `saleTracking_FK_2` (`workerFk`),
CONSTRAINT `fgnStateFk` FOREIGN KEY (`stateFk`) REFERENCES `state` (`id`) ON UPDATE CASCADE,
CONSTRAINT `saleTracking_FK` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `saleTracking_FK_1` FOREIGN KEY (`actionFk__`) REFERENCES `ticketTrackingState__` (`id`) ON UPDATE CASCADE,
CONSTRAINT `saleTracking_FK_2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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 `typeFk`,
1 AS `buyer`,
1 AS `itemTypeFk`,
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 `landed`,
1 AS `volume`,
1 AS `physicalWeight`,
1 AS `weight`,
1 AS `physicalVolume`,
1 AS `freight`,
1 AS `zoneFk`,
1 AS `clientFk`,
1 AS `isPicked`,
1 AS `eurosValue`,
1 AS `itemPackingTypeFk` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `saleVolume_Today_VNH`
--
DROP TABLE IF EXISTS `saleVolume_Today_VNH`;
/*!50001 DROP VIEW IF EXISTS `saleVolume_Today_VNH`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `saleVolume_Today_VNH` AS SELECT
1 AS `Cliente`,
1 AS `Provincia`,
1 AS `Pais`,
1 AS `volume` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `sale_freightComponent`
--
DROP TABLE IF EXISTS `sale_freightComponent`;
/*!50001 DROP VIEW IF EXISTS `sale_freightComponent`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `sale_freightComponent` AS SELECT
1 AS `ticketFk`,
1 AS `amount`,
1 AS `shipped` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `salesPersonGoal`
--
DROP TABLE IF EXISTS `salesPersonGoal`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `salesPersonGoal` (
`salesPersonName` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '',
`month` int(11) DEFAULT NULL,
`year` int(11) DEFAULT NULL,
`goal` int(11) DEFAULT NULL,
PRIMARY KEY (`salesPersonName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `salesPersonProtected`
--
DROP TABLE IF EXISTS `salesPersonProtected`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `salesPersonProtected` (
`salesPersonFk` int(10) unsigned NOT NULL,
PRIMARY KEY (`salesPersonFk`),
CONSTRAINT `salesPersonProtected_FK` FOREIGN KEY (`salesPersonFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lista de comerciales que no se desasignarán automáticamente los clientes';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `salesPersonSince`
--
DROP TABLE IF EXISTS `salesPersonSince`;
/*!50001 DROP VIEW IF EXISTS `salesPersonSince`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `salesPersonSince` AS SELECT
1 AS `workerFk`,
1 AS `started` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `salesPreparedLastHour`
--
DROP TABLE IF EXISTS `salesPreparedLastHour`;
/*!50001 DROP VIEW IF EXISTS `salesPreparedLastHour`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `salesPreparedLastHour` AS SELECT
1 AS `warehouseFk`,
1 AS `saleFk`,
1 AS `isChecked`,
1 AS `originalQuantity`,
1 AS `created`,
1 AS `code`,
1 AS `firstname`,
1 AS `lastName`,
1 AS `workerCode`,
1 AS `litros`,
1 AS `concept`,
1 AS `departmentName` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `salesPreviousPreparated`
--
DROP TABLE IF EXISTS `salesPreviousPreparated`;
/*!50001 DROP VIEW IF EXISTS `salesPreviousPreparated`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `salesPreviousPreparated` AS SELECT
1 AS `saleFk` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `salespersonConfig`
--
DROP TABLE IF EXISTS `salespersonConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `salespersonConfig` (
`id` int(10) unsigned NOT NULL,
`manaMaxRate` decimal(3,2) DEFAULT 0.05 COMMENT 'Valor máximo a recficar en una línea por el maná de un comercial',
`manaMinRate` decimal(3,2) DEFAULT -0.05 COMMENT 'Valor mínimo a recficar en una línea por el maná de un comercial',
`manaDateFrom` date NOT NULL DEFAULT '2023-01-01' COMMENT 'first date to count mana',
`manaFromDays` int(11) NOT NULL DEFAULT 90 COMMENT 'Range of days from mana calculation',
`manaToDays` int(11) NOT NULL DEFAULT 30 COMMENT 'Range of days to mana calculation',
PRIMARY KEY (`id`),
CONSTRAINT `salespersonConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 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(25) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`description` varchar(105) NOT NULL,
`isVisible` tinyint(1) unsigned NOT NULL DEFAULT 1,
`hasCompany` tinyint(1) unsigned NOT NULL DEFAULT 0,
`hasPreview` tinyint(1) unsigned NOT NULL DEFAULT 1,
`datepickerEnabled` tinyint(1) NOT NULL DEFAULT 0,
`model` varchar(25) DEFAULT NULL COMMENT 'Model name in plural',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `scanner`
--
DROP TABLE IF EXISTS `scanner`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `scanner` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`modelFk` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
KEY `scanner_FK` (`modelFk`),
CONSTRAINT `scanner_FK` FOREIGN KEY (`modelFk`) REFERENCES `scannerModel` (`code`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `scannerModel`
--
DROP TABLE IF EXISTS `scannerModel`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `scannerModel` (
`code` varchar(50) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `screen`
--
DROP TABLE IF EXISTS `screen`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `screen` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`modelFk` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
KEY `screen_FK` (`modelFk`),
CONSTRAINT `screen_FK` FOREIGN KEY (`modelFk`) REFERENCES `screenModel` (`code`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `screenModel`
--
DROP TABLE IF EXISTS `screenModel`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `screenModel` (
`code` varchar(50) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`warehouseFk` smallint(6) unsigned NOT NULL DEFAULT 1,
`code` varchar(15) DEFAULT NULL,
`isPackagingArea` tinyint(1) NOT NULL DEFAULT 0,
`reportFk` tinyint(3) unsigned DEFAULT NULL,
`sonFk` int(11) DEFAULT NULL,
`isMain` tinyint(1) NOT NULL DEFAULT 0,
`itemPackingTypeFk` varchar(1) DEFAULT NULL,
`workerFk` int(11) DEFAULT NULL,
`isHideForPickers` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'sector a ocultar a los sacadores',
`isReserve` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Sectores de reserva, como Albenfruit o Fuentes',
`backupPrinterFk` int(10) unsigned DEFAULT NULL,
`typeFk` int(10) unsigned NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`),
KEY `sector_fk1_idx` (`warehouseFk`),
KEY `sector_report` (`reportFk`),
KEY `sector_FK` (`sonFk`,`warehouseFk`),
KEY `sector_FK_1` (`backupPrinterFk`),
KEY `sectorType_FK` (`typeFk`),
CONSTRAINT `sectorType_FK` FOREIGN KEY (`typeFk`) REFERENCES `sectorType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `sector_fk1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sector_report` FOREIGN KEY (`reportFk`) REFERENCES `report` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `sectorCollection`
--
DROP TABLE IF EXISTS `sectorCollection`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sectorCollection` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`userFk` int(10) unsigned NOT NULL,
`sectorFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `sectorCollection_FK` (`userFk`),
KEY `sectorCollection_FK_2` (`sectorFk`),
CONSTRAINT `sectorCollection_FK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sectorCollection_FK_1` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Las lineas de preparacion de pedidos por sectores se agrupan bajo el identificador de esta tabla';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `sectorCollectionSaleGroup`
--
DROP TABLE IF EXISTS `sectorCollectionSaleGroup`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sectorCollectionSaleGroup` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`sectorCollectionFk` int(11) NOT NULL,
`saleGroupFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `saleGroupFk` (`saleGroupFk`),
KEY `sectorCollectionFk` (`sectorCollectionFk`),
CONSTRAINT `sectorCollectionSaleGroup_ibfk_1` FOREIGN KEY (`sectorCollectionFk`) REFERENCES `sectorCollection` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sectorCollectionSaleGroup_ibfk_2` FOREIGN KEY (`saleGroupFk`) REFERENCES `saleGroup` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sectorCollectionSaleGroup_ibfk_3` FOREIGN KEY (`saleGroupFk`) REFERENCES `saleGroup` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Relaciona las lineas de venta con la coleccion del sector';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `sectorProductivity`
--
DROP TABLE IF EXISTS `sectorProductivity`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sectorProductivity` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`workerFk` int(11) DEFAULT NULL,
`firstName` varchar(50) DEFAULT NULL,
`lastName` varchar(50) DEFAULT NULL,
`sector` varchar(50) DEFAULT NULL,
`ticketCount` int(11) DEFAULT NULL,
`saleCount` int(11) DEFAULT NULL,
`error` int(11) DEFAULT NULL,
`volume` decimal(10,6) DEFAULT NULL,
`hourWorked` decimal(10,2) DEFAULT NULL,
`dated` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `sectorType`
--
DROP TABLE IF EXISTS `sectorType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sectorType` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`code` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `sendingConfig`
--
DROP TABLE IF EXISTS `sendingConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sendingConfig` (
`id` int(10) unsigned NOT NULL,
`defaultWeight` int(11) NOT NULL DEFAULT 13,
`defaultPackages` int(11) NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
CONSTRAINT `sendingConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `sendingService`
--
DROP TABLE IF EXISTS `sendingService`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sendingService` (
`agencyModeCodeFk` varchar(45) NOT NULL,
`serviceType` varchar(45) NOT NULL DEFAULT '01',
`accountNumber` varchar(100) NOT NULL,
PRIMARY KEY (`agencyModeCodeFk`),
CONSTRAINT `sendingService_agencyModeCodeFk` FOREIGN KEY (`agencyModeCodeFk`) REFERENCES `agencyMode` (`code`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Configuración de los servicios de Sending';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `sendingServiceWeekday`
--
DROP TABLE IF EXISTS `sendingServiceWeekday`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sendingServiceWeekday` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`weekdays` set('mon','tue','wed','thu','fri','sat','sun') NOT NULL,
`params` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Configuración de parámetros por dia de SENDING';
/*!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(10) unsigned NOT NULL,
`started` date NOT NULL,
`ended` date NOT NULL,
`workerSubstitute` int(10) unsigned NOT NULL,
`created` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`id`),
UNIQUE KEY `workerFk_UNIQUE` (`workerFk`,`started`,`ended`,`workerSubstitute`),
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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(10) unsigned NOT NULL,
`substituteFk` int(10) unsigned 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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(10) unsigned 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `shelving`
--
DROP TABLE IF EXISTS `shelving`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shelving` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`parkingFk` int(11) DEFAULT NULL,
`isPrinted` tinyint(4) NOT NULL DEFAULT 0,
`priority` int(11) NOT NULL DEFAULT 0,
`parked` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`userFk` int(10) unsigned DEFAULT NULL,
`isSpam` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'señala las matrículas con producto que se puede llevar a la reserva',
`isRecyclable` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'las matrículas marcadas como reciclables se liberan cada noche desde vn.shelving_clean para poder volver a utilizarlas',
`editorFk` int(10) unsigned DEFAULT NULL,
`isMoving` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `shelving_UN` (`code`),
KEY `shelving_fk1_idx` (`parkingFk`),
KEY `shelving_fk2_idx` (`userFk`),
KEY `shelving_fk_editor` (`editorFk`),
CONSTRAINT `shelving_fk1` FOREIGN KEY (`parkingFk`) REFERENCES `parking` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `shelving_fk2` FOREIGN KEY (`userFk`) REFERENCES `worker` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `shelving_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `chkShelvingCodeFormat` CHECK (char_length(`code`) <= 4 and `code` not like '%-%')
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla usada para localizar el carro en el parking del altillo';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `shelvingLog`
--
DROP TABLE IF EXISTS `shelvingLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shelvingLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`originFk` int(11) DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete','select') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` enum('Shelving') NOT NULL DEFAULT 'Shelving',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `userFk` (`userFk`),
KEY `shelvingLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `shelvingLog_originFk` (`originFk`,`creationDate`),
CONSTRAINT `shelvingLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `siiTrascendencyInvoiceIn`
--
DROP TABLE IF EXISTS `siiTrascendencyInvoiceIn`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `siiTrascendencyInvoiceIn` (
`id` int(10) unsigned NOT NULL,
`description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Clave de régimen especial o trascendencia en facturas recibidas en el suministro de inmediato';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `siiTrascendencyInvoiceOut`
--
DROP TABLE IF EXISTS `siiTrascendencyInvoiceOut`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `siiTrascendencyInvoiceOut` (
`id` int(10) unsigned NOT NULL,
`description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Clave de régimen especial o trascendencia en facturas expedidas del suministro de inmediato';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `siiTypeInvoiceIn`
--
DROP TABLE IF EXISTS `siiTypeInvoiceIn`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `siiTypeInvoiceIn` (
`id` int(10) unsigned NOT NULL,
`code` varchar(2) NOT NULL,
`description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tipo de Factura Recibidas en el suministro de inmediato';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `siiTypeInvoiceOut`
--
DROP TABLE IF EXISTS `siiTypeInvoiceOut`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `siiTypeInvoiceOut` (
`id` int(10) unsigned NOT NULL,
`code` varchar(2) NOT NULL,
`description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tipo de Factura Emitidas en el suministro de inmediato';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `silexACL`
--
DROP TABLE IF EXISTS `silexACL`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `silexACL` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`module` varchar(50) NOT NULL,
`method` varchar(50) NOT NULL,
`role` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `module_UNIQUE` (`module`,`method`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `sinister`
--
DROP TABLE IF EXISTS `sinister`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sinister` (
`id` int(11) NOT NULL,
`supplierFk` int(10) unsigned NOT NULL,
`clientFk` int(11) NOT NULL,
`amount` decimal(10,2) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`insureRate` decimal(3,2) NOT NULL DEFAULT 0.75,
`isBooked` tinyint(4) NOT NULL DEFAULT 0,
`workerFk` int(10) unsigned NOT NULL,
`companyFk` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `sinister_fk1_idx` (`supplierFk`),
KEY `sinister_fk2_idx` (`clientFk`),
KEY `sinister_fk3_idx` (`workerFk`),
KEY `sinister_fk4_idx` (`companyFk`),
CONSTRAINT `sinisterCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sinister_fk2` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sinister_fk3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `sinister_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Impago de cliente asegurado';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `sinisterDetail`
--
DROP TABLE IF EXISTS `sinisterDetail`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sinisterDetail` (
`id` int(11) NOT NULL,
`sinisterFk` int(11) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`amountIn` decimal(10,2) DEFAULT NULL,
`amountOut` decimal(10,2) DEFAULT NULL,
`isConciliated` tinyint(1) NOT NULL DEFAULT 0,
`workerFk` int(10) unsigned NOT NULL,
`bankFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `sinisterDetail_fk1_idx` (`sinisterFk`),
KEY `sinisterDetail_fk2_idx` (`workerFk`),
KEY `sinisterDetail_fk3_idx` (`bankFk`),
CONSTRAINT `sinisterDetail_fk1` FOREIGN KEY (`sinisterFk`) REFERENCES `sinister` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sinisterDetail_fk2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `sinisterDetail_fk3` FOREIGN KEY (`bankFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `smartTag`
--
DROP TABLE IF EXISTS `smartTag`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `smartTag` (
`code` varchar(12) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`shelvingFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`level` int(11) DEFAULT NULL,
PRIMARY KEY (`code`),
KEY `smartTag_shelving_fk` (`shelvingFk`),
CONSTRAINT `smartTag_FK` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`code`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `sms`
--
DROP TABLE IF EXISTS `sms`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sms` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`senderFk` int(10) unsigned NOT NULL,
`sender` varchar(15) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '693474205',
`destination` varchar(15) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`message` varchar(160) NOT NULL,
`statusCode` smallint(9) DEFAULT 0,
`status` varchar(255) DEFAULT 'OK',
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `sms_FK` (`senderFk`),
CONSTRAINT `sms_FK` FOREIGN KEY (`senderFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`uri` varchar(255) NOT NULL,
`title` varchar(50) NOT NULL,
`apiKey` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `smsConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `sorter`
--
DROP TABLE IF EXISTS `sorter`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sorter` (
`id` int(11) NOT NULL DEFAULT 0,
`created` datetime NOT NULL,
`routeFk` int(10) unsigned NOT NULL,
`ticketFk` int(10) NOT NULL,
`isBox` int(11) DEFAULT 1,
`itemFk` int(11) DEFAULT NULL,
`width` decimal(10,2) DEFAULT 0.00,
`depth` decimal(10,2) DEFAULT 0.00,
`height` decimal(10,2) DEFAULT 0.00,
`warehouseFk` smallint(6) unsigned NOT NULL DEFAULT 1,
`weight` decimal(5,2) NOT NULL DEFAULT 0.00,
`buildingOrder` int(5) NOT NULL DEFAULT 0,
`ETD` time NOT NULL DEFAULT '23:59:00',
`palletOrder` int(5) DEFAULT NULL,
`lungGrow` int(11) DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `specialLabels`
--
DROP TABLE IF EXISTS `specialLabels`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `specialLabels` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(100) NOT NULL,
`reportName` varchar(100) NOT NULL,
`isVisible` tinyint(1) NOT NULL DEFAULT 0,
`image` blob DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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) DEFAULT NULL,
`itemFk` int(11) NOT NULL,
`value` decimal(10,2) NOT NULL,
`started` date NOT NULL DEFAULT '2024-01-01',
`ended` date DEFAULT NULL,
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 `check_date_range` CHECK (`ended` is null or `ended` >= `started`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `specie`
--
DROP TABLE IF EXISTS `specie`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `specie` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `specie_UN` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `specieGeoInvasive`
--
DROP TABLE IF EXISTS `specieGeoInvasive`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `specieGeoInvasive` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`genusFk` int(11) NOT NULL,
`specieFk` int(11) NOT NULL,
`zoneGeofk` int(11) NOT NULL,
`isForbidden` tinyint(1) NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
KEY `specieGeoInvasive_FK` (`genusFk`),
KEY `specieGeoInvasive_FK_1` (`specieFk`),
KEY `specieGeoInvasive_FK_2` (`zoneGeofk`),
CONSTRAINT `specieGeoInvasive_FK` FOREIGN KEY (`genusFk`) REFERENCES `genus` (`id`) ON UPDATE CASCADE,
CONSTRAINT `specieGeoInvasive_FK_1` FOREIGN KEY (`specieFk`) REFERENCES `specie` (`id`) ON UPDATE CASCADE,
CONSTRAINT `specieGeoInvasive_FK_2` FOREIGN KEY (`zoneGeofk`) REFERENCES `zoneGeo` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Esta tabla recoge las prohibiciones de comerciar con especies invasoras de acuerdo con el Catálogo de Especies Exóticas Invasoras publicado por el Estado Español';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `split`
--
DROP TABLE IF EXISTS `split`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `split` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ticketFk` int(11) DEFAULT NULL,
`entryFk` int(11) DEFAULT NULL,
`dated` datetime DEFAULT NULL,
`note` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `Id_Entrada` (`entryFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `splitFilter`
--
DROP TABLE IF EXISTS `splitFilter`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `splitFilter` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`autonomyFk` int(11) DEFAULT NULL,
`clientFk` int(11) DEFAULT NULL,
`nickname` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `splitFilter_UN` (`autonomyFk`),
UNIQUE KEY `splitFilter_UN1` (`clientFk`),
KEY `splitFilter_FK` (`autonomyFk`),
KEY `splitFilter_FK_1` (`clientFk`),
CONSTRAINT `splitFilter_FK` FOREIGN KEY (`autonomyFk`) REFERENCES `autonomy` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `splitFilter_FK_1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='define los clientes que tienen split y el nombre a mostrar en la etiqueta';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `splitLine`
--
DROP TABLE IF EXISTS `splitLine`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `splitLine` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`splitFk` int(11) NOT NULL,
`itemFk` int(11) DEFAULT NULL,
`buyFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `Id_Split` (`splitFk`),
KEY `Id_Compra` (`buyFk`),
CONSTRAINT `Id_Compra` FOREIGN KEY (`buyFk`) REFERENCES `buy` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `splitLine_ibfk_1` FOREIGN KEY (`splitFk`) REFERENCES `split` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `starredModule`
--
DROP TABLE IF EXISTS `starredModule`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `starredModule` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`workerFk` int(10) unsigned NOT NULL,
`moduleFk` varchar(45) NOT NULL,
`position` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `starred_workerFk` (`workerFk`),
KEY `starred_moduleFk` (`moduleFk`),
CONSTRAINT `starred_moduleFk` FOREIGN KEY (`moduleFk`) REFERENCES `salix`.`module` (`code`) ON UPDATE CASCADE,
CONSTRAINT `starred_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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(20) NOT NULL,
`order` tinyint(3) unsigned DEFAULT NULL,
`alertLevel` int(11) NOT NULL DEFAULT 0,
`code` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`sectorProdPriority` tinyint(3) DEFAULT NULL,
`nextStateFk` tinyint(3) unsigned 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,
`isPrintable` tinyint(4) NOT NULL DEFAULT 0,
`isOK` tinyint(4) NOT NULL DEFAULT 0,
`graphCategory` int(11) NOT NULL DEFAULT 0,
`isNotValidated` tinyint(1) DEFAULT 0 COMMENT 'Los tienen que ser validados por un comercial para prepararse',
`classColor` varchar(12) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`),
KEY `state_id3` (`semaphore`),
KEY `alertLevel` (`alertLevel`),
KEY `state_FK` (`nextStateFk`),
CONSTRAINT `state_FK` FOREIGN KEY (`nextStateFk`) REFERENCES `state` (`id`) ON UPDATE CASCADE,
CONSTRAINT `state_ibfk_1` FOREIGN KEY (`alertLevel`) REFERENCES `alertLevel` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `stateI18n`
--
DROP TABLE IF EXISTS `stateI18n`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `stateI18n` (
`stateFk` tinyint(3) unsigned NOT NULL,
`lang` char(2) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`stateFk`,`lang`),
CONSTRAINT `stateI18n_state_id` FOREIGN KEY (`stateFk`) REFERENCES `state` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_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,
`userFk` int(10) unsigned DEFAULT NULL,
`buyed` decimal(10,2) DEFAULT NULL,
`dated` date DEFAULT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`reserved` decimal(10,2) DEFAULT NULL,
`requested` decimal(10,2) DEFAULT NULL,
`description` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `stockBuyed_user_idx` (`userFk`),
CONSTRAINT `stockBuyedUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`account` varchar(10) NOT NULL DEFAULT '4100000000' COMMENT 'Default accounting code for suppliers.',
`street` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`city` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`provinceFk` smallint(5) unsigned DEFAULT NULL,
`countryFk` mediumint(8) unsigned DEFAULT NULL,
`nif` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`isOfficial` tinyint(1) NOT NULL DEFAULT 1,
`isFarmer` tinyint(1) NOT NULL DEFAULT 0,
`retAccount` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`phone` varchar(16) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`commission` float NOT NULL DEFAULT 0,
`nickname` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`payMethodFk` tinyint(3) unsigned DEFAULT NULL,
`payDay` tinyint(4) unsigned DEFAULT NULL,
`payDemFk` tinyint(3) unsigned NOT NULL DEFAULT 7,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`isReal` tinyint(1) unsigned NOT NULL DEFAULT 0,
`note` text CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`postcodeFk` int(11) unsigned DEFAULT NULL,
`postCode` char(8) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`isActive` tinyint(4) NOT NULL DEFAULT 1,
`taxTypeSageFk` smallint(6) DEFAULT NULL COMMENT 'Tipo de IVA SAGE',
`withholdingSageFk` smallint(6) DEFAULT NULL COMMENT 'Tipos de retención SAGE',
`transactionTypeSageFk` tinyint(4) DEFAULT NULL COMMENT 'Ti po de transacción SAGE',
`isTrucker` tinyint(1) NOT NULL DEFAULT 0,
`workerFk` int(10) unsigned DEFAULT NULL COMMENT 'Responsible for approving invoices',
`supplierActivityFk` varchar(45) DEFAULT NULL,
`healthRegister` varchar(45) DEFAULT NULL,
`isPayMethodChecked` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'Se ha validado la forma de pago',
`isVies` tinyint(4) NOT NULL DEFAULT 0,
`stamp` longblob DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
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`),
KEY `supplier_taxTypeFk_idx` (`taxTypeSageFk`),
KEY `supplier_withholdingFk_idx` (`withholdingSageFk`),
KEY `supplier_transactionFk_idx` (`transactionTypeSageFk`),
KEY `suppplier_supplierActivityFk` (`supplierActivityFk`),
KEY `supplier_workerFk` (`workerFk`),
KEY `supplier_fk_editor` (`editorFk`),
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,
CONSTRAINT `supplier_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `supplier_taxTypeFk` FOREIGN KEY (`taxTypeSageFk`) REFERENCES `sage`.`TiposIva` (`CodigoIva`) ON UPDATE CASCADE,
CONSTRAINT `supplier_transactionFk` FOREIGN KEY (`transactionTypeSageFk`) REFERENCES `sage`.`TiposTransacciones` (`CodigoTransaccion`) ON UPDATE CASCADE,
CONSTRAINT `supplier_withholdingFk` FOREIGN KEY (`withholdingSageFk`) REFERENCES `sage`.`TiposRetencion` (`CodigoRetencion`) ON UPDATE CASCADE,
CONSTRAINT `supplier_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `suppplier_supplierActivityFk` FOREIGN KEY (`supplierActivityFk`) REFERENCES `supplierActivity` (`code`) ON UPDATE CASCADE,
CONSTRAINT `supplierAccountTooShort` CHECK (octet_length(`account`) = 10)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_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(10) unsigned DEFAULT NULL,
`iban` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`office` varchar(4) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`DC` varchar(2) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`number` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`description__` varchar(45) DEFAULT NULL COMMENT '@deprecated 2023-03-23',
`bankEntityFk` int(10) unsigned DEFAULT NULL,
`accountingFk` int(11) DEFAULT NULL,
`beneficiary` varchar(50) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
`countryFk` mediumint(8) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_supplier_country` (`supplierFk`,`countryFk`),
KEY `fk_proveedores_proveedores_account_idx` (`supplierFk`),
KEY `fk_Proveedores_account_entity1_idx` (`bankEntityFk`),
KEY `fk_banco_prov_account_idx` (`accountingFk`),
KEY `supplierAccount_fk_editor` (`editorFk`),
KEY `fk_supplierAccount_country` (`countryFk`),
CONSTRAINT `fk_supplierAccount_country` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE,
CONSTRAINT `supplierAccount_FK_1` FOREIGN KEY (`bankEntityFk`) REFERENCES `bankEntity` (`id`) ON UPDATE CASCADE,
CONSTRAINT `supplierAccount_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `supplierAccount_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `supplierActivity`
--
DROP TABLE IF EXISTS `supplierActivity`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `supplierActivity` (
`code` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `supplierAddress`
--
DROP TABLE IF EXISTS `supplierAddress`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `supplierAddress` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`supplierFk` int(10) unsigned DEFAULT NULL,
`nickname` varchar(40) DEFAULT NULL,
`street` varchar(255) DEFAULT NULL,
`provinceFk` smallint(6) unsigned DEFAULT NULL,
`postalCode` varchar(10) DEFAULT NULL,
`city` varchar(50) DEFAULT NULL,
`phone` varchar(15) DEFAULT NULL,
`mobile` varchar(15) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `supplierAddress_province_fk` (`provinceFk`),
KEY `supplierAddress_fk_editor` (`editorFk`),
KEY `supplierAddress_FK` (`supplierFk`),
CONSTRAINT `supplierAddress_FK` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `supplierAddress_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `supplierAddress_province_fk` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `supplierAgencyTerm`
--
DROP TABLE IF EXISTS `supplierAgencyTerm`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `supplierAgencyTerm` (
`agencyFk` smallint(5) unsigned NOT NULL,
`supplierFk` int(10) unsigned DEFAULT NULL,
`minimumPackages` int(11) NOT NULL DEFAULT 0 COMMENT 'numero minimo de bultos',
`kmPrice` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'precio extra por km',
`packagePrice` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'precio extra por bulto',
`routePrice` decimal(10,2) DEFAULT NULL COMMENT 'precio fijo por ruta',
`minimumKm` int(11) NOT NULL DEFAULT 0,
`minimumM3` decimal(10,2) NOT NULL DEFAULT 0.00,
`m3Price` decimal(10,2) NOT NULL DEFAULT 0.00,
PRIMARY KEY (`agencyFk`),
KEY `supplierAgencyTerm_supplierFk` (`supplierFk`),
CONSTRAINT `agencyTerm_FK` FOREIGN KEY (`agencyFk`) REFERENCES `agency` (`id`) ON UPDATE CASCADE,
CONSTRAINT `supplierAgencyTerm_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `supplierContact`
--
DROP TABLE IF EXISTS `supplierContact`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `supplierContact` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`supplierFk` int(10) unsigned DEFAULT NULL,
`phone` varchar(16) DEFAULT NULL,
`mobile` varchar(16) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`observation` text DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `supplierContact_fk_editor` (`editorFk`),
KEY `supplierContact_supplierFk` (`supplierFk`),
CONSTRAINT `supplierContact_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `supplierContact_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `supplierDebtConfig`
--
DROP TABLE IF EXISTS `supplierDebtConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `supplierDebtConfig` (
`dated` date NOT NULL DEFAULT '2014-12-31' COMMENT 'date from which we start counting',
`invalidBalances` double NOT NULL DEFAULT 0.5 COMMENT 'balances not to be paid'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `supplierDms`
--
DROP TABLE IF EXISTS `supplierDms`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `supplierDms` (
`supplierFk` int(10) unsigned NOT NULL,
`dmsFk` int(11) NOT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`supplierFk`,`dmsFk`),
KEY `user_Fk` (`editorFk`),
KEY `dms_Fk` (`dmsFk`),
CONSTRAINT `dms_Fk` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `supplier_Fk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE,
CONSTRAINT `user_Fk` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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(10) unsigned NOT NULL,
`currencyFk` tinyint(3) unsigned NOT NULL DEFAULT 2,
`amount` decimal(10,2) NOT NULL DEFAULT 0.00,
`description` varchar(50) DEFAULT NULL,
`companyFk` int(10) 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_moneda` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON UPDATE CASCADE,
CONSTRAINT `supplierExpenseCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `supplierExpense_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `supplierFreight`
--
DROP TABLE IF EXISTS `supplierFreight`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `supplierFreight` (
`supplierFk` int(10) unsigned NOT NULL,
PRIMARY KEY (`supplierFk`),
CONSTRAINT `Proveedores_cargueras_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla de espcializacion para señalar las compañias que prestan servicio de transitario';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `supplierLog`
--
DROP TABLE IF EXISTS `supplierLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `supplierLog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`originFk` int(10) unsigned DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` enum('Supplier','SupplierAddress','SupplierAccount','SupplierContact','SupplierDms') NOT NULL DEFAULT 'Supplier',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `supplierLog_ibfk_2` (`userFk`),
KEY `supplierLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `supplierLog_originFk` (`originFk`,`creationDate`),
CONSTRAINT `supplierLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!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 `warehouse`,
1 AS `buyingValue` */;
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) NOT NULL,
`name` varchar(45) DEFAULT NULL,
`place` varchar(45) DEFAULT NULL,
`macwifi` varchar(45) DEFAULT '0',
PRIMARY KEY (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) 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 CASCADE ON UPDATE CASCADE,
CONSTRAINT `tablet_uuid` FOREIGN KEY (`tabletFk`) REFERENCES `tablet` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`name` varchar(25) NOT NULL,
`isFree` tinyint(1) NOT NULL DEFAULT 1,
`isQuantitatif` tinyint(4) NOT NULL DEFAULT 0,
`sourceTable` varchar(255) DEFAULT NULL,
`unit` varchar(45) DEFAULT NULL,
`ediTypeFk` varchar(3) DEFAULT NULL,
`overwrite` varchar(45) DEFAULT NULL COMMENT 'nombre del campo de item a sobreescribir con el valor del tag, hay que añadir el código correspondiente en item_refreshTags',
PRIMARY KEY (`id`),
UNIQUE KEY `tagNameIdx` (`name`,`ediTypeFk`),
UNIQUE KEY `tagEdiTypeFkIdx` (`ediTypeFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`abbreviation` varchar(10) NOT NULL,
`tagFk` int(11) DEFAULT NULL,
PRIMARY KEY (`value`),
KEY `tagAbbreviation_FK` (`tagFk`),
CONSTRAINT `tagAbbreviation_FK` FOREIGN KEY (`tagFk`) REFERENCES `tag` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`tagFk`,`lang`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`ClaveOperacionFactura` varchar(1) DEFAULT NULL,
`CodigoTransaccion` int(2) DEFAULT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`code` varchar(1) NOT NULL DEFAULT 'R',
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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` int(10) 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=utf8mb3 COLLATE=utf8mb3_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` int(10) unsigned NOT NULL AUTO_INCREMENT,
`dated` date NOT NULL,
`code` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_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) NOT NULL COMMENT 'Solo rellenar si en el asiento ira en el DEBE',
`link` tinyint(4) unsigned 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) DEFAULT NULL COMMENT 'Código de Transacción de SAGE',
`operationCode` varchar(1) DEFAULT NULL COMMENT 'Código de operaciones de SAGE',
`taxCode` int(4) DEFAULT NULL COMMENT 'Código de IVA SAGE',
`isIntracommunity` tinyint(2) DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `taxCode_dated_IDX` (`dated`,`taxTypeFk`,`type`,`link`) USING BTREE,
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`isAccrued` tinyint(4) NOT NULL DEFAULT 0,
`serial` char(1) DEFAULT NULL,
`TIPOOPE` varchar(1) NOT NULL DEFAULT ' ' COMMENT 'respetar el nombre de la columna, se utiliza en contaplus',
`description` varchar(100) 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `temperature`
--
DROP TABLE IF EXISTS `temperature`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `temperature` (
`code` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`description` text DEFAULT NULL,
`name` varchar(10) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`model` enum('TL30','SENSITECH','TREKVIEW1','TREKVIEW2','DISPOSABLE','TEMPMATE') NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 DEFAULT NULL,
`shipped` datetime NOT NULL,
`nickname` varchar(50) DEFAULT NULL,
`refFk` varchar(20) DEFAULT NULL,
`addressFk` int(11) NOT NULL DEFAULT 0,
`workerFk` int(11) DEFAULT NULL,
`observations` varchar(255) 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) DEFAULT NULL,
`hour` int(11) DEFAULT 0,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`isBlocked` tinyint(1) NOT NULL DEFAULT 1,
`solution` varchar(5) DEFAULT NULL,
`routeFk` int(10) unsigned DEFAULT NULL,
`priority` tinyint(3) unsigned DEFAULT NULL,
`hasPriority` tinyint(1) unsigned NOT NULL DEFAULT 1,
`companyFk` int(10) 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,
`zonePrice` decimal(10,2) DEFAULT NULL,
`zoneBonus` decimal(10,2) DEFAULT NULL,
`totalWithVat` decimal(10,2) DEFAULT NULL COMMENT 'cache calculada del total con iva',
`totalWithoutVat` decimal(10,2) DEFAULT NULL COMMENT 'cache calculada del total sin iva',
`weight` decimal(10,2) DEFAULT NULL COMMENT 'En caso de informar, se utilizará su valor para calcular el peso de la factura',
`clonedFrom` int(11) DEFAULT NULL,
`cmrFk` int(11) DEFAULT NULL,
`editorFk` int(10) unsigned 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 `ticket_fk_editor` (`editorFk`),
KEY `ticket_cmrFk` (`cmrFk`),
CONSTRAINT `ticketCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `ticket_FK` FOREIGN KEY (`refFk`) REFERENCES `invoiceOut` (`ref`) ON UPDATE CASCADE,
CONSTRAINT `ticket_cmrFk` FOREIGN KEY (`cmrFk`) REFERENCES `cmr` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `ticket_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE,
CONSTRAINT `ticket_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `ticket_ibfk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`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 DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `tickets_zone_fk` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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,
`wagon` int(11) NOT NULL DEFAULT 0,
`smartTagFk` varchar(12) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`usedShelves` int(11) DEFAULT NULL COMMENT 'número de bandejas que ocupa un ticket en el carro',
`itemCount` int(11) DEFAULT NULL COMMENT 'número de productos distintos en el pedido',
`liters` int(11) DEFAULT NULL COMMENT 'volumen del pedido en litros',
PRIMARY KEY (`id`),
UNIQUE KEY `ticketCollection_UN` (`ticketFk`),
KEY `ticketCollection_fk1_idx` (`collectionFk`),
KEY `ticketCollection_fk2_idx` (`ticketFk`),
KEY `ticketCollection_smartTagFk_IDX` (`smartTagFk`) USING BTREE,
KEY `ticketCollection_created_IDX` (`created`) USING BTREE,
CONSTRAINT `ticketCollection_FK` FOREIGN KEY (`smartTagFk`) REFERENCES `smartTag` (`code`) ON UPDATE CASCADE,
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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(10) unsigned NOT NULL,
`scopeDays` tinyint(3) DEFAULT NULL,
`pickingDelay` int(11) NOT NULL DEFAULT 10 COMMENT 'minutos de cortesia desde que se crea un ticket hasta que se puede preparar',
`packagingInvoicingDated` date NOT NULL DEFAULT '2017-11-21' COMMENT 'Fecha desde la cual se gestiona el registro de embalajes de tickets (tabla vn.ticketPackaging)',
`packingDelay` int(11) DEFAULT 1 COMMENT 'Horas que marcará el retraso respecto hora de cierre web del ticket',
`daysForWarningClaim` int(11) NOT NULL DEFAULT 2 COMMENT 'dias restantes hasta que salte el aviso de reclamación fuera de plazo',
`defaultAttenderFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `ticketConfig_worker_FK` (`defaultAttenderFk`),
CONSTRAINT `ticketConfig_worker_FK` FOREIGN KEY (`defaultAttenderFk`) REFERENCES `worker` (`id`),
CONSTRAINT `ticketConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`ticketFk`,`dmsFk`),
KEY `gestdoc_id` (`dmsFk`),
KEY `ticketDms_fk_editor` (`editorFk`),
CONSTRAINT `ticketDms_dmsFk` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `ticketDms_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `ticketDms_ticketFk` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ticketDocumentation`
--
DROP TABLE IF EXISTS `ticketDocumentation`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketDocumentation` (
`ticketFk` int(11) NOT NULL,
PRIMARY KEY (`ticketFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Marca si se ha revisado el ticket para aportar la documentación CRM/DUA (relativa al trasporte internacional de mercancias)';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ticketDown`
--
DROP TABLE IF EXISTS `ticketDown`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketDown` (
`ticketFk` int(11) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`selected` int(11) NOT NULL DEFAULT 0,
`collectionFk` int(11) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
KEY `created_idx` (`created`),
KEY `selected_idx` (`selected`),
KEY `ticketDown_FK` (`collectionFk`),
CONSTRAINT `ticketDown_FK` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `ticketDown_fk1` FOREIGN KEY (`selected`) REFERENCES `ticketDown_SelectionType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Cola de impresion para los tickets que se van a solicitar al altillo';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `ticketDownBuffer`
--
DROP TABLE IF EXISTS `ticketDownBuffer`;
/*!50001 DROP VIEW IF EXISTS `ticketDownBuffer`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketDownBuffer` AS SELECT
1 AS `ticketFk`,
1 AS `created`,
1 AS `selected`,
1 AS `sacador`,
1 AS `parking` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `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) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `description_UNIQUE` (`description`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 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) 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 `ticketTracking` (`ticketFk`, `id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `ticketLastUpdated`
--
DROP TABLE IF EXISTS `ticketLastUpdated`;
/*!50001 DROP VIEW IF EXISTS `ticketLastUpdated`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketLastUpdated` AS SELECT
1 AS `ticketFk`,
1 AS `lastUpdated` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `ticketLastUpdatedList`
--
DROP TABLE IF EXISTS `ticketLastUpdatedList`;
/*!50001 DROP VIEW IF EXISTS `ticketLastUpdatedList`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketLastUpdatedList` AS SELECT
1 AS `ticketFk`,
1 AS `created` */;
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) DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete','select') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` enum('Ticket','Sale','TicketWeekly','TicketTracking','TicketService','TicketRequest','TicketRefund','TicketPackaging','TicketObservation','TicketDms','Expedition','Sms') NOT NULL DEFAULT 'Ticket',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `logTicketuserFk` (`userFk`),
KEY `ticketLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `ticketLog_originFk` (`originFk`,`creationDate`),
CONSTRAINT `ticketLog_user` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!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 NOT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `Id_Ticket` (`ticketFk`,`observationTypeFk`),
KEY `observation_type_id` (`observationTypeFk`),
KEY `ticketObservation_fk_editor` (`editorFk`),
CONSTRAINT `ticketObservation_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`quantity` int(10) DEFAULT 0,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`pvp` double DEFAULT NULL,
`workerFk` int(10) unsigned DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `ticketPackaging_fk1_idx` (`ticketFk`),
KEY `ticketPackaging_fk2_idx` (`packagingFk`),
KEY `ticketPackaging_fk3_idx` (`workerFk`),
KEY `ticketPackaging_fk_editor` (`editorFk`),
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,
CONSTRAINT `ticketPackaging_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ticketPackagingStartingStock`
--
DROP TABLE IF EXISTS `ticketPackagingStartingStock`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketPackagingStartingStock` (
`clientFk` int(11) NOT NULL,
`packagingFk` varchar(10) 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=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `ticketPackingList`
--
DROP TABLE IF EXISTS `ticketPackingList`;
/*!50001 DROP VIEW IF EXISTS `ticketPackingList`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticketPackingList` AS SELECT
1 AS `nickname`,
1 AS `ticketFk`,
1 AS `agencyMode`,
1 AS `flag`,
1 AS `province`,
1 AS `itemFk`,
1 AS `concept`,
1 AS `quantity`,
1 AS `litros`,
1 AS `observaciones` */;
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(),
`workerFk` int(11) DEFAULT NULL,
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `parking`,
1 AS `sectorFk`,
1 AS `alertCode` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `ticketRefund`
--
DROP TABLE IF EXISTS `ticketRefund`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketRefund` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`refundTicketFk` int(11) NOT NULL,
`originalTicketFk` int(11) NOT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ticketRefund_UN` (`refundTicketFk`),
KEY `ticketRefund_FK_1` (`originalTicketFk`),
KEY `ticketRefund_fk_editor` (`editorFk`),
CONSTRAINT `ticketRefund_FK` FOREIGN KEY (`refundTicketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `ticketRefund_FK_1` FOREIGN KEY (`originalTicketFk`) REFERENCES `ticket` (`id`) ON UPDATE CASCADE,
CONSTRAINT `ticketRefund_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 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) DEFAULT NULL,
`ordered` datetime DEFAULT NULL,
`shipped` datetime DEFAULT NULL,
`salesPersonCode` varchar(3) DEFAULT NULL,
`buyerCode__` varchar(3) NOT NULL COMMENT '@deprecated 2024-04-23 refs #6731 field not used',
`quantity` int(11) DEFAULT NULL,
`price` double DEFAULT NULL,
`itemFk` double DEFAULT NULL,
`clientFk` int(11) DEFAULT NULL,
`response` longtext DEFAULT NULL,
`total` int(11) DEFAULT NULL,
`buyed` datetime DEFAULT NULL,
`saleFk` int(11) DEFAULT NULL,
`created` timestamp NULL DEFAULT current_timestamp(),
`isOk` tinyint(1) DEFAULT NULL,
`requesterFk` int(10) unsigned DEFAULT NULL,
`attenderFk` int(10) unsigned DEFAULT NULL,
`ticketFk` int(11) DEFAULT NULL,
`editorFk` int(10) unsigned 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`),
KEY `ticketRequest_fk_editor` (`editorFk`),
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,
CONSTRAINT `ticketRequest_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ticketService`
--
DROP TABLE IF EXISTS `ticketService`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketService` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(45) DEFAULT NULL,
`quantity` int(11) NOT NULL DEFAULT 0,
`price` decimal(10,2) NOT NULL DEFAULT 0.00,
`taxClassFk` tinyint(3) unsigned NOT NULL DEFAULT 2,
`ticketFk` int(11) NOT NULL,
`ticketServiceTypeFk` int(11) NOT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `ticketServiceIvaGroup_idx` (`taxClassFk`),
KEY `fgn_ticketFk_idx` (`ticketFk`),
KEY `ticketService_ticketServiceType_idx` (`ticketServiceTypeFk`),
KEY `ticketService_fk_editor` (`editorFk`),
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_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `ticketService_ticketServiceType` FOREIGN KEY (`ticketServiceTypeFk`) REFERENCES `ticketServiceType` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL,
`expenseFk` varchar(10) NOT NULL DEFAULT '7050000000',
PRIMARY KEY (`id`),
KEY `ticketServiceType_expenceFk_idx` (`expenseFk`),
CONSTRAINT `ticketServiceType_expenceFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Lista de los posibles servicios a elegir';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ticketSms__`
--
DROP TABLE IF EXISTS `ticketSms__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketSms__` (
`smsFk` mediumint(8) unsigned NOT NULL,
`ticketFk` int(11) DEFAULT NULL,
PRIMARY KEY (`smsFk`),
KEY `ticketSms_FK_1` (`ticketFk`),
CONSTRAINT `ticketSms_FK` FOREIGN KEY (`smsFk`) REFERENCES `sms` (`id`) ON UPDATE CASCADE,
CONSTRAINT `ticketSms_FK_1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!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 `userFk`,
1 AS `ticketFk`,
1 AS `state`,
1 AS `productionOrder`,
1 AS `alertLevel`,
1 AS `code`,
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 `ticketFk`,
1 AS `state`,
1 AS `productionOrder`,
1 AS `alertLevel`,
1 AS `userFk`,
1 AS `code`,
1 AS `updated`,
1 AS `isPicked` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `ticketTracking`
--
DROP TABLE IF EXISTS `ticketTracking`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketTracking` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`stateFk` tinyint(3) unsigned NOT NULL,
`failFk` int(10) unsigned NOT NULL DEFAULT 21,
`notes` varchar(255) DEFAULT NULL,
`created` timestamp NULL DEFAULT current_timestamp(),
`ticketFk` int(11) DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`supervisorFk` int(10) unsigned DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `currante` (`userFk`),
KEY `responsable` (`supervisorFk`),
KEY `ticket` (`ticketFk`),
KEY `inter_state` (`stateFk`),
KEY `inter_id` (`ticketFk`,`id`) USING BTREE,
KEY `ticketTracking_fk_editor` (`editorFk`),
KEY `ticketTracking_created_IDX` (`created`) USING BTREE,
CONSTRAINT `inter_state` FOREIGN KEY (`stateFk`) REFERENCES `state` (`id`) ON UPDATE CASCADE,
CONSTRAINT `responsable` FOREIGN KEY (`supervisorFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `ticketTracking_FK3` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE,
CONSTRAINT `ticketTracking_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `ticketTracking_ibfk_1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ticketTrackingState__`
--
DROP TABLE IF EXISTS `ticketTrackingState__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketTrackingState__` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`action` varchar(15) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `ticketTrolley`
--
DROP TABLE IF EXISTS `ticketTrolley`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketTrolley` (
`ticket` int(11) NOT NULL,
`labelCount` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`ticket`),
CONSTRAINT `fk_ticketTrolley_vs_ticket` FOREIGN KEY (`ticket`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`code` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL COMMENT 'funcion de mysql Lunes = 0, Domingo = 6\nShipped, dia de preparacion del pedido',
`agencyModeFk` int(11) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`ticketFk`),
KEY `agencyModeFk_idx` (`agencyModeFk`),
KEY `ticketWeekly_fk_editor` (`editorFk`),
CONSTRAINT `Id_Ticket_fk` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `agencyModeFk` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `ticketWeekly_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`number` int(11) DEFAULT NULL,
`concept` varchar(50) DEFAULT NULL,
`in` decimal(10,2) DEFAULT NULL,
`out` decimal(10,2) DEFAULT NULL,
`bankFk` int(11) DEFAULT 1,
`workerFk` int(10) unsigned 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) 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 `accounting` (`id`) ON UPDATE CASCADE,
CONSTRAINT `till_ibfk_3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `tillConfig`
--
DROP TABLE IF EXISTS `tillConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tillConfig` (
`id` int(10) unsigned NOT NULL,
`openingBalance` decimal(10,2) NOT NULL,
`updated` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
CONSTRAINT `tillConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `time`
--
DROP TABLE IF EXISTS `time`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `time` (
`dated` date NOT NULL,
`period` int(6) NOT NULL,
`month` int(2) NOT NULL,
`year` int(4) NOT NULL,
`day` int(2) NOT NULL,
`week` int(2) NOT NULL,
`yearMonth` int(6) NOT NULL,
`salesYear` int(4) NOT NULL COMMENT 'año para los calculos de las comisiones ventas',
PRIMARY KEY (`dated`),
KEY `day_index` (`day`) USING HASH,
KEY `week_index` (`week`) USING HASH,
KEY `year_index` (`year`) USING HASH,
KEY `month_index` (`month`) USING HASH,
KEY `periodo` (`period`) USING HASH,
KEY `yearMonth` (`yearMonth`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla de referencia para las semanas, años y meses';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `timeSlots`
--
DROP TABLE IF EXISTS `timeSlots`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `timeSlots` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`section` time NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `Tramo` (`section`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `tr2`
--
DROP TABLE IF EXISTS `tr2`;
/*!50001 DROP VIEW IF EXISTS `tr2`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `tr2` AS SELECT
1 AS `id`,
1 AS `shipped`,
1 AS `shipmentHour`,
1 AS `landed`,
1 AS `landingHour`,
1 AS `warehouseInFk`,
1 AS `warehouseOutFk`,
1 AS `agencyFk`,
1 AS `ref`,
1 AS `isDelivered`,
1 AS `isReceived`,
1 AS `m3`,
1 AS `kg`,
1 AS `cargoSupplierFk`,
1 AS `totalEntries` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `traceabilityBuy`
--
DROP TABLE IF EXISTS `traceabilityBuy`;
/*!50001 DROP VIEW IF EXISTS `traceabilityBuy`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `traceabilityBuy` AS SELECT
1 AS `buyFk`,
1 AS `quantity`,
1 AS `landed`,
1 AS `warehouseName`,
1 AS `entryFk`,
1 AS `supplierName`,
1 AS `itemFk` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `traceabilitySale`
--
DROP TABLE IF EXISTS `traceabilitySale`;
/*!50001 DROP VIEW IF EXISTS `traceabilitySale`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `traceabilitySale` AS SELECT
1 AS `ticketFk`,
1 AS `buyFk`,
1 AS `shipped`,
1 AS `nickname`,
1 AS `quantity`,
1 AS `worker` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `train`
--
DROP TABLE IF EXISTS `train`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `train` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Define la configuración de los carros que se utilizan para sacar pedidos';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `trainingCenter`
--
DROP TABLE IF EXISTS `trainingCenter`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `trainingCenter` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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(10) unsigned NOT NULL,
`trainingCourseTypeFk` int(11) NOT NULL,
`centerFk` int(11) DEFAULT NULL,
`started` datetime NOT NULL,
`ended` datetime NOT NULL,
`invoice` varchar(50) DEFAULT NULL,
`amount` double DEFAULT NULL,
`remark` longtext DEFAULT NULL,
`hasDiscount` tinyint(1) NOT NULL DEFAULT 0,
`hasDiploma` 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lista de las formaciones';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `transitoryDuaUnified`
--
DROP TABLE IF EXISTS `transitoryDuaUnified`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `transitoryDuaUnified` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`supplierFk` int(10) unsigned DEFAULT NULL,
`countryCodeFk` varchar(2) NOT NULL DEFAULT 'EC',
PRIMARY KEY (`id`),
KEY `transitoryDuaUnified_FK` (`supplierFk`),
KEY `transitoryDuaUnified_country_FK` (`countryCodeFk`),
CONSTRAINT `transitoryDuaUnified_FK` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `transitoryDuaUnified_country_FK` FOREIGN KEY (`countryCodeFk`) REFERENCES `country` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Transitarios que al contabilizar sus entradas sólo generan un único DUA para todos los proveedores';
/*!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__` smallint(5) unsigned NOT NULL COMMENT '@deprecated 2024-10-01 refs #6604',
`ref` varchar(20) 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,
`appointment` datetime DEFAULT NULL,
`agencyModeFk` int(11) DEFAULT NULL,
`clonedFrom` int(11) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
`awbFk` smallint(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `shipment_1` (`shipped`,`landed`,`warehouseInFk`,`warehouseOutFk`,`agencyModeFk`,`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`),
KEY `travel_FK` (`agencyModeFk`),
KEY `travel_fk_editor` (`editorFk`),
KEY `travel_FK_1` (`awbFk`),
CONSTRAINT `travel_FK` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE,
CONSTRAINT `travel_FK_1` FOREIGN KEY (`awbFk`) REFERENCES `awb` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `travel_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
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
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci ROW_FORMAT=DYNAMIC;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `travelClonedWeekly`
--
DROP TABLE IF EXISTS `travelClonedWeekly`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `travelClonedWeekly` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`weekStart` tinyint(3) unsigned NOT NULL,
`weekEnd` tinyint(3) unsigned NOT NULL,
`warehouseOutFk` smallint(6) unsigned NOT NULL,
`warehouseInFk` smallint(6) unsigned NOT NULL,
`agencyModeFk` int(11) NOT NULL,
`weekDay` tinyint(3) unsigned NOT NULL,
`duration` tinyint(3) unsigned NOT NULL,
`ref` varchar(50) NOT NULL,
`supplierFk` int(10) unsigned DEFAULT NULL,
`kg` decimal(10,0) unsigned DEFAULT NULL,
`travelFk` int(11) unsigned DEFAULT NULL COMMENT 'Travel origen para clonar ademas sus entradas',
PRIMARY KEY (`id`),
KEY `travelClonedWeekly_FK` (`warehouseOutFk`),
KEY `travelClonedWeekly_FK_1` (`warehouseInFk`),
KEY `travelClonedWeekly_FK_2` (`agencyModeFk`),
KEY `travelClonedWeekly_FK_4` (`travelFk`),
KEY `travelClonedWeekly_supplierFk` (`supplierFk`),
CONSTRAINT `travelClonedWeekly_FK` FOREIGN KEY (`warehouseOutFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
CONSTRAINT `travelClonedWeekly_FK_1` FOREIGN KEY (`warehouseInFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
CONSTRAINT `travelClonedWeekly_FK_2` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE,
CONSTRAINT `travelClonedWeekly_FK_4` FOREIGN KEY (`travelFk`) REFERENCES `travel` (`id`) ON UPDATE CASCADE,
CONSTRAINT `travelClonedWeekly_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `travelConfig`
--
DROP TABLE IF EXISTS `travelConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `travelConfig` (
`id` int(10) unsigned NOT NULL,
`warehouseInFk` smallint(6) unsigned NOT NULL DEFAULT 8 COMMENT 'Warehouse de origen',
`warehouseOutFk` smallint(6) unsigned NOT NULL DEFAULT 60 COMMENT 'Warehouse destino',
`agencyFk` int(11) NOT NULL DEFAULT 1378 COMMENT 'Agencia por defecto',
`companyFk` int(10) unsigned NOT NULL DEFAULT 442 COMMENT 'Compañía por defecto',
PRIMARY KEY (`id`),
KEY `travelConfig_FK` (`warehouseInFk`),
KEY `travelConfig_FK_1` (`warehouseOutFk`),
KEY `travelConfig_FK_2` (`agencyFk`),
KEY `travelConfig_FK_3` (`companyFk`),
CONSTRAINT `travelConfig_FK` FOREIGN KEY (`warehouseInFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `travelConfig_FK_1` FOREIGN KEY (`warehouseOutFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `travelConfig_FK_2` FOREIGN KEY (`agencyFk`) REFERENCES `agencyMode` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `travelConfig_FK_3` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `travelConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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 DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` enum('Travel','TravelThermograph') NOT NULL DEFAULT 'Travel',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `userFk` (`userFk`),
KEY `travelLog_changedModel` (`changedModel`,`changedModelId`,`originFk`),
KEY `travelLog_originFk` (`originFk`,`creationDate`),
CONSTRAINT `travelLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!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 NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Observaciones de travel';
/*!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` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`thermographFk` varchar(45) NOT NULL,
`created` date NOT NULL,
`warehouseFk` smallint(6) unsigned NOT NULL,
`travelFk` int(10) unsigned DEFAULT NULL,
`result` varchar(45) DEFAULT NULL,
`dmsFk` int(11) DEFAULT NULL,
`temperatureFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT 'cool' COMMENT 'En la versión de Agosto de Salix se empezará a usar este campo y se actualizaran los anteriores mirando temperature.',
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `thermograph_fk_idx` (`thermographFk`),
KEY `gestdoc_fk_idx` (`dmsFk`),
KEY `travel_id` (`travelFk`),
KEY `warehouse_id` (`warehouseFk`),
KEY `travelThermographTemperatureFgn` (`temperatureFk`),
KEY `travelThermograph_fk_editor` (`editorFk`),
CONSTRAINT `travelThermographDmsFgn` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON UPDATE CASCADE,
CONSTRAINT `travelThermographTemperatureFgn` FOREIGN KEY (`temperatureFk`) REFERENCES `temperature` (`code`),
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,
CONSTRAINT `travelThermograph_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Registra cada termografo que se ha introducido en cada travel';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `trolley`
--
DROP TABLE IF EXISTS `trolley`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `trolley` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`workerFk` int(10) unsigned DEFAULT NULL,
`coupled` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `trolley_FK` (`workerFk`),
CONSTRAINT `trolley_FK` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 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(),
`darkMode` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'Salix interface dark mode',
`tabletFk` varchar(100) DEFAULT NULL,
PRIMARY KEY (`userFk`),
KEY `tabletFk` (`tabletFk`),
CONSTRAINT `userConfig_ibfk_1` FOREIGN KEY (`tabletFk`) REFERENCES `docuwareTablet` (`tablet`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` varchar(45) DEFAULT NULL,
`oldInstance` text DEFAULT NULL,
`newInstance` text DEFAULT NULL,
`changedModelId` int(11) DEFAULT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `originFk` (`originFk`),
KEY `userFk` (`userFk`),
CONSTRAINT `userLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!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) NOT NULL,
`phone` varchar(25) 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=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`model` varchar(20) NOT NULL,
`tradeMark` varchar(20) NOT NULL,
`companyFk` int(10) unsigned DEFAULT 442,
`m3` double DEFAULT NULL,
`isActive` tinyint(4) NOT NULL DEFAULT 1,
`warehouseFk` smallint(6) unsigned DEFAULT NULL,
`description` varchar(45) DEFAULT NULL,
`deliveryPointFk` int(11) DEFAULT 6 COMMENT 'Direccion para Buscaman',
`isKmTruckRate` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'Computar km como camión en el cálculo de salario de reparto',
`photo` blob DEFAULT NULL,
`chassis` varchar(100) DEFAULT NULL COMMENT 'numero de bastidor',
`fuelTypeFk` int(11) DEFAULT NULL,
`ppeFk` int(11) DEFAULT NULL,
`countryCodeFk` varchar(2) DEFAULT 'ES',
`leasing` varchar(50) DEFAULT NULL COMMENT 'Id de arrendamiento',
`supplierFk` int(10) unsigned DEFAULT NULL COMMENT 'supplier from whom the vehicle was purchased',
`import` decimal(10,2) DEFAULT NULL,
`supplierCoolerFk` int(10) unsigned DEFAULT NULL,
`vin` varchar(50) DEFAULT NULL,
`bankPolicyFk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `vehicle_UN` (`numberPlate`),
KEY `empresa_id` (`companyFk`),
KEY `provinceFk_idx` (`warehouseFk`),
KEY `vehicle_deliveryPointFk_idx` (`deliveryPointFk`),
KEY `vehicle_FK` (`fuelTypeFk`),
KEY `vehicle_FK_1` (`ppeFk`),
KEY `vehicle_supplierFk` (`supplierFk`),
KEY `vehicle_supplierCoolerFk` (`supplierCoolerFk`),
KEY `vehicle_bankPolicyFk` (`bankPolicyFk`),
CONSTRAINT `provinceFk` FOREIGN KEY (`warehouseFk`) REFERENCES `province` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `vehicleCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `vehicle_FK` FOREIGN KEY (`fuelTypeFk`) REFERENCES `fuelType` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `vehicle_FK_1` FOREIGN KEY (`ppeFk`) REFERENCES `ppe` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `vehicle_bankPolicyFk` FOREIGN KEY (`bankPolicyFk`) REFERENCES `bankPolicy` (`id`) ON UPDATE CASCADE,
CONSTRAINT `vehicle_deliveryPointFk` FOREIGN KEY (`deliveryPointFk`) REFERENCES `deliveryPoint` (`id`) ON UPDATE CASCADE,
CONSTRAINT `vehicle_supplierCoolerFk` FOREIGN KEY (`supplierCoolerFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE,
CONSTRAINT `vehicle_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `vehicleConfig`
--
DROP TABLE IF EXISTS `vehicleConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `vehicleConfig` (
`eventEarlyDays` int(11) DEFAULT 15 COMMENT 'Previous days on which the expiration of an event must be notified'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `vehicleConsumption`
--
DROP TABLE IF EXISTS `vehicleConsumption`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `vehicleConsumption` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`vehicleFk` int(10) unsigned NOT NULL,
`dated` date NOT NULL,
`km` int(20) unsigned NOT NULL,
`liters` double unsigned NOT NULL,
`price` double unsigned NOT NULL,
`adblue` decimal(10,2) NOT NULL DEFAULT 0.00,
`tolls` double DEFAULT NULL,
`discount` double DEFAULT NULL,
`silla` int(11) NOT NULL DEFAULT 0 COMMENT 'indica si han repostado en la gasolinera de la rotonda',
`created` timestamp NULL DEFAULT current_timestamp(),
`others` double DEFAULT NULL,
`fuelTypeFk` varchar(45) DEFAULT NULL,
`supplierFk` int(10) unsigned DEFAULT NULL,
`liters100km` decimal(10,2) DEFAULT NULL COMMENT 'se rellena en Vehiculos_consumo_beforeInsert y son los litros consumidos a los 100 kilometros',
`gasoline` decimal(10,2) NOT NULL DEFAULT 0.00,
PRIMARY KEY (`id`,`vehicleFk`),
KEY `fk_Vehiculos_consumo_Vehiculos_idx` (`vehicleFk`),
KEY `fuelTypeFk_idx` (`fuelTypeFk`),
KEY `proveedoresFk_idx` (`supplierFk`),
CONSTRAINT `Vehiculos_consumo_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_Vehiculos_consumo_Vehiculos` FOREIGN KEY (`vehicleFk`) REFERENCES `vehicle` (`id`) ON UPDATE CASCADE,
CONSTRAINT `fuelTypeFk` FOREIGN KEY (`fuelTypeFk`) REFERENCES `fuelType` (`code`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='En esta tabla apuntan el importe de los tickets de la gasolinera solred, con quien tenemos un contrato y nos facturan mensualmente';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `vehicleDms`
--
DROP TABLE IF EXISTS `vehicleDms`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `vehicleDms` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`vehicleFk` int(10) unsigned NOT NULL,
`dmsFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `vehicleDms_FK` (`vehicleFk`),
KEY `vehicleDms_FK_1` (`dmsFk`),
CONSTRAINT `vehicleDms_FK` FOREIGN KEY (`vehicleFk`) REFERENCES `vehicle` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `vehicleDms_FK_1` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Gestion documental de vehicle';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `vehicleEvent`
--
DROP TABLE IF EXISTS `vehicleEvent`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `vehicleEvent` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`started` date DEFAULT NULL,
`finished` date DEFAULT NULL,
`vehicleStateFk` int(11) DEFAULT NULL,
`description` varchar(250) NOT NULL,
`vehicleFk` int(11) NOT NULL,
`userFk` int(10) unsigned NOT NULL,
`notified` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `vehicleEvent_FK` (`vehicleStateFk`),
KEY `vehicleEvent_FK_1` (`userFk`),
CONSTRAINT `vehicleEvent_FK` FOREIGN KEY (`vehicleStateFk`) REFERENCES `vehicleState` (`id`),
CONSTRAINT `vehicleEvent_FK_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `vehicleInvoiceIn`
--
DROP TABLE IF EXISTS `vehicleInvoiceIn`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `vehicleInvoiceIn` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`vehicleFk` int(10) unsigned NOT NULL,
`invoiceInFk` mediumint(8) unsigned NOT NULL,
`amount` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `vehicleInvoiceIn_FK` (`vehicleFk`),
KEY `vehicleInvoiceIn_FK_1` (`invoiceInFk`),
CONSTRAINT `vehicleInvoiceIn_FK` FOREIGN KEY (`vehicleFk`) REFERENCES `vehicle` (`id`),
CONSTRAINT `vehicleInvoiceIn_FK_1` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `vehicleNotes`
--
DROP TABLE IF EXISTS `vehicleNotes`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `vehicleNotes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`vehicleFk` int(10) unsigned NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`note` text NOT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `vehicleNotes_FK_1` (`userFk`),
KEY `vehicleNotes_FK` (`vehicleFk`),
CONSTRAINT `vehicleNotes_FK` FOREIGN KEY (`vehicleFk`) REFERENCES `vehicle` (`id`),
CONSTRAINT `vehicleNotes_FK_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `vehiclePlateRegex`
--
DROP TABLE IF EXISTS `vehiclePlateRegex`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `vehiclePlateRegex` (
`countryCodeFk` varchar(2) NOT NULL,
`regex` varchar(45) NOT NULL,
PRIMARY KEY (`countryCodeFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `vehicleState`
--
DROP TABLE IF EXISTS `vehicleState`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `vehicleState` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`state` varchar(100) NOT NULL,
`hasToNotify` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `viaexpressConfig`
--
DROP TABLE IF EXISTS `viaexpressConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `viaexpressConfig` (
`id` int(10) unsigned NOT NULL,
`url` varchar(100) NOT NULL,
`client` varchar(100) NOT NULL,
`user` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`defaultWeight` decimal(10,2) NOT NULL,
`deliveryType` varchar(5) NOT NULL,
`agencyModeFk` int(11) DEFAULT NULL COMMENT 'Indica el agencyMode que es interdia',
PRIMARY KEY (`id`),
KEY `viaexpressConfig_agencyMode_Fk` (`agencyModeFk`),
CONSTRAINT `viaexpressConfig_agencyMode_Fk` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`),
CONSTRAINT `viaexpressConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `volumeConfig`
--
DROP TABLE IF EXISTS `volumeConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `volumeConfig` (
`palletM3` decimal(10,2) DEFAULT NULL COMMENT 'metros cúbicos',
`trolleyM3` decimal(10,2) DEFAULT NULL COMMENT 'metros cúbicos',
`dutchCompressionRate` double NOT NULL DEFAULT 1,
`standardFlowerBox` int(11) NOT NULL COMMENT 'en litros',
`minCompressionRate` decimal(10,2) DEFAULT 0.30 COMMENT 'minimo permitido por la empresa',
`ccLength` int(11) NOT NULL DEFAULT 130 COMMENT 'longitud útil para la carga de un CC, en cm',
`ccWidth` int(11) NOT NULL DEFAULT 60 COMMENT 'ancho útil para la carga en un CC, en cm',
`sorterPallet_m3` decimal(5,1) NOT NULL DEFAULT 2.0 COMMENT 'volumen minimo para extraer pallet del sorter',
`minTicketVolume` int(11) NOT NULL DEFAULT 75 COMMENT 'volumen mínimo, en litros, para que un pedido sea preparable',
`shelveVolume` int(11) DEFAULT 200 COMMENT 'volumen en litros de una bandeja standard, a efectos de los sacadores',
`minTicketValue` int(11) NOT NULL DEFAULT 50,
`aerealVolumetricDensity` decimal(10,1) DEFAULT 167.0 COMMENT 'factor de conversión para calcular el peso tasable aereo'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='almacena el valor standard para volumenes convencionales de Verdnatura, en metros cúbicos';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `wagon`
--
DROP TABLE IF EXISTS `wagon`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wagon` (
`id` varchar(6) NOT NULL COMMENT '26 letras de alfabeto inglés',
`volume` int(11) NOT NULL DEFAULT 150 COMMENT 'Volumen en litros',
`plate` varchar(10) NOT NULL COMMENT 'Matrícula',
`typeFk` int(11) unsigned NOT NULL,
`label` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `wagon_type` (`typeFk`),
CONSTRAINT `wagon_type` FOREIGN KEY (`typeFk`) REFERENCES `wagonType` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `wagonConfig`
--
DROP TABLE IF EXISTS `wagonConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wagonConfig` (
`id` int(10) unsigned NOT NULL,
`width` int(11) unsigned DEFAULT 1350,
`height` int(11) unsigned DEFAULT 1900,
`maxWagonHeight` int(11) unsigned DEFAULT 200,
`minHeightBetweenTrays` int(11) unsigned DEFAULT 50,
`maxTrays` int(11) unsigned DEFAULT 6,
PRIMARY KEY (`id`),
CONSTRAINT `wagonConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `wagonType`
--
DROP TABLE IF EXISTS `wagonType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wagonType` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
`divisible` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `wagonTypeColor`
--
DROP TABLE IF EXISTS `wagonTypeColor`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wagonTypeColor` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
`rgb` varchar(30) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
UNIQUE KEY `rgb` (`rgb`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `wagonTypeTray`
--
DROP TABLE IF EXISTS `wagonTypeTray`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wagonTypeTray` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`typeFk` int(11) unsigned DEFAULT NULL,
`height` int(11) unsigned NOT NULL,
`colorFk` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `typeFk` (`typeFk`,`height`),
KEY `wagonTypeTray_color` (`colorFk`),
CONSTRAINT `wagonTypeTray_color` FOREIGN KEY (`colorFk`) REFERENCES `wagonTypeColor` (`id`) ON UPDATE CASCADE,
CONSTRAINT `wagonTypeTray_type` FOREIGN KEY (`typeFk`) REFERENCES `wagonType` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `wagonVolumetry`
--
DROP TABLE IF EXISTS `wagonVolumetry`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wagonVolumetry` (
`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,
`height` int(10) unsigned NOT NULL DEFAULT 20,
`wagonFk` varchar(6) NOT NULL,
PRIMARY KEY (`id`),
KEY `wagonVolumetry_FK_1` (`wagonFk`),
CONSTRAINT `wagonVolumetry_FK_1` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) NOT NULL,
`code` varchar(3) DEFAULT NULL,
`isFeedStock` tinyint(1) unsigned NOT NULL DEFAULT 0,
`addressName` varchar(45) 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 COMMENT 'almacenes donde hay produccion',
`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 COMMENT '@deprecated 2024-01-23 refs #5167',
`labelReport` int(11) DEFAULT NULL,
`hasUbications` tinyint(1) NOT NULL DEFAULT 1,
`hasProduction` tinyint(1) NOT NULL DEFAULT 0,
`addressFk` int(11) DEFAULT NULL,
`hasMachine` tinyint(1) NOT NULL DEFAULT 0,
`isLogiflora` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Este almacén acepta productos de Logiflora',
`isBionic` tinyint(1) NOT NULL DEFAULT 1,
`isHalt` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Almacén en el que descargan nuestros troncales',
`isOrigin` tinyint(1) DEFAULT NULL,
`isDestiny` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`),
KEY `Id_Paises` (`countryFk`),
KEY `isComparativeIdx` (`isComparative`),
KEY `warehouse_ibfk_1_idx` (`aliasFk__`),
KEY `warehouse_FK` (`addressFk`),
KEY `warehouse_FK_1` (`pickUpAgencyModeFk`),
CONSTRAINT `warehouse_FK` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `warehouse_FK_1` FOREIGN KEY (`pickUpAgencyModeFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE,
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2024-01-23 refs #5167';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `warehousePickup`
--
DROP TABLE IF EXISTS `warehousePickup`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `warehousePickup` (
`warehouseFk` smallint(5) unsigned NOT NULL,
`agencyModeFk` int(11) DEFAULT NULL,
PRIMARY KEY (`warehouseFk`),
UNIQUE KEY `agency_id` (`agencyModeFk`,`warehouseFk`),
CONSTRAINT `warehousePickup_ibfk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `warehousePickup_ibfk_2` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Agencia de recogida para cada almacén';
/*!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 COMMENT 'Campo workcenter en A3',
`counter` bigint(20) DEFAULT NULL,
`warehouseFk` smallint(6) DEFAULT NULL,
`street` varchar(255) DEFAULT NULL,
`geoFk` int(11) DEFAULT NULL,
`deliveryManAdjustment` decimal(4,2) DEFAULT NULL COMMENT 'Número de trabajadores para equilibrar los repartidores de diferentes centros. Utilizado en repartidores de grafana',
PRIMARY KEY (`id`),
KEY `workCenter_geoFk_idx` (`geoFk`),
CONSTRAINT `workCenter_geoFk` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!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=utf8mb3 COLLATE=utf8mb3_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(10) unsigned NOT NULL AUTO_INCREMENT,
`code` varchar(3) NOT NULL,
`firstName` varchar(50) DEFAULT NULL,
`lastName` varchar(50) DEFAULT NULL,
`sub` int(11) unsigned DEFAULT NULL,
`photo` blob DEFAULT NULL,
`phone` varchar(15) DEFAULT NULL,
`mobileExtension` int(4) DEFAULT NULL,
`bossFk` int(10) unsigned DEFAULT 103,
`fiDueDate` datetime DEFAULT NULL,
`hasMachineryAuthorized` tinyint(2) DEFAULT 0,
`seniority` date DEFAULT NULL,
`isTodayRelative` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Para el F11. Calcula los problemas de visiblidad en funcion del dia actual',
`isF11Allowed` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Usuario autorizado para abrir el F11',
`maritalStatus` enum('S','M') NOT NULL,
`labelerFk__` tinyint(3) unsigned DEFAULT NULL COMMENT '@deprecated 2023-06-26',
`originCountryFk` mediumint(8) unsigned DEFAULT NULL COMMENT 'País de origen',
`educationLevelFk` smallint(6) DEFAULT NULL,
`SSN` varchar(15) DEFAULT NULL,
`fi` varchar(15) DEFAULT NULL,
`birth` date DEFAULT NULL,
`isDisable` tinyint(1) NOT NULL DEFAULT 0,
`isFreelance` tinyint(1) NOT NULL DEFAULT 0,
`isSsDiscounted` tinyint(1) NOT NULL DEFAULT 0,
`sex` enum('M','F') NOT NULL DEFAULT 'F' COMMENT 'M Masculino F Femenino',
`businessFk` int(11) DEFAULT NULL,
`balance` decimal(10,2) DEFAULT NULL,
`locker` int(10) unsigned DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `CodigoTrabajador_UNIQUE` (`code`),
UNIQUE KEY `worker_business` (`businessFk`),
UNIQUE KEY `locker` (`locker`),
KEY `sub` (`sub`),
KEY `boss_idx` (`bossFk`),
KEY `worker_FK` (`labelerFk__`),
KEY `worker_FK_2` (`educationLevelFk`),
KEY `worker_FK_1` (`originCountryFk`),
KEY `worker_fk_editor` (`editorFk`),
CONSTRAINT `worker_FK_1` FOREIGN KEY (`originCountryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE,
CONSTRAINT `worker_FK_2` FOREIGN KEY (`educationLevelFk`) REFERENCES `educationLevel` (`id`) ON UPDATE CASCADE,
CONSTRAINT `worker_FK_3` FOREIGN KEY (`bossFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `worker_businessFk` FOREIGN KEY (`businessFk`) REFERENCES `business` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `worker_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `worker_ibfk_1` FOREIGN KEY (`id`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `workerActivity`
--
DROP TABLE IF EXISTS `workerActivity`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerActivity` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` timestamp NULL DEFAULT current_timestamp(),
`model` enum('COM','ENT','TPV','ENC','LAB','ETI','APP') NOT NULL,
`workerFk` int(10) unsigned NOT NULL,
`event` enum('open','close','insert','delete','update','refresh') DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`workerActivityTypeFk` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_workerActivity_worker` (`workerFk`),
KEY `workerActivity_workerActivityType_FK` (`workerActivityTypeFk`),
CONSTRAINT `fk_workerActivity_worker` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `workerActivity_workerActivityType_FK` FOREIGN KEY (`workerActivityTypeFk`) REFERENCES `workerActivityType` (`code`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `workerActivityType`
--
DROP TABLE IF EXISTS `workerActivityType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerActivityType` (
`code` varchar(20) NOT NULL,
`description` varchar(45) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `workerAppTester`
--
DROP TABLE IF EXISTS `workerAppTester`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerAppTester` (
`workerFk` int(10) unsigned NOT NULL,
PRIMARY KEY (`workerFk`),
KEY `workerAppTester_FK` (`workerFk`),
CONSTRAINT `workerAppTester_FK_1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='La tabla incluye usuarios testers que actualizarán a una versión diferente que el resto para testear los cambios nuevos en las app';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `workerBosses`
--
DROP TABLE IF EXISTS `workerBosses`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerBosses` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`workerFk` int(10) unsigned NOT NULL,
`bossFk` int(10) unsigned 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `workerBusinessAgreement`
--
DROP TABLE IF EXISTS `workerBusinessAgreement`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerBusinessAgreement` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`monthHolidays` double DEFAULT NULL,
`yearHours` int(11) DEFAULT NULL,
`started` date DEFAULT NULL,
`ended` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `workerBusinessDated`
--
DROP TABLE IF EXISTS `workerBusinessDated`;
/*!50001 DROP VIEW IF EXISTS `workerBusinessDated`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `workerBusinessDated` AS SELECT
1 AS `dated`,
1 AS `businessFk`,
1 AS `workerFk` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `workerBusinessType`
--
DROP TABLE IF EXISTS `workerBusinessType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerBusinessType` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`isFullTime` tinyint(1) NOT NULL DEFAULT 1,
`isPermanent` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'Contrato fijo',
`hasHolidayEntitlement` tinyint(1) DEFAULT 1 COMMENT 'Tiene derecho a vacaciones',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 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 DEFAULT NULL,
`action` set('insert','update','delete','select') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text NOT NULL,
PRIMARY KEY (`id`),
KEY `logWorkerClockoriginFk` (`originFk`),
KEY `logWorkerClockuserFk` (`userFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`businessUpdated` date DEFAULT NULL,
`roleFk` int(10) unsigned NOT NULL COMMENT 'Rol por defecto al dar de alta un trabajador nuevo',
`businessTypeFk` varchar(100) DEFAULT NULL COMMENT 'Tipo de negocio por defecto al dar de alta un trabajador nuevo',
`payMethodFk` tinyint(3) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `workerConfig_FK` (`roleFk`),
KEY `workerConfig_FK_1` (`payMethodFk`),
CONSTRAINT `workerConfig_FK` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE,
CONSTRAINT `workerConfig_FK_1` FOREIGN KEY (`payMethodFk`) REFERENCES `payMethod` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `workerConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `workerDisableExcluded`
--
DROP TABLE IF EXISTS `workerDisableExcluded`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerDisableExcluded` (
`workerFk` int(10) unsigned NOT NULL,
`dated` date DEFAULT NULL,
PRIMARY KEY (`workerFk`),
CONSTRAINT `workerDisableExcludedFk1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='No se deshabilitan hasta la fecha especificada';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `workerDistributionCategory`
--
DROP TABLE IF EXISTS `workerDistributionCategory`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerDistributionCategory` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`workerFk` int(10) unsigned NOT NULL,
`category` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `workerDistributionCategory_workerFk_idx` (`workerFk`),
CONSTRAINT `workerDistributionCategory_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `workerDocument`
--
DROP TABLE IF EXISTS `workerDocument`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerDocument` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`worker` int(10) unsigned DEFAULT NULL,
`document` int(11) DEFAULT NULL,
`isReadableByWorker` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Indica si el empleado tiene permiso para acceder al documento',
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `workerDocument_ibfk_1` (`worker`),
KEY `workerDocument_ibfk_2` (`document`),
KEY `workerDocument_fk_editor` (`editorFk`),
CONSTRAINT `workerDocument_FK` FOREIGN KEY (`worker`) REFERENCES `worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `workerDocument_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `workerDocument_ibfk_2` FOREIGN KEY (`document`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`value` varchar(45) DEFAULT NULL COMMENT 'Table to save all responsible people phones',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`holidayInc` decimal(4,2) DEFAULT NULL,
`nightInc` decimal(4,2) DEFAULT NULL,
`extraInc` decimal(4,2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Recoge los acuerdos de los distintos convenios';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `workerIncome`
--
DROP TABLE IF EXISTS `workerIncome`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerIncome` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`debit` decimal(10,2) NOT NULL DEFAULT 0.00,
`credit` decimal(10,2) NOT NULL DEFAULT 0.00,
`incomeTypeFk` int(11) DEFAULT NULL,
`paymentDate` date DEFAULT NULL,
`workerFk` int(11) unsigned NOT NULL,
`concept` longtext DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `income_employeeId_incomeType_idx` (`incomeTypeFk`),
KEY `income_employee_workerFk_idx` (`workerFk`),
CONSTRAINT `income_employeeId_incomeType` FOREIGN KEY (`incomeTypeFk`) REFERENCES `payrollComponent` (`id`) ON UPDATE CASCADE,
CONSTRAINT `income_employee_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `workerIrpf`
--
DROP TABLE IF EXISTS `workerIrpf`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerIrpf` (
`workerFk` int(10) unsigned NOT NULL,
`spouseNif` varchar(45) DEFAULT NULL,
`geographicMobilityDate` date DEFAULT NULL,
`disabilityGradeFk` int(11) DEFAULT NULL,
`isDependend` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Acredita la necesidad de ayuda de terceras personas o movilidad reducida',
`familySituation` enum('1','2','3') DEFAULT '1',
`spousePension` decimal(10,2) DEFAULT NULL COMMENT 'Apartado 4 - Pensión compensatoria en favor del conyuge ',
`childPension` decimal(10,2) DEFAULT NULL COMMENT 'Apartado 4 - Anualidades por alimentos en favor de los hijos',
`hasHousingPaymentBefore` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Apartado 5 - Pagos por adquisición o rehabilitación de la vivienda habitual utilizando financiación ajena, con derecho a deducción del IRPF',
`hasHousingPaymentAfter` tinyint(1) NOT NULL DEFAULT 0,
`hasExtendedWorking` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Aprtado 1 - prolongar la actividad laboral',
`updated` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`workerFk`),
KEY `workerIrpf_disabilityGradeFk` (`disabilityGradeFk`),
CONSTRAINT `workerIrpf_disabilityGradeFk` FOREIGN KEY (`disabilityGradeFk`) REFERENCES `disabilityGrade` (`id`) ON UPDATE CASCADE,
CONSTRAINT `workerIrpf_wokerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Modelo 145 IRPF apartado 1 - 4 y 5 ';
/*!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,
`holiday` decimal(5,2) NOT NULL DEFAULT 0.00,
`priceHolidayHour` 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,
`priceExtraHoliday` 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`),
KEY `workerJourney_dated_idx` (`dated`),
KEY `workerJourney_businessFk` (`businessFk`),
CONSTRAINT `fk_workerJourney_user` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE,
CONSTRAINT `workerJourney_businessFk` FOREIGN KEY (`businessFk`) REFERENCES `business` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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`,
1 AS `payedHolidays` */;
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(10) unsigned DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text DEFAULT NULL,
`changedModel` enum('Worker','Calendar','WorkerTimeControlMail','Business','WorkerDms','WorkerTimeControl') NOT NULL DEFAULT 'Worker',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `userFk_idx` (`userFk`),
KEY `workerLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `workerLog_originFk` (`originFk`,`creationDate`),
CONSTRAINT `userFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!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(10) unsigned 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,
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=utf8mb3 COLLATE=utf8mb3_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(10) unsigned 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=utf8mb3 COLLATE=utf8mb3_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 `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 `workerMistake`
--
DROP TABLE IF EXISTS `workerMistake`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerMistake` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userFk` int(10) unsigned NOT NULL,
`workerMistakeTypeFk` varchar(10) NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `workerMistake_fk1_idx` (`userFk`),
KEY `workerMistake_fk2_idx` (`workerMistakeTypeFk`),
CONSTRAINT `workerMistake_fk1` FOREIGN KEY (`userFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `workerMistake_fk2` FOREIGN KEY (`workerMistakeTypeFk`) REFERENCES `workerMistakeType` (`code`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `workerMistakeType`
--
DROP TABLE IF EXISTS `workerMistakeType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerMistakeType` (
`code` varchar(10) NOT NULL,
`description` varchar(45) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `workerObservation`
--
DROP TABLE IF EXISTS `workerObservation`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerObservation` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`workerFk` int(10) unsigned DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`text` text NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `workerFk_workerObservation_FK` (`workerFk`),
KEY `userFk_workerObservation_FK` (`userFk`),
CONSTRAINT `userFk_workerObservation_FK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE,
CONSTRAINT `workerFk_workerObservation_FK` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Todas las observaciones referentes a un trabajador';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `workerRelatives`
--
DROP TABLE IF EXISTS `workerRelatives`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerRelatives` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`workerFk` int(10) unsigned NOT NULL,
`isDescendant` tinyint(1) DEFAULT 1 COMMENT 'Descendientes - Ascendientes',
`disabilityGradeFk` int(11) DEFAULT NULL,
`birthed` int(4) NOT NULL,
`adoptionYear` int(4) DEFAULT NULL COMMENT 'Solo en el caso de descendientes',
`isDependend` tinyint(1) DEFAULT 0,
`isJointCustody` tinyint(1) DEFAULT 0 COMMENT 'Solo en el caso de descendientes',
`updated` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `workerRelatives_disabilityGradeFk` (`disabilityGradeFk`),
KEY `workerRelatives_workerFk` (`workerFk`),
CONSTRAINT `workerRelatives_disabilityGradeFk` FOREIGN KEY (`disabilityGradeFk`) REFERENCES `disabilityGrade` (`id`) ON UPDATE CASCADE,
CONSTRAINT `workerRelatives_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `workerIrpf` (`workerFk`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Modelo 145 IRPF apartado 2 y 3';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `workerShelving`
--
DROP TABLE IF EXISTS `workerShelving`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerShelving` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`workerFk` int(10) unsigned NOT NULL,
`shelvingFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`collectionFk` int(11) DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `workerShelving_shelving_fk` (`shelvingFk`),
KEY `workerShelving_FK` (`workerFk`),
KEY `workerShelving_FK_1` (`collectionFk`),
CONSTRAINT `workerShelving_FK` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `workerShelving_FK_1` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`code`) ON UPDATE CASCADE,
CONSTRAINT `workerShelving_worker_fk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='utilizaremos el id para establecer la prioridad de los carros a asignar';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `workerSpeedExpedition`
--
DROP TABLE IF EXISTS `workerSpeedExpedition`;
/*!50001 DROP VIEW IF EXISTS `workerSpeedExpedition`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `workerSpeedExpedition` AS SELECT
1 AS `ticketFk`,
1 AS `litros`,
1 AS `literLastHour`,
1 AS `litersByMinute`,
1 AS `workerCode`,
1 AS `cajas`,
1 AS `warehouseFk` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `workerSpeedSaleTracking`
--
DROP TABLE IF EXISTS `workerSpeedSaleTracking`;
/*!50001 DROP VIEW IF EXISTS `workerSpeedSaleTracking`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `workerSpeedSaleTracking` AS SELECT
1 AS `warehouseFk`,
1 AS `state`,
1 AS `workerCode`,
1 AS `sumaLitros`,
1 AS `started`,
1 AS `finished`,
1 AS `sumaLitrosLastHour`,
1 AS `litersByMinute`,
1 AS `departmentName` */;
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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,
`direction` enum('in','out','middle') DEFAULT 'middle',
`manual` tinyint(4) NOT NULL DEFAULT 0,
`order` int(11) DEFAULT NULL,
`device` varchar(255) DEFAULT NULL COMMENT 'Dispositivo en el que se ha fichado',
`warehouseFk` smallint(6) unsigned DEFAULT NULL,
`isSendMail` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'Fichadas generadas autómaticamente con el procedimiento vn.workerTimeControl_sendMail',
`logExclude` tinyint(1) GENERATED ALWAYS AS (if(`manual`,0,1)) VIRTUAL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `userFk_Timed_uniq` (`userFk`,`timed`),
KEY `warehouseFkfk1_idx` (`warehouseFk`),
KEY `timed_idx` (`timed`),
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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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(10) unsigned NOT NULL,
`dayBreak` int(11) NOT NULL,
`dayBreakDriver` int(11) NOT NULL,
`shortWeekBreak` int(11) NOT NULL,
`longWeekBreak` int(11) NOT NULL,
`weekScope` int(11) NOT NULL,
`mailPass` varchar(45) NOT NULL,
`mailHost` varchar(45) NOT NULL,
`mailSuccessFolder` varchar(45) NOT NULL,
`mailErrorFolder` varchar(45) NOT NULL,
`mailUser` varchar(45) NOT NULL,
`minHoursToBreak` decimal(5,2) unsigned NOT NULL COMMENT 'Horas mínimas que se deben trabajar para añadir descanso remunerado',
`breakHours` decimal(5,2) unsigned NOT NULL COMMENT 'Descanso remunerado',
`hoursCompleteWeek` int(10) unsigned NOT NULL COMMENT 'Horas a realizar por semana para que se considere jornada completa',
`startNightlyHours` time NOT NULL,
`endNightlyHours` time NOT NULL,
`maxTimePerDay` int(11) unsigned NOT NULL COMMENT 'Maximo tiempo transcurrido en segundos desde que se inicia la jornada hasta que se termina',
`breakTime` int(11) DEFAULT NULL COMMENT 'Tiempo de descanso expresado en segundos',
`timeToBreakTime` int(11) DEFAULT NULL COMMENT 'Tiempo mínimo que se debe trabajar para añadir descanso, expresado en segundos',
`dayMaxTime` int(11) DEFAULT NULL COMMENT 'Tiempo máximo desde la entrada hasta la salida, expresado en segundos',
`shortWeekDays` int(11) DEFAULT NULL COMMENT 'Días a tener en cuenta para calcular el descanso corto',
`longWeekDays` int(11) DEFAULT NULL COMMENT 'Días a tener en cuenta para calcular el descanso largo',
`teleworkingStart` int(11) DEFAULT NULL COMMENT 'Hora comienzo jornada de los teletrabajdores expresada en segundos',
`teleworkingStartBreakTime` int(11) DEFAULT NULL COMMENT 'Hora comienzo descanso de los teletrabjadores expresada en segundos',
`maxTimeToBreak` int(11) DEFAULT 3600,
`maxWorkShortCycle` int(10) unsigned DEFAULT 561600 COMMENT 'Máximo tiempo que un trabajador puede estar trabajando con el que adquirirá el derecho a un descanso semanal corto',
`maxWorkLongCycle` int(10) unsigned DEFAULT 950400 COMMENT 'Máximo tiempo que un trabajador puede estar trabajando con el que adquirirá el derecho a un descanso semanal largo',
PRIMARY KEY (`id`),
CONSTRAINT `workerTimeControlConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_bin COMMENT='All values in seconds';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `workerTimeControlError`
--
DROP TABLE IF EXISTS `workerTimeControlError`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerTimeControlError` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`code` char(35) NOT NULL,
`description` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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) DEFAULT NULL,
`created` datetime NOT NULL DEFAULT current_timestamp(),
`description` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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 `workerTimeControlMail`
--
DROP TABLE IF EXISTS `workerTimeControlMail`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerTimeControlMail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`workerFk` int(10) unsigned NOT NULL,
`year` int(4) NOT NULL,
`week` int(2) NOT NULL,
`state` enum('SENDED','CONFIRMED','REVISE') NOT NULL DEFAULT 'SENDED',
`updated` datetime NOT NULL DEFAULT current_timestamp() COMMENT 'Fecha/hora último cambio de estado',
`sendedCounter` int(3) NOT NULL DEFAULT 1 COMMENT 'Número de veces que se ha enviado el correo',
`reason` text DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `workerFk_UNIQUE` (`workerFk`,`year`,`week`),
KEY `workerFk_idx` (`workerFk`),
CONSTRAINT `workerTimeControlMail_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Guarda las respuestas de mail de los correos generados automáticamente por la procedimiento workerTimeControl_sendMail';
/*!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,
`weekMaxBreak` int(11) NOT NULL,
`weekMaxScope` int(11) NOT NULL,
`askInOut` int(11) NOT NULL COMMENT 'Tiempo desde la última fichada que determinará si se pregunta al usuario por la dirección de la fichada',
`mailPass` varchar(45) NOT NULL,
`mailHost` varchar(45) NOT NULL,
`mailSuccessFolder` varchar(45) NOT NULL,
`mailErrorFolder` varchar(45) NOT NULL,
`mailUser` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_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(10) unsigned NOT NULL,
`pin` varchar(255) NOT NULL,
PRIMARY KEY (`workerFk`),
CONSTRAINT `workerFk_.1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `workerTimeControlSchedule`
--
DROP TABLE IF EXISTS `workerTimeControlSchedule`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerTimeControlSchedule` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`time` time DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `punique_trhf` (`time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!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 `departmentFk`,
1 AS `dni` */;
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;
--
-- Temporary table structure for view `workerWithoutTractor`
--
DROP TABLE IF EXISTS `workerWithoutTractor`;
/*!50001 DROP VIEW IF EXISTS `workerWithoutTractor`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `workerWithoutTractor` AS SELECT
1 AS `workerFk`,
1 AS `Trabajador`,
1 AS `Colecciones`,
1 AS `created` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `workingHours`
--
DROP TABLE IF EXISTS `workingHours`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workingHours` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`timeIn` datetime NOT NULL,
`timeOut` datetime DEFAULT NULL,
`userId` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `user_working_hour_idx` (`userId`),
CONSTRAINT `user_working_hour` FOREIGN KEY (`userId`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Almacena horas de Entrada y de Salida del personal';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `zipConfig`
--
DROP TABLE IF EXISTS `zipConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zipConfig` (
`id` int(10) unsigned NOT NULL,
`maxSize` int(11) DEFAULT NULL COMMENT 'in MegaBytes',
PRIMARY KEY (`id`),
CONSTRAINT `zipConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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 utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL,
`hour` datetime NOT NULL,
`agencyModeFk` int(11) NOT NULL,
`travelingDays` int(11) NOT NULL DEFAULT 1,
`price` double NOT NULL DEFAULT 0 CHECK (`price` > 0),
`bonus` double NOT NULL DEFAULT 0,
`isVolumetric` tinyint(1) NOT NULL DEFAULT 0,
`inflation` decimal(5,2) NOT NULL DEFAULT 1.00,
`m3Max` decimal(10,2) unsigned DEFAULT NULL,
`itemMaxSize` int(11) DEFAULT NULL COMMENT 'tamaño maximo de los articulos que esa ruta puede transportar',
`code` varchar(45) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_zone_2_idx` (`agencyModeFk`),
KEY `zone_name_idx` (`name`),
KEY `zone_fk_editor` (`editorFk`),
CONSTRAINT `fk_zone_2` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `zone_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `zoneAgencyMode`
--
DROP TABLE IF EXISTS `zoneAgencyMode`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneAgencyMode` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`agencyModeFk` int(11) NOT NULL,
`zoneFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `zoneAgencyMode_UN` (`agencyModeFk`,`zoneFk`),
KEY `zoneAgencyMode_FK_1` (`zoneFk`),
CONSTRAINT `zoneAgencyMode_FK` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `zoneAgencyMode_FK_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='junta agencias con zonas para que al enrutar se puedan proponer tickets.';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `zoneClosure`
--
DROP TABLE IF EXISTS `zoneClosure`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneClosure` (
`zoneFk` int(11) NOT NULL,
`dated` date NOT NULL,
`hour` time NOT NULL,
PRIMARY KEY (`zoneFk`,`dated`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `zoneConfig`
--
DROP TABLE IF EXISTS `zoneConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneConfig` (
`id` int(10) unsigned NOT NULL,
`scope` int(10) unsigned NOT NULL,
`forwardDays` int(10) NOT NULL DEFAULT 7 COMMENT 'days forward to show zone_upcomingDeliveries',
PRIMARY KEY (`id`),
CONSTRAINT `zoneConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `zoneEstimatedDelivery`
--
DROP TABLE IF EXISTS `zoneEstimatedDelivery`;
/*!50001 DROP VIEW IF EXISTS `zoneEstimatedDelivery`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `zoneEstimatedDelivery` AS SELECT
1 AS `zoneFk`,
1 AS `zoneClosureHour`,
1 AS `zoneHour`,
1 AS `volume`,
1 AS `hasToRecalcPrice`,
1 AS `m3`,
1 AS `minSpeed` */;
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,
`m3Max` decimal(10,2) unsigned DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `zoneFk` (`zoneFk`,`type`,`dated`),
KEY `zoneEvent_fk_editor` (`editorFk`),
CONSTRAINT `zoneEvent_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `zoneEvent_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!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,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`userFk` int(11) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `zoneFk_2` (`zoneFk`,`dated`),
KEY `zoneFk` (`zoneFk`),
KEY `zoneExclusion_fk_editor` (`editorFk`),
CONSTRAINT `zoneExclusion_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `zoneExclusion_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `zoneExclusionGeo`
--
DROP TABLE IF EXISTS `zoneExclusionGeo`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneExclusionGeo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`zoneExclusionFk` int(11) NOT NULL,
`geoFk` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `zoneExclusionGeo_UN` (`zoneExclusionFk`,`geoFk`),
KEY `zoneExclusionGeo2_FK_1` (`geoFk`),
CONSTRAINT `zoneExclusionGeo_FK` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON UPDATE CASCADE,
CONSTRAINT `zoneExclusionGeo_FK_1` FOREIGN KEY (`zoneExclusionFk`) REFERENCES `zoneExclusion` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `zoneFilter`
--
DROP TABLE IF EXISTS `zoneFilter`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneFilter` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`zoneFk` int(11) NOT NULL,
`sizeMax` int(11) DEFAULT NULL COMMENT 'altura máxima en cm',
`itemTypeFk` smallint(5) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `zoneFilter_FK` (`zoneFk`),
KEY `zoneFilter_FK_1` (`itemTypeFk`),
CONSTRAINT `zoneFilter_FK` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `zoneFilter_FK_1` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='recoge los parámetros para filtrar determinados productos según la zona';
/*!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','autonomy') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`name` varchar(100) DEFAULT NULL,
`parentFk` int(10) unsigned DEFAULT NULL,
`path` varchar(255) 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- 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=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `zoneIncluded`
--
DROP TABLE IF EXISTS `zoneIncluded`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneIncluded` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`zoneFk` int(11) NOT NULL,
`geoFk` int(11) NOT NULL,
`isIncluded` tinyint(1) DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_zone_geo` (`zoneFk`,`geoFk`),
KEY `zoneIncluded_fk_editor` (`editorFk`),
KEY `zoneIncluded_FK_2` (`geoFk`),
CONSTRAINT `zoneIncluded_FK_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `zoneIncluded_FK_2` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `zoneIncluded_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `zoneItemType`
--
DROP TABLE IF EXISTS `zoneItemType`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneItemType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`zoneFk` int(11) NOT NULL,
`itemTypeFk` smallint(5) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `zoneType_itemTypeFk_UNIQUE` (`zoneFk`,`itemTypeFk`),
KEY `zoneItemType_FK_1` (`itemTypeFk`),
CONSTRAINT `zoneItemType_FK` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `zoneItemType_FK_1` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Combinaciones prohibidas entre zone e itemType al calcular el catálogo de items';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `zoneLog`
--
DROP TABLE IF EXISTS `zoneLog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneLog` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`originFk` int(11) DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`action` set('insert','update','delete') NOT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`changedModel` enum('Zone','ZoneEvent','ZoneExclusion','ZoneIncluded','ZoneWarehouse') NOT NULL DEFAULT 'Zone',
`oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)),
`newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)),
`changedModelId` int(11) NOT NULL,
`changedModelValue` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `userFk` (`userFk`),
KEY `zoneLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`),
KEY `zoneLog_originFk` (`originFk`,`creationDate`),
CONSTRAINT `zoneLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1;
/*!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,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `zoneFk` (`zoneFk`,`warehouseFk`),
KEY `warehouseFk` (`warehouseFk`),
KEY `zoneWarehouse_fk_editor` (`editorFk`),
CONSTRAINT `zoneWarehouse_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `zoneWarehouse_fk_warehouse` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE,
CONSTRAINT `zoneWarehouse_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping events for database 'vn'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `clientsDisable` */;
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 = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `clientsDisable` ON SCHEDULE EVERY 1 MONTH STARTS '2023-06-01 00:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN
UPDATE account.user u
JOIN client c ON c.id = u.id
LEFT JOIN account.account a ON a.id = u.id
SET u.active = FALSE
WHERE c.typeFk = 'normal'
AND a.id IS NULL
AND u.active
AND c.created < util.VN_CURDATE() - INTERVAL 12 MONTH
AND u.id NOT IN (
SELECT DISTINCT c.id
FROM client c
LEFT JOIN ticket t ON t.clientFk = c.id
WHERE c.salesPersonFk IS NOT NULL
OR t.created > util.VN_CURDATE() - INTERVAL 12 MONTH
OR shipped > util.VN_CURDATE() - INTERVAL 12 MONTH
);
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 `client_unassignSalesPerson` */;;
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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `client_unassignSalesPerson` ON SCHEDULE EVERY 1 DAY STARTS '2023-06-01 03:30:00' ON COMPLETION PRESERVE ENABLE DO CALL client_unassignSalesPerson */ ;;
/*!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 `collection_make` */;;
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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_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`@`localhost`*/ /*!50106 EVENT `collection_make` ON SCHEDULE EVERY 5 MINUTE STARTS '2022-09-15 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL vn.collection_make */ ;;
/*!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 `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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `envialiaThreHoldChecker` ON SCHEDULE EVERY 1 DAY STARTS '2022-01-28 09:52:46' ON COMPLETION NOT PRESERVE ENABLE 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
CALL mail_insert(
'cau@verdnatura.es',
NULL,
'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 `greuge_notify` */;;
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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `greuge_notify` ON SCHEDULE EVERY 1 DAY STARTS '2023-01-01 00:07:00' ON COMPLETION NOT PRESERVE ENABLE COMMENT 'Notifies subscribed users of events in wrong greuges' DO CALL vn.greuge_notifyEvents() */ ;;
/*!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 `itemImageQueue_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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `itemImageQueue_check` ON SCHEDULE EVERY 1 HOUR STARTS '2023-07-28 00:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN
DELETE FROM itemImageQueue
WHERE attempts >= (SELECT downloadMaxAttempts FROM itemConfig);
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 `mysqlConnectionsSorter_kill` */;;
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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `mysqlConnectionsSorter_kill` ON SCHEDULE EVERY 1 MINUTE STARTS '2021-10-28 09:56:27' ON COMPLETION NOT PRESERVE ENABLE DO CALL mysqlConnectionsSorter_kill() */ ;;
/*!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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2022-01-28 09:52:46' ON COMPLETION PRESERVE ENABLE DO BEGIN
DECLARE vCurrentCount INT;
DECLARE vCheckSum INT;
DECLARE vIsAlreadyNotified BOOLEAN;
DECLARE vTableQueue TEXT;
DECLARE vLineQueue TEXT;
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vPrintQueueLimit INT;
DECLARE vCur CURSOR FOR
SELECT CONCAT('
', IFNULL(pq.id, ''), ' |
', IFNULL(p.path, ''),' |
', IFNULL(r.name, ''),' |
', IFNULL(pq.statusCode, ''),' |
', IFNULL(w.firstname, ''), " ", IFNULL(w.lastName, ''),' |
', IFNULL(pq.`error`, ''),' |
')
FROM printQueue pq
LEFT JOIN worker w ON w.id = pq.workerFk
LEFT JOIN printer p ON p.id = pq.printerFk
LEFT JOIN report r ON r.id = pq.reportFk
JOIN printQueueConfig
LIMIT vPrintQueueLimit;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
SELECT printQueueLimit INTO vPrintQueueLimit
FROM printQueueConfig;
SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum
FROM printQueue WHERE statusCode = 'queued';
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 '
Id Cola |
Ruta Impresora |
Informe |
Estado |
Trabajador |
Error |
' 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;
CALL mail_insert(
'cau@verdnatura.es',
NULL,
'Servidor de impresion parado',
CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '
')
);
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 `raidUpdate` */;;
DELIMITER ;;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
/*!50003 SET character_set_client = 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 = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `raidUpdate` ON SCHEDULE EVERY 1 DAY STARTS '2017-12-29 00:05:00' ON COMPLETION PRESERVE ENABLE DO CALL raidUpdate */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
/*!50003 SET character_set_results = @saved_cs_results */ ;;
/*!50003 SET collation_connection = @saved_col_connection */ ;;
/*!50106 DROP EVENT IF EXISTS `route_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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `route_doRecalc` ON SCHEDULE EVERY 10 SECOND STARTS '2021-07-08 07:32:23' ON COMPLETION PRESERVE ENABLE DO CALL route_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 `vehicle_notify` */;;
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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `vehicle_notify` ON SCHEDULE EVERY 1 DAY STARTS '2022-01-01 00:07:00' ON COMPLETION NOT PRESERVE ENABLE COMMENT 'Notifies subscribed users of events in vehicles that are about t' DO CALL vn.vehicle_notifyEvents */ ;;
/*!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 `workerJourney_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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `workerJourney_doRecalc` ON SCHEDULE EVERY 1 DAY STARTS '2023-07-22 04:00:00' ON COMPLETION PRESERVE ENABLE DO CALL workerJourney_replace(util.VN_CURDATE() - INTERVAL 1 WEEK, util.VN_CURDATE(), NULL) */ ;;
/*!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 `worker_updateChangedBusiness` */;;
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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `worker_updateChangedBusiness` ON SCHEDULE EVERY 1 DAY STARTS '2000-01-01 00:00:05' ON COMPLETION NOT PRESERVE ENABLE DO CALL worker_updateChangedBusiness */ ;;
/*!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 `zoneClosure_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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`salix`@`10.0.%.%`*/ /*!50106 EVENT `zoneClosure_doRecalc` ON SCHEDULE AT '2023-11-13 07:15:54' ON COMPLETION NOT PRESERVE DISABLE DO CALL zoneClosure_recalc */ ;;
/*!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 = utf8mb3 */ ;;
/*!50003 SET character_set_results = utf8mb3 */ ;;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `addressTaxArea`(vAddresId INT, vCompanyId INT) RETURNS varchar(25) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
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);
DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany;
CREATE TEMPORARY TABLE tmp.addressCompany
SELECT vAddresId addressFk, vCompanyId companyFk;
CALL vn.addressTaxArea();
SELECT areaFk INTO vTaxArea FROM tmp.addressTaxArea;
DROP TEMPORARY TABLE
tmp.addressCompany,
tmp.addressTaxArea;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `barcodeToItem`(vBarcode VARCHAR(22)) RETURNS int(11)
DETERMINISTIC
BEGIN
/**
* Obtiene el id del artículo
*
* @param vBarcode código de barras
*
* return id del item
*/
DECLARE vItemFk INT;
SELECT id INTO vItemFk
FROM vn.item
WHERE id = vBarcode OR comment = vBarcode
LIMIT 1;
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;
IF vItemFk THEN
RETURN vItemFk;
END IF;
SELECT i.id INTO vItemFk
FROM vn.item i
WHERE i.name LIKE CONCAT('%',vBarcode,'%')
ORDER BY i.id ASC
LIMIT 1;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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, packagingFk, 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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, packagingFk 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 <= util.VN_CURDATE()
AND warehouseFk = vWarehouse
ORDER BY dated DESC
LIMIT 1;
-- Margen
-- No se aplica margen, cau 12589
/* INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost)
SELECT vWarehouse, vItem, vComponentMargin, (vCost / ((100 - rate2) / 100)) - vCost
FROM vn.rate
WHERE dated <= util.VN_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(wm.pricesModifierRate, 3)
FROM client c
JOIN vn.workerMana wm ON c.salesPersonFk = wm.workerFk
WHERE wm.isPricesModifierActivated 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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);
CREATE OR REPLACE TEMPORARY TABLE tmp.client
SELECT vClient id;
CALL client_getMana();
SET vMana = (SELECT mana
FROM tmp.clientMana);
DROP TEMPORARY TABLE
tmp.client,
tmp.clientMana;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `clientTaxArea`(vClientId INT, vCompanyId INT) RETURNS varchar(25) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
READS SQL DATA
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);
SELECT addressTaxArea(defaultAddressFk, vCompanyId)
INTO vTaxArea
FROM client
WHERE id = vClientId;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `client_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `client_getDebt`(`vClient` INT, `vDate` DATE) RETURNS decimal(10,2)
READS SQL DATA
BEGIN
/**
* Returns the risk of a customer.
*
* @param vClient client id
* @param vDate date to check the risk
* @return Client risk
*/
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;
CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt (clientFk INT);
INSERT INTO tmp.clientGetDebt SET clientFk = vClient;
CALL vn.client_getDebt(vDate);
SELECT risk INTO vDebt FROM tmp.risk;
DROP TEMPORARY TABLE
tmp.clientGetDebt,
tmp.risk;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 clientFk
FROM vn.clientContact
WHERE phone = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 util.VN_CURDATE() 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `client_getSalesPersonCode`(vClientFk INT, vDated DATE) RETURNS varchar(3) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `client_getSalesPersonCodeByTicket`(vTicketFk INT) RETURNS varchar(3) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `client_hasDifferentCountries` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `client_hasDifferentCountries`(vClientFk INT) RETURNS tinyint(1)
READS SQL DATA
BEGIN
/**
* Return if client have address in different countries.
*
* @param vClientFk The id client
* @return BOOL
**/
RETURN (SELECT COUNT(DISTINCT c.id) > 1
FROM `address` a
JOIN province p ON p.id = a.provinceFk
JOIN country c ON c.id = p.countryFk
WHERE a.clientFk = vClientFk
AND a.isActive);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `collection_isPacked` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `collection_isPacked`(vSelf INT) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
/**
* Check if collection is packed.
*
* @param vSelf the collection to check
* @return true if the collection is packed
*/
DECLARE vTicketsWithoutExpeditions INT;
SELECT (COUNT(*) > 0) INTO vTicketsWithoutExpeditions
FROM vn.ticketCollection tc
LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk
WHERE tc.collectionFk = vSelf
AND ISNULL(e.id);
RETURN NOT vTicketsWithoutExpeditions;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `currency_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `currency_getCommission`(vSelf INT) RETURNS int(11)
DETERMINISTIC
BEGIN
/**
* Devuelve el tipo de cambio en el dia de hoy dada el tipo de moneda
*
* @param vSelf id del tipo de moneda
* @return devuelve la comision
*/
DECLARE vCommission INT;
SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission
FROM referenceCurrent r
WHERE r.currencyFk = vSelf
AND r.`dated` <= util.VN_CURDATE()
ORDER BY r.`dated` DESC
LIMIT 1;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `currentRate`(vCurrencyFk INT, vDated DATE) RETURNS decimal(10,4)
READS SQL DATA
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `deviceProductionUser_accessGranted` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `deviceProductionUser_accessGranted`(vUserFK INT(10) , android_id VARCHAR(50)) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
/*
* Comprueba si el usuario puede entrar en la aplicacion de almacen con ese movil
*
* */
/*DECLARE vIsGranted BOOLEAN;
DECLARE vDeviceProductionFk INT(11) DEFAULT NULL;
SELECT dp.id INTO vDeviceProductionFk
FROM vn.deviceProduction dp
WHERE dp.android_id = android_id;
IF vDeviceProductionFk THEN
SELECT COUNT(*) INTO vIsGranted
FROM vn.deviceProductionUser dpu
WHERE dpu.userFk = vUserFK
AND dpu.deviceProductionFk = vDeviceProductionFk;
RETURN vIsGranted;
END IF;*/
RETURN TRUE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `duaTax_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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `duaTax_getRate`(vDuaFk INT, vTaxClassFk INT) RETURNS decimal(5,2)
DETERMINISTIC
BEGIN
/**
* Devuelve el rate para un Dua teniendo en cuenta la fecha de opreción del DUA
*
* @param vDuaFk Identificador de la tabla dua
* @param vTaxClassFk Identificador del IVA de la tabla invoiceInTaxBookingAccount
*/
RETURN (
SELECT rate
FROM dua d
JOIN supplier s ON s.id = d.companyFk
JOIN invoiceInTaxBookingAccount iit ON iit.countryFk = s.countryFk
AND iit.taxClassFk = vTaxClassFk
AND iit.effectived <= IFNULL( d.operated, util.VN_CURDATE())
WHERE d.id = vDuaFk
ORDER BY effectived DESC
LIMIT 1);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `ekt_getEntry` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ekt_getEntry`(vEktFk INT) RETURNS int(11)
READS SQL DATA
BEGIN
/**
* Devuelve el numero de entrada para el ekt
*
* @param vEktFk Identificador de edi.ekt
*/
DECLARE vTravelFk INT;
DECLARE vEntryFk INT DEFAULT 0;
DECLARE vEntryAssignFk INT;
SELECT ea.id
INTO vEntryAssignFk
FROM edi.ekt e
JOIN vn.ektEntryAssign ea ON
IFNULL(ea.sub, e.sub) <=> e.sub AND
IFNULL(ea.kop, e.kop) <=> e.kop AND
IFNULL(ea.pro, e.pro) <=> e.pro AND
IFNULL(ea.auction, e.auction) <=> e.auction
WHERE e.id = vEktFk
ORDER BY
IF(ea.sub,1,0) * 1000 +
IF(ea.kop,1,0) * 100 +
IF(ea.pro,1,0) * 10 +
IF(ea.auction,1,0) DESC
LIMIT 1;
SET vTravelFk = vn.ekt_getTravel(vEntryAssignFk, vEktFk);
IF vTravelFk THEN
SELECT MAX(e.id)
INTO vEntryFk
FROM vn.entry e
JOIN vn.ektEntryAssign ea ON ea.id = vEntryAssignFk
WHERE e.travelFk = vTravelFk
AND e.sub <=> ea.sub
AND e.kop <=> ea.kop
AND e.pro <=> ea.pro
AND e.auction <=> ea.auction
AND e.companyFk <=> ea.companyFk;
IF vEntryFk IS NULL THEN
INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk, kop, sub, reference, pro, auction)
SELECT vTravelFk, ea.supplierFk, ea.companyFk, cu.id, ea.kop, ea.sub, ea.ref, ea.pro, ea.auction
FROM vn.ektEntryAssign ea
JOIN vn.currency cu ON cu.code = 'EUR'
WHERE ea.id = vEntryAssignFk;
SET vEntryFk = LAST_INSERT_ID();
END IF;
UPDATE vn.ektEntryAssign
SET entryFk = vEntryFk
WHERE id = vEntryAssignFk;
ELSE
SELECT ec.defaultEntry INTO vEntryFk
FROM vn.entryConfig ec;
INSERT IGNORE INTO vn.entry(id) VALUES(vEntryFk);
END IF;
RETURN vEntryFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `ekt_getTravel` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ekt_getTravel`(vEntryAssignFk INT, vEktFk INT) RETURNS int(11)
READS SQL DATA
BEGIN
/**
* Devuelve un vn.travel.id
*
* @param vEntryAssignFk Identificador de vn.entryAssign
*/
DECLARE vTravelFk INT;
IF vEntryAssignFk IS NOT NULL THEN
SELECT MAX(tr.id) INTO vTravelFk
FROM vn.travel tr
JOIN vn.ektEntryAssign ea ON ea.id = vEntryAssignFk
JOIN edi.ekt e ON e.id = vEktFk
WHERE ea.warehouseOutFk = tr.warehouseOutFk
AND ea.warehouseInFk = tr.warehouseInFk
AND ea.agencyModeFk = tr.agencyModeFk
AND tr.landed = e.fec;
IF vTravelFk IS NULL THEN
INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk)
SELECT e.fec, e.fec, ea.warehouseInFk, ea.warehouseOutFk, ea.agencyModeFk
FROM edi.ekt e
JOIN vn.ektEntryAssign ea ON ea.kop = e.kop
WHERE e.id = vEktFk
ORDER BY
IF(ea.sub,1,0) * 1000 +
IF(ea.kop,1,0) * 100 +
IF(ea.pro,1,0) * 10 +
IF(ea.auction,1,0) DESC
LIMIT 1;
SET vTravelFk = LAST_INSERT_ID();
END IF;
END IF;
RETURN vTravelFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `entry_getForLogiflora` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `entry_getForLogiflora`(vLanded DATE, vWarehouseFk INT) RETURNS int(11)
READS SQL DATA
BEGIN
/**
* Devuelve una entrada para Logiflora. Si no existe la crea.
*
* @param vLanded Fecha de llegada al almacén
* @param vWarehouseFk Identificador de vn.warehouse
*/
DECLARE vTravelFk INT;
DECLARE vEntryFk INT;
DECLARE previousEntryFk INT;
SET vTravelFk = vn.travel_getForLogiflora(vLanded, vWarehouseFk);
IF vLanded THEN
SELECT IFNULL(MAX(id),0) INTO vEntryFk
FROM vn.entry
WHERE travelFk = vTravelFk
AND isRaid;
IF NOT vEntryFk THEN
INSERT INTO vn.entry(travelFk, supplierFk, commission, companyFk, currencyFk, isRaid)
SELECT vTravelFk, s.id, 4, c.id, cu.id, TRUE
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 MAX(id) INTO vEntryFk
FROM vn.entry
WHERE travelFk = vTravelFk;
END IF;
END IF;
SELECT entryFk INTO previousEntryFk
FROM edi.warehouseFloramondo wf
WHERE wf.warehouseFk = vWarehouseFk;
IF IFNULL(previousEntryFk,0) != vEntryFk THEN
UPDATE buy b
SET b.printedStickers = 0
WHERE entryFk = previousEntryFk;
DELETE FROM buy WHERE entryFk = previousEntryFk;
DELETE FROM entry WHERE id = previousEntryFk;
END IF;
RETURN vEntryFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `entry_isIntrastat` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `entry_isIntrastat`(vSelf INT) RETURNS int(11)
READS SQL DATA
BEGIN
/**
* Devuelve si el proveedor de la entrada es de la CEE
*
* @param vSelf Id de la entrada
* @return true si es de la CEE
*/
DECLARE vIsUeeSupplier BOOLEAN;
DECLARE vIsUeeCompany BOOLEAN;
DECLARE vSupplierCountry INT;
DECLARE vCompanyCountry INT;
SELECT IFNULL(a.isUeeMember, c.isUeeMember), c.id
INTO vIsUeeSupplier, vSupplierCountry
FROM entry e
JOIN supplier s ON s.id = e.supplierFk
JOIN country c ON c.id = s.countryFk
LEFT JOIN province p ON p.id = s.provinceFk
LEFT JOIN autonomy a ON a.id = p.autonomyFk
WHERE e.id = vSelf;
SELECT IFNULL(a.isUeeMember, c.isUeeMember), c.id
INTO vIsUeeCompany, vCompanyCountry
FROM entry e
JOIN supplier s ON s.id = e.companyFk
JOIN country c ON c.id = s.countryFk
LEFT JOIN province p ON p.id = s.provinceFk
LEFT JOIN autonomy a ON a.id = p.autonomyFk
WHERE e.id = vSelf;
RETURN vIsUeeCompany AND vIsUeeSupplier AND (vSupplierCountry <> vCompanyCountry);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `entry_isInventoryOrPrevious` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `entry_isInventoryOrPrevious`(vSelf INT) RETURNS int(11)
DETERMINISTIC
BEGIN
DECLARE vIsInventoryOrPrevious BOOL;
SELECT ec.inventorySupplierFk = e.supplierFk OR t.landed < c.inventoried
INTO vIsInventoryOrPrevious
FROM entry e
JOIN travel t ON e.travelFk = t.id
JOIN entryConfig ec
JOIN config c
WHERE e.id = vSelf;
RETURN vIsInventoryOrPrevious;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `expedition_checkRoute` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `expedition_checkRoute`(vPalletFk INT,vExpeditionFk INT) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
/**
* Comprueba si las expediciones del pallet son todas
* de la misma ruta.
*
* @param vExpeditionFk numero de expedition a comprobar
* @param vPalletFk numero de pallet
* @return vHasDistinctRoutes
*/
DECLARE vRouteFk INT;
DECLARE vHasDistinctRoutes BOOL;
SELECT t.routeFk INTO vRouteFk
FROM vn.expedition e
JOIN vn.ticket t ON e.ticketFk = t.id
WHERE e.id = vExpeditionFk;
SELECT COUNT(*) > 0 INTO vHasDistinctRoutes
FROM vn.expeditionScan es
JOIN vn.expedition e ON es.expeditionFk = e.id
JOIN vn.ticket t ON e.ticketFk = t.id
WHERE es.palletFk = vPalletFk
AND t.routeFk <> vRouteFk;
RETURN vHasDistinctRoutes;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `firstDayOfWeek` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `firstDayOfWeek`(vYear INT, vWeek INT) RETURNS date
DETERMINISTIC
BEGIN
/**
* Returns the date of the first day of the week
*
* @param vYear The year
* @param vWeek The week number
* @return Date of the first day of the week
*/
DECLARE vDate DATE;
SELECT dated INTO vDate
FROM `time`
WHERE `year` = vYear
AND `week` = vWeek
ORDER BY dated
LIMIT 1;
RETURN 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `getAlert3State`(vTicket INT) RETURNS varchar(45) CHARSET utf8mb3 COLLATE utf8mb3_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `getDueDate`(vDated DATE, vDayToPay INT) RETURNS date
NO SQL
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `getInventoryDate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `getInventoryDate`() RETURNS date
DETERMINISTIC
BEGIN
RETURN (SELECT inventoried FROM config 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `getNewItemId`() RETURNS int(11)
READS SQL DATA
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `getNextDueDate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `getNextDueDate`(vDated DATE, vGapDays INT, vPayDay INT) RETURNS date
NO SQL
BEGIN
DECLARE vReturn DATE;
DECLARE vDuaDate DATE;
DECLARE vDuaDateDay INT;
SELECT TIMESTAMPADD(DAY, vGapDays, vDated) INTO vDuaDate;
IF vDuaDate = CONCAT(YEAR(vDuaDate), '-03-01') THEN
SET vDuaDate = TIMESTAMPADD (DAY , -1, vDuaDate);
ELSEIF vDuaDate = CONCAT(YEAR(vDuaDate), '-02-29') THEN
SET vDuaDate = TIMESTAMPADD (DAY , -2, vDuaDate);
END IF;
IF MONTH(vDuaDate) = 2 AND vPayDay = 30 THEN
IF util.isLeapYear(YEAR(vDuaDate)) THEN
SET vPayDay = 29;
ELSE
SET vPayDay = 28;
END IF;
END IF;
SELECT DAY(vDuaDate) INTO vDuaDateDay;
RETURN TIMESTAMPADD(MONTH, (vDuaDateDay > vPayDay), DATE_FORMAT(vDuaDate, CONCAT('%y/%m/', vPayDay)));
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `getSpecialPrice`(vItemFk int(11),vClientFk int(11)) RETURNS decimal(10,2)
READS SQL DATA
BEGIN
DECLARE price DECIMAL(10,2);
SELECT rate3 INTO price
FROM vn.priceFixed
WHERE itemFk = vItemFk
AND util.VN_CURDATE() BETWEEN started AND ended ORDER BY created DESC LIMIT 1;
SELECT `value` INTO price
FROM vn.specialPrice
WHERE itemFk = vItemFk
AND (clientFk = vClientFk OR clientFk IS NULL)
AND started <= util.VN_CURDATE()
AND (ended >= util.VN_CURDATE() OR ended IS NULL)
ORDER BY id DESC LIMIT 1;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `getTicketTrolleyLabelCount` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `getTicketTrolleyLabelCount`(vTicket INT) RETURNS int(11)
READS SQL DATA
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 */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `getUser`() RETURNS int(11)
DETERMINISTIC
BEGIN
/**
* @deprecated Use account.userGetId()
*/
RETURN account.myUser_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `getUserId` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `getUserId`(userName varchar(30)) RETURNS int(11)
READS SQL DATA
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 */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `hasAnyNegativeBase`() RETURNS tinyint(1)
DETERMINISTIC
BEGIN
/**
* Calcula si existe alguna base imponible negativa
* Requiere la tabla temporal tmp.ticketToInvoice(id) para getTaxBases()
*
* returns BOOLEAN
*/
DECLARE hasAnyNegativeBase BOOLEAN;
CALL getTaxBases();
SELECT negative INTO hasAnyNegativeBase
FROM tmp.taxBases
LIMIT 1;
DROP TEMPORARY TABLE
tmp.ticketTax,
tmp.ticket,
tmp.taxBases;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `hasAnyPositiveBase` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `hasAnyPositiveBase`() RETURNS tinyint(1)
DETERMINISTIC
BEGIN
/**
* Calcula si existe alguna base imponible positiva
* Requiere la tabla temporal tmp.ticketToInvoice(id) para getTaxBases()
*
* returns BOOLEAN
*/
DECLARE hasAnyPositiveBase BOOLEAN;
CALL getTaxBases();
SELECT positive INTO hasAnyPositiveBase
FROM tmp.taxBases
LIMIT 1;
DROP TEMPORARY TABLE
tmp.ticketTax,
tmp.ticket,
tmp.taxBases;
RETURN hasAnyPositiveBase;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `hasItemsInSector` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `hasItemsInSector`(vTicketFk INT, vSectorFk INT) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
DECLARE vItemCount INT;
SELECT count(*) INTO vItemCount
FROM vn.sale s
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
WHERE s.ticketFk = vTicketFk
AND p.sectorFk = vSectorFk;
RETURN vItemCount;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `hasSomeNegativeBase`(vTicket INT) RETURNS tinyint(1)
READS SQL DATA
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `intrastat_estimateNet` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `intrastat_estimateNet`(vSelf INT,
vStems INT
) RETURNS double
DETERMINISTIC
BEGIN
/**
* Calcula un valor neto estimado en función de
* datos históricos de facturas intrastat.
*
* @param vSelf Id de intrastat
* @param vStems Número de unidades
* @return vNet
*/
DECLARE vNet DOUBLE;
SELECT ROUND(vStems / (SUM(average) / COUNT(average)), 2) INTO vNet
FROM (
SELECT *, stems / net average
FROM invoiceInIntrastat
WHERE intrastatFk = vSelf
AND net
AND stems > 0
ORDER BY dated DESC
LIMIT 20
) sub;
RETURN vNet/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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `invoiceOutAmount`(vInvoiceRef VARCHAR(15)) RETURNS decimal(10,2)
READS SQL DATA
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 invoiceOutExpense 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `invoiceOut_getMaxIssued` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `invoiceOut_getMaxIssued`(vSerial VARCHAR(2),
vCompanyFk INT,
vYear INT
) RETURNS date
READS SQL DATA
BEGIN
/**
* Retorna la fecha a partir de la cual es válido emitir una factura
*
* @param vSerial Serie de facturación
* @param vCompanyFk Empresa factura emitida
* @param vYear Año contable
* @return vInvoiceOutIssued fecha factura válida
*/
DECLARE vInvoiceOutIssued DATE;
DECLARE vFirstDayOfYear DATE;
SET vFirstDayOfYear := MAKEDATE(vYear, 1);
SELECT IFNULL(MAX(io.issued), vFirstDayOfYear) INTO vInvoiceOutIssued
FROM invoiceOut io
WHERE io.serial = vSerial
AND io.companyFk = vCompanyFk
AND io.issued BETWEEN vFirstDayOfYear
AND util.lastDayOfYear(vFirstDayOfYear);
RETURN vInvoiceOutIssued;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `invoiceOut_getPath`(vSelf INT) RETURNS varchar(255) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `invoiceOut_getWeight` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `invoiceOut_getWeight`(vInvoiceRef VARCHAR(15)
) RETURNS decimal(10,2)
READS SQL DATA
BEGIN
/**
* Calcula el peso de una factura emitida
*
* @param vInvoiceRef referencia de la factura
* @return vTotalWeight peso de la factura
*/
DECLARE vTotalWeight DECIMAL(10,2);
SELECT SUM(CAST(IFNULL(i.stems, 1)
* s.quantity
* IF(ic.grams, ic.grams, IFNULL(i.weightByPiece, 0)) / 1000 AS DECIMAL(10,2)))
INTO vTotalWeight
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
JOIN itemCost ic ON ic.itemFk = i.id
AND ic.warehouseFk = t.warehouseFk
WHERE t.refFk = vInvoiceRef
AND i.intrastatFk;
RETURN vTotalWeight;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `invoiceSerial`(vClientFk INT, vCompanyFk INT, vType CHAR(1)) RETURNS char(1) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `invoiceSerialArea`(vType CHAR(1), vTaxArea VARCHAR(25)) RETURNS char(1) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
DETERMINISTIC
BEGIN
DECLARE vSerie CHAR(1);
IF vType = 'R' THEN
SELECT
CASE vTaxArea
WHEN 'CEE' THEN 'H'
WHEN 'WORLD' THEN 'E'
ELSE 'T'
END INTO vSerie;
-- Factura multiple
ELSEIF vType = 'M' THEN
SELECT
CASE vTaxArea
WHEN 'CEE' THEN 'H'
WHEN 'WORLD' THEN 'E'
ELSE 'M'
END INTO vSerie;
-- Factura global
ELSEIF vType = 'G' THEN
SELECT
CASE vTaxArea
WHEN 'CEE' THEN 'V'
WHEN 'WORLD' THEN 'X'
ELSE '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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `isLogifloraDay` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `isLogifloraDay`(vShipped DATE, vWarehouse INT) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
DECLARE vIsLogifloraDay BOOLEAN;
SELECT COUNT(*) INTO vIsLogifloraDay
FROM edi.warehouseFloramondo wf
JOIN vn.floramondoConfig fc
WHERE wf.warehouseFk = vWarehouse
AND vShipped BETWEEN DATE(TIMESTAMPADD(DAY, wf.travellingDays , fc.nextLanded))
AND DATE(TIMESTAMPADD(DAY, wf.travellingDays + wf.dayRange , fc.nextLanded));
RETURN vIsLogifloraDay;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `itemsInSector_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `itemsInSector_get`(vTicketFk INT, vSectorFk INT) RETURNS int(11)
READS SQL DATA
BEGIN
DECLARE vItemCount INT;
SELECT count(*) INTO vItemCount
FROM vn.sale s
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
WHERE s.ticketFk = vTicketFk
AND p.sectorFk = vSectorFk;
RETURN vItemCount;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `item_getFhImage` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `item_getFhImage`(itemFk INT) RETURNS varchar(255) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
DETERMINISTIC
BEGIN
DECLARE vImageUrl VARCHAR(255);
SELECT sr.PictureReference INTO vImageUrl
FROM vn.buy b
JOIN edi.ekt e ON b.ektFk = e.id
JOIN edi.supplyResponse sr ON sr.Item_ArticleCode =e.`ref`
JOIN vn.item i ON i.id = b.itemFk
WHERE b.itemFk = itemFk
ORDER BY (sr.EmbalageCode = e.package) DESC
LIMIT 1;
RETURN vImageUrl;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `item_getPackage` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `item_getPackage`(vItemFk INT) RETURNS varchar(50) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
DETERMINISTIC
BEGIN
DECLARE vDiameter INT;
DECLARE vPackageFk VARCHAR(50);
DECLARE vCoeficient DOUBLE DEFAULT 1.08;
SELECT MAX(LEFT(value,3)) INTO vDiameter
FROM vn.itemTag it
JOIN vn.tag t ON t.id = it.tagFk
WHERE it.itemFk = vItemFk
AND t.overwrite = 'diameter';
SELECT 8000 + FLOOR(vc.ccLength * vc.ccWidth / (vCoeficient * PI() * (vDiameter / 2) * (vDiameter / 2)))
INTO vPackageFk
FROM vn.volumeConfig vc;
INSERT IGNORE INTO vn.packaging(id, width, `depth`)
SELECT vPackageFk,
FLOOR(vc.ccWidth / FLOOR(vc.ccWidth / vDiameter)),
FLOOR(vc.ccLength / FLOOR(vc.ccLength / vDiameter))
FROM vn.volumeConfig vc;
RETURN vPackageFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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(IFNULL(p.height,0), p.height, IFNULL(i.size,60) + 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `lastDayOfWeek` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `lastDayOfWeek`(vYear INT, vWeek INT) RETURNS date
DETERMINISTIC
BEGIN
/**
* Returns the date of the last day of the week
*
* @param vYear The year
* @param vWeek The week number
* @return Date of the first day of the week
*/
DECLARE vDate DATE;
SELECT dated INTO vDate
FROM `time`
WHERE `year` = vYear
AND `week` = vWeek
ORDER BY dated DESC
LIMIT 1;
RETURN 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `machine_checkPlate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `machine_checkPlate`(vPlate VARCHAR(10)) RETURNS tinyint(1)
READS SQL DATA
BEGIN
/**
* Comprueba si existe matrícula
*
* @param vPlate matrícula del vehículo
* @return Devuelve TRUE en caso de que exista
*
*/
IF (SELECT COUNT(*)
FROM machine m
WHERE m.plate = vPlate
) THEN
RETURN TRUE;
ELSE
RETURN FALSE;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `messageSend`(vRecipient VARCHAR(255) CHARSET utf8, vMessage TEXT CHARSET utf8) RETURNS int(11)
READS SQL DATA
BEGIN
DECLARE result INT;
DECLARE vSenderFk INT;
SELECT id INTO vSenderFk
FROM account.user WHERE `name` = account.myUser_getName();
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `MIDNIGHT` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 * ic.cm3delivery)/1000000,0) INTO vVolume
FROM hedera.orderRow o
JOIN item i ON i.id = o.itemFk
JOIN itemCost ic on ic.itemFk = o.itemFk AND ic.warehouseFk = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `orderTotalVolumeBoxes`(vOrderId INT) RETURNS decimal(10,3)
READS SQL DATA
BEGIN
/**
* Devuelve el volumen estimado del ticket sumado, en cajas
*
* @param vOrder Id del pedido
*/
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `packaging_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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `packaging_calculate`(isPackageReturnable TINYINT(1),
packagingReturnFk INT(11),
base DECIMAL(10,2),
price DECIMAL(10,2),
upload VARCHAR(255)) RETURNS decimal(10,2)
DETERMINISTIC
BEGIN
DECLARE vAmount INT DEFAULT NULL;
DECLARE vValue DECIMAL(10,2);
IF isPackageReturnable THEN
SELECT cb.freightPackagingFull INTO vAmount
FROM returnBuckets cb
WHERE cb.id = packagingReturnFk;
SET vValue = IF (vAmount IS NULL,
IFNULL(base,0),
vAmount / IFNULL(upload, 0) + IFNULL(base, 0));
ELSE
SET vValue = IFNULL(price, 0) + IFNULL(base, 0);
END IF;
RETURN vValue;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `priceFixed_getRate2` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `priceFixed_getRate2`(vFixedPriceFk INT, vRate3 DOUBLE) RETURNS double
BEGIN
DECLARE vWarehouse INT;
DECLARE vRate2 DOUBLE;
SELECT round(vRate3 * (1 + ((r.rate2 - r.rate3)/100)), 2) INTO vRate2
FROM vn.rate r
JOIN vn.priceFixed p ON p.id = vFixedPriceFk
WHERE r.dated <= p.started
AND r.warehouseFk = p.warehouseFk
ORDER BY r.dated DESC
LIMIT 1;
RETURN vRate2;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `routeProposal` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `routeProposal`(vTicketFk INT) RETURNS int(11)
READS SQL DATA
BEGIN
DECLARE vRouteFk INT;
DECLARE vAddressFk INT;
DECLARE vLanded DATE;
DECLARE vZoneFk INT;
DECLARE vSignificativeFriendship INT DEFAULT 6;
DECLARE vVolumeMax DECIMAL(5,1) DEFAULT 10;
SELECT addressFk, zoneFk, landed INTO vAddressFk, vZoneFk, vLanded
FROM vn.ticket
WHERE id = vTicketFk;
-- Se inicia la selección de rutas posibles con aquellas cuyas agencias alguna vez han estado asociadas con nuestra zona
DROP TEMPORARY TABLE IF EXISTS tmp.route;
CREATE TEMPORARY TABLE tmp.route
SELECT r.id routeFk,
zf.friendship zoneFriendship
FROM vn.route r
JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk
WHERE friendship >= vSignificativeFriendship
AND zf.zoneFk = vZoneFk
AND r.created = vLanded
ORDER BY friendship;
-- Se eliminan aquellas que superan el volumen máximo
DELETE r.*
FROM tmp.route r
JOIN (SELECT routeFk, sum(volume) volume
FROM vn.saleVolume
WHERE landed = vLanded
GROUP BY routeFk) sub ON sub.routeFk = r.routeFk
WHERE sub.volume > vVolumeMax;
-- Se ordenan las que quedan en función con la afinidad del resto de consignatarios de cada ruta
SELECT routeFk INTO vRouteFk
FROM
(SELECT r.routeFk, r.zoneFriendship, sum(af.friendship) friendshipSum
FROM tmp.route r
LEFT JOIN vn.ticket t ON t.routeFk = r.routeFk
LEFT JOIN cache.addressFriendship af ON af.addressFk2 = t.addressFk AND af.addressFk1 = vAddressFk
GROUP BY routeFk
ORDER BY zoneFriendship DESC, friendshipSum DESC
) sub
LIMIT 1;
RETURN 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `routeProposal_` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `routeProposal_`(vTicketFk INT) RETURNS int(11)
READS SQL DATA
BEGIN
DECLARE vRouteFk INT;
DECLARE vAddressFk INT;
DECLARE vShipped DATETIME;
SELECT addressFk, date(shipped) INTO vAddressFk, vShipped
FROM vn.ticket
WHERE id = vTicketFk;
SELECT routeFk INTO vRouteFk
FROM
(SELECT t.routeFk, sum(af.friendship) friendshipSum
FROM vn.ticket t
JOIN cache.addressFriendship af ON af.addressFk2 = t.addressFk AND af.addressFk1 = vAddressFk
WHERE t.shipped BETWEEN vShipped and MIDNIGHT(vShipped)
AND t.routeFk
GROUP BY routeFk
ORDER BY friendshipSum DESC
) sub
LIMIT 1;
RETURN 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `routeProposal_beta` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `routeProposal_beta`(vTicketFk INT) RETURNS int(11)
READS SQL DATA
BEGIN
DECLARE vRouteFk INT;
DECLARE vAddressFk INT;
DECLARE vLanded DATE;
DECLARE vZoneFk INT;
DECLARE vSignificativeFriendship INT DEFAULT 6;
DECLARE vVolumeMax DECIMAL(5,1) DEFAULT 10;
SELECT addressFk, zoneFk, landed INTO vAddressFk, vZoneFk, vLanded
FROM vn.ticket
WHERE id = vTicketFk;
-- Se inicia la selección de rutas posibles con aquellas cuyas agencias alguna vez han estado asociadas con nuestra zona
DROP TEMPORARY TABLE IF EXISTS tmp.route;
CREATE TEMPORARY TABLE tmp.route
SELECT r.id routeFk,
zf.friendship zoneFriendship
FROM vn.route r
JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk
WHERE friendship >= vSignificativeFriendship
AND zf.zoneFk = vZoneFk
AND r.created = vLanded
ORDER BY friendship;
-- Se eliminan aquellas que superan el volumen máximo
DELETE r.*
FROM tmp.route r
JOIN (SELECT routeFk, sum(volume) volume
FROM vn.saleVolume
WHERE landed = vLanded
GROUP BY routeFk) sub ON sub.routeFk = r.routeFk
WHERE sub.volume > vVolumeMax;
-- Se ordenan las que quedan en función con la afinidad del resto de consignatarios de cada ruta
SELECT routeFk INTO vRouteFk
FROM
(SELECT r.routeFk, r.zoneFriendship, sum(af.friendship) friendshipSum
FROM tmp.route r
LEFT JOIN vn.ticket t ON t.routeFk = r.routeFk
LEFT JOIN cache.addressFriendship af ON af.addressFk2 = t.addressFk AND af.addressFk1 = vAddressFk
GROUP BY routeFk
ORDER BY zoneFriendship DESC, friendshipSum DESC
) sub
LIMIT 1;
RETURN 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `specie_IsForbidden` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `specie_IsForbidden`(vItemFk INT, vAddressFk INT) RETURNS tinyint(1)
READS SQL DATA
BEGIN
DECLARE vIsForbbiden BOOL;
DECLARE vLeft INT;
SELECT zg.lft INTO vLeft
FROM vn.address a
JOIN vn.zoneGeo zg ON zg.name = a.postalCode
WHERE a.id = vAddressFk;
SELECT sgi.isForbidden INTO vIsForbbiden
FROM vn.specieGeoInvasive sgi
JOIN vn.zoneGeo zg ON zg.id = sgi.zoneGeofk
JOIN vn.itemBotanical ib ON ib.genusFk = sgi.genusFk AND sgi.specieFk IN ('sp.',ib.specieFk)
WHERE vLeft BETWEEN zg.lft AND zg.rgt
AND ib.itemFk = vItemFk
ORDER BY zg.`depth` DESC
LIMIT 1;
RETURN IFNULL(vIsForbbiden, 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `testCIF` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `testCIF`(vCIF VARCHAR(9)) RETURNS varchar(10) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
DETERMINISTIC
BEGIN
DECLARE vLetraInicial VARCHAR(1);
DECLARE vLetraFinal VARCHAR(1);
DECLARE vParteNumerica VARCHAR(7);
DECLARE vSuma INT DEFAULT 0;
DECLARE vNumero INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
DECLARE vResult BOOL DEFAULT FALSE;
SET vLetraInicial = SUBSTR(vCIF, 1, 1);
SET vLetraFinal = SUBSTR(vCIF, 9, 1);
SET vParteNumerica = SUBSTR(vCIF, 2, 7);
WHILE i < 7 DO
SET i = i + 1;
SET vNumero = CAST(SUBSTR(vParteNumerica, i, 1) AS DECIMAL(1,0));
IF i MOD 2 THEN
SET vNumero = vNumero * 2;
SET vNumero = vNumero MOD 10 + FLOOR(vNumero/10);
END IF;
SET vSuma = vSuma + vNumero;
END WHILE;
SET vSuma = vSuma MOD 10;
IF vSuma > 0 THEN
SET vSuma = 10 - vSuma;
END IF;
-- Comprobación de dígito de control
IF CAST(vLetraFinal AS DECIMAL(1,0)) = vSuma THEN
SET vResult = TRUE;
END IF;
IF vSuma = 0 THEN
SET vSuma = 10;
END IF;
IF CHAR(64 + vSuma) = vLetraFinal THEN
SET vResult = TRUE;
END IF;
-- Sólo se aceptan letras como caracter inicial
IF ASCII(vLetraInicial) < 65 OR ASCII(vLetraInicial) > 87 THEN -- Ha de ser entre la A y la W
SET vResult = FALSE;
END IF;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `testNIE` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `testNIE`(vNIE VARCHAR(9)) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
DECLARE vIndice INT;
DECLARE vNumero VARCHAR(7);
DECLARE vOperador VARCHAR(9);
DECLARE vParteNumerica DECIMAL(8,0);
DECLARE vLetraInicial VARCHAR(1);
DECLARE vLetraFinal VARCHAR(1);
DECLARE vLetrasFinalesPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE";
DECLARE vLetraInicialEsIncorrecta BOOL DEFAULT FALSE;
SET vLetraInicial = SUBSTR(vNIE, 1, 1);
SET vLetraFinal = SUBSTR(vNIE, 9, 1);
SET vNumero = SUBSTR(vNIE, 2, 7);
CASE vLetraInicial
WHEN 'X' THEN
SET vOperador = "0";
WHEN 'Y' THEN
SET vOperador = "1";
WHEN 'Z' THEN
SET vOperador = "2";
ELSE
SET vLetraInicialEsIncorrecta = TRUE;
END CASE;
SET vOperador = CONCAT(vOperador, vNumero);
SET vParteNumerica = CAST(vOperador AS DECIMAL(8,0));
SET vIndice = Round(vParteNumerica Mod 23, 0) + 1;
IF SUBSTR(vLetrasFinalesPosibles, vIndice, 1) = vLetraFinal AND vLetraInicialEsIncorrecta = FALSE THEN
RETURN TRUE;
ELSE
RETURN FALSE;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `testNIF` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `testNIF`(vNIF VARCHAR(9)) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
DECLARE vIndice INT;
DECLARE vParteNumerica DECIMAL(8,0);
DECLARE vLetra VARCHAR(1);
DECLARE vLetrasPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE";
SET vLetra = SUBSTRING(vNIF, 9, 1);
SET vParteNumerica = CAST(SUBSTRING(vNIF, 1, 8) AS DECIMAL(8,0));
SET vIndice = Round(vParteNumerica MOD 23, 0) + 1;
If SUBSTRING(vLetrasPosibles, vIndice, 1) = vLetra Then
RETURN TRUE;
ELSE
RETURN FALSE;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `ticketCollection_getNoPacked` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticketCollection_getNoPacked`(vCollectionFk INT) RETURNS varchar(100) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci
DETERMINISTIC
BEGIN
/*
* return message with tickets and collection if there is tickets of a collection without expeditions
*
* @param vCollectionFk the collection to check
* @return an array with collection and tickets without expeditions
*
*/
DECLARE vAnswer VARCHAR(100) DEFAULT '';
IF collection_isPacked(vCollectionFk) = FALSE THEN
SELECT CONCAT('Colección: ',tc.collectionFk,' Tickets: ' , GROUP_CONCAT(tc.ticketFk) ) INTO vAnswer
FROM vn.ticketCollection tc
LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk
WHERE tc.collectionFk = vCollectionFk
AND ISNULL(e.id);
END IF;
RETURN 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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(NULL);
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticketPositionInPath`(vTicketId INT) RETURNS varchar(10) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
DETERMINISTIC
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.ticketFk = t.id
WHERE t.id = vTicketId;
SELECT (a.`name` = 'VN_VALENCIA')
INTO vIsValenciaPath
FROM `route` r
JOIN agencyMode am on am.id = r.agencyModeFk
JOIN agency a on a.id = am.agencyFk
WHERE r.id = 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.ticketFk
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.ticketFk
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticketSplitCounter`(vTicketFk INT) RETURNS varchar(15) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
READS SQL DATA
BEGIN
DECLARE vSplitCounter VARCHAR(15);
SELECT CONCAT(printedStickers,'/',Total, IF(printedStickers = Total ,' LS','')) INTO vSplitCounter
FROM
(
SELECT count(sl.saleFk) as printedStickers, COUNT(*) as Total
FROM sale s
LEFT JOIN saleLabel sl ON sl.saleFk = s.id
WHERE ticketFk = vTicketFk
) sub;
RETURN IFNULL(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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticketTotalVolume`(vTicketId INT) RETURNS decimal(10,3)
READS SQL DATA
BEGIN
-- Devuelte el volumen total del ticket sumado
DECLARE vVolume DECIMAL(10,3);
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticketWarehouseGet`(vTicketFk INT) RETURNS int(11)
READS SQL DATA
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `ticket_CC_volume` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_CC_volume`(vTicketFk INT) RETURNS decimal(10,1)
READS SQL DATA
BEGIN
DECLARE vCC DECIMAL(10,1);
SELECT sum(sv.volume * IF(i.itemPackingTypeFk = 'H', vc.dutchCompressionRate, 1)) / (p.volume / 1000000)
INTO vCC
FROM vn.saleVolume sv
JOIN vn.sale s ON s.id = sv.saleFk
JOIN vn.item i ON i.id = s.itemFk
JOIN vn.packaging p ON p.id = 'CC'
JOIN vn.volumeConfig vc
WHERE sv.ticketFk = vTicketFk;
RETURN vCC;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `ticket_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_get`(vParamFk INT) RETURNS int(11)
READS SQL DATA
proc:BEGIN
/* Devuelve el número de ticket o collection consultando en varias tablas posibles
*
* @param vParamFk Número a validar
* @return vValidFk Identificador validado
*/
DECLARE vValidFk INT;
-- Tabla vn.saleGroup
SELECT s.ticketFk INTO vValidFk
FROM vn.sale s
JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk
WHERE sg.id = vParamFk
AND sg.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE())
LIMIT 1;
IF vValidFk THEN
RETURN vValidFk;
LEAVE proc;
END IF;
-- Tabla vn.collection
SELECT c.id INTO vValidFk
FROM vn.collection c
WHERE c.id = vParamFk
AND c.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE());
IF vValidFk THEN
RETURN vValidFk;
LEAVE proc;
END IF;
-- Tabla vn.ticket
SELECT t.id INTO vValidFk
FROM vn.ticket t
WHERE t.id = vParamFk
AND t.shipped > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE());
IF vValidFk THEN
RETURN vValidFk;
LEAVE proc;
END IF;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `ticket_getFreightCost` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_getFreightCost`(vTicketFk INT) RETURNS decimal(10,2)
DETERMINISTIC
BEGIN
/**
* Devuelve el coste de transportar un ticket.
*
* @vTicketFk Id del ticket a calcular
*/
DECLARE deliveryPrice DECIMAL (10,2);
IF (SELECT isVolumetric FROM ticket t JOIN zone z ON t.zoneFk = z.id
WHERE t.id = vTicketFk) THEN
SELECT SUM(sv.freight) INTO deliveryPrice
FROM vn.saleVolume sv
WHERE sv.ticketFk = vTicketFk;
ELSE
SELECT SUM((t.zonePrice - t.zoneBonus) * ebv.ratio) INTO deliveryPrice
FROM vn.ticket t
LEFT JOIN expedition e ON e.ticketFk = t.id
JOIN expeditionBoxVol ebv ON ebv.boxFk = e.freightItemFk
WHERE t.id = vTicketFk;
END IF;
RETURN deliveryPrice;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `ticket_getWeight` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_getWeight`(vTicketFk INT) RETURNS decimal(10,3)
READS SQL DATA
BEGIN
/**
* Devuelve el peso total del ticket
*
* @return Total peso
*/
DECLARE vWeight DECIMAL(10,3);
SELECT sum(weight) INTO vWeight
FROM saleVolume
WHERE ticketFk = vTicketFk;
RETURN vWeight;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `ticket_HasUbication` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_HasUbication`(vTicketFk INT) RETURNS tinyint(1)
READS SQL DATA
BEGIN
DECLARE hasUbication BOOL;
SELECT COUNT(*) INTO hasUbication
FROM vn.ticket t
JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk
WHERE rm.beachFk
AND t.id = vTicketFk;
RETURN hasUbication;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `ticket_isOutClosureZone` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_isOutClosureZone`(vSelf INT) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
/**
* Devuelve true/false si la hora actual supera la hora del cierre del ticket más el tiempo configurado en packingDelay
*
* @param vSelf Ticket id
* @return true o false
*/
DECLARE vIsTicketInTime BOOL;
SELECT TIMEDIFF(CURRENT_TIME(), zc.hour + INTERVAL tc.packingDelay HOUR) > 0 INTO vIsTicketInTime
FROM vn.ticket t
JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk
LEFT JOIN vn.ticketConfig tc ON TRUE
WHERE t.id = vSelf
AND zc.dated = util.VN_CURDATE();
RETURN vIsTicketInTime;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 accounting 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `timeWorkerControl_getDirection`(vUserFk INT, vTimed DATETIME) RETURNS varchar(6) CHARSET utf8mb3 COLLATE utf8mb3_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `time_getSalesYear` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `time_getSalesYear`(vMonth INT, vYear INT) RETURNS int(11)
DETERMINISTIC
BEGIN
DECLARE vSalesYear INT;
SELECT salesYear INTO vSalesYear
FROM `time`
WHERE `month` = vMonth AND `year` = vYear
LIMIT 1;
RETURN vSalesYear;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `travel_getForLogiflora` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `travel_getForLogiflora`(vLanded DATE, vWarehouseFk INT) RETURNS int(11)
READS SQL DATA
BEGIN
/**
* Devuelve un número de travel para compras de Logiflora a partir de la fecha de llegada y del almacén.
* Si no existe lo genera.
*
* @param vLanded Fecha de llegada al almacén
* @param vWarehouseFk Identificador de vn.warehouse
*/
DECLARE vTravelFk INT;
IF vLanded THEN
SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk
FROM vn.travel tr
JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk
JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk
JOIN vn.agencyMode am ON am.id = tr.agencyModeFk
WHERE wIn.id = vWarehouseFk
AND wOut.name = 'Holanda'
AND am.name = 'LOGIFLORA'
AND landed = vLanded;
IF NOT vTravelFk THEN
INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk)
SELECT vLanded, util.VN_CURDATE(), vWarehouseFk, wOut.id, am.id
FROM vn.warehouse wOut
JOIN vn.agencyMode am ON am.name = 'LOGIFLORA'
WHERE wOut.name = 'Holanda';
SELECT MAX(tr.id) INTO vTravelFk
FROM vn.travel tr
JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk
JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk
WHERE wIn.id = vWarehouseFk
AND wOut.name = 'Holanda'
AND landed = vLanded;
END IF;
END IF;
RETURN vTravelFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `travel_hasUniqueAwb` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `travel_hasUniqueAwb`(vSelf INT
) RETURNS tinyint(1)
READS SQL DATA
BEGIN
/**
* Comprueba que el travel pasado tiene un AWB lógico,
* no se pueden tener varios AWB asociados al mismo DUA
*
* @param vSelf Id del travel
*/
DECLARE vHasUniqueAwb BOOL DEFAULT TRUE;
SELECT NOT COUNT(t2.awbFk) INTO vHasUniqueAwb
FROM entry e
JOIN travel t ON t.id = e.travelFk
JOIN duaEntry de ON de.entryFk = e.id
JOIN duaEntry de2 ON de2.duaFk = de.duaFk
JOIN entry e2 ON e2.id = de2.entryFk
JOIN travel t2 ON t2.id = e2.travelFk
WHERE t.id = vSelf
AND t2.awbFk <> t.awbFk;
RETURN vHasUniqueAwb;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `validationCode`(vString VARCHAR(255)) RETURNS int(11)
DETERMINISTIC
BEGIN
DECLARE vSeed DOUBLE DEFAULT 0;
DECLARE vCode INT;
DECLARE vLength INT;
DECLARE vChar INT;
SET vLength = length(vString);
WHILE vLength > 0 DO
SET vChar = MID(vString,vLength,1);
SET vSeed = vSeed + ASCII(vChar);
SET vLength = vLength - 1;
END WHILE;
SET vCode = FLOOR(SQRT(vSeed)*1000000) 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `validationCode_beta` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `validationCode_beta`(vString VARCHAR(255)) RETURNS int(11)
DETERMINISTIC
BEGIN
DECLARE vSeed DOUBLE DEFAULT 0;
DECLARE vCode INT;
DECLARE vLength INT;
DECLARE vChar INT;
SET vLength = length(vString);
WHILE vLength > 0 DO
SET vChar = MID(vString,vLength,1);
SET vSeed = vSeed + ASCII(vChar);
SET vLength = vLength - 1;
END WHILE;
SET vCode = FLOOR(SQRT(vSeed)*1000000) 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `workerMachinery_isRegistered` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `workerMachinery_isRegistered`(vWorkerFk VARCHAR(10)) RETURNS tinyint(1)
READS SQL DATA
BEGIN
/**
* Comprueba si existen registros en las últimas horas (maxHours de machineWorkerConfig) del trabajador vWorkerFk y si tiene a nulo la hora outTimed (indica la hora que deja el vehículo)
*
* @param vWorkerFk id del trabajador
* @return Devuelve TRUE/FALSE en caso de que haya o no registros
*/
IF (SELECT COUNT(*)
FROM machineWorker m
WHERE m.workerFk = vWorkerFk
AND m.inTimed >= TIMESTAMPADD(HOUR , -(SELECT maxHours from machineWorkerConfig), util.VN_NOW()) AND ISNULL(m.outTimed))
THEN
RETURN TRUE;
ELSE
RETURN FALSE;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `workerNigthlyHours_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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `workerNigthlyHours_calculate`(vTimeIn DATETIME, vTimeOut DATETIME) RETURNS decimal(5,2)
READS SQL DATA
BEGIN
/**
* Calcula el número decimal de horas nocturnas comprendidas entre 2 horas dadas
*
* @param vTimeIn
* @param vTimeOut
* @return vNigthlyHours
*/
DECLARE vNigthlyHours DECIMAL(5,2);
DECLARE vSecondsPerHour INT(4) DEFAULT 3600;
SELECT GREATEST(0, TIMESTAMPDIFF(SECOND,
IF(TIME(vTimeIn) BETWEEN endNightlyHours AND startNightlyHours,
CONCAT(DATE(vTimeIn), ' ', startNightlyHours),
vTimeIn),
IF(TIME(vTimeOut) BETWEEN endNightlyHours AND startNightlyHours,
CONCAT(DATE(vTimeOut), ' ', endNightlyHours),
vTimeOut))) / vSecondsPerHour INTO vNigthlyHours
FROM vn.workerTimeControlConfig;
RETURN vNigthlyHours;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `worker_getCode` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `worker_getCode`() RETURNS varchar(3) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
READS SQL DATA
BEGIN
DECLARE vUserCode VARCHAR(3) CHARSET utf8 COLLATE utf8_unicode_ci;
SELECT code INTO vUserCode
FROM worker
WHERE id = account.myUser_getId();
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `worker_isBoss` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `worker_isBoss`(vUserId INT) RETURNS int(11)
DETERMINISTIC
BEGIN
/**
* Comprueba por jerarquía si el trabajador actual es jefe
* de un trabajador en concreto.
*
* @param vSelf 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 worker
WHERE id = vSelf;
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 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 = account.myUser_getId() 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `worker_isInDepartment` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `worker_isInDepartment`(vDepartmentCode VARCHAR(255)) RETURNS int(11)
DETERMINISTIC
BEGIN
/**
* Devuelve booleano si el trabajador conectado pertenece
* al departamento vDepartmentCode o a sus departamentos subordinados
*
* @param vDepartmentCode code del departamento que se desea comprobar.
* @return Devuelve verdadero si es jefe del empleado por escala jerárquica.
*/
DECLARE vIsInDepartment BOOLEAN;
WITH RECURSIVE department AS (
SELECT d.id FROM vn.department d WHERE code = vDepartmentCode
UNION
SELECT d.id
FROM department ds
JOIN vn.department d ON ds.id = d.parentFk
)
SELECT COUNT(*) INTO vIsInDepartment FROM department ds
JOIN vn.workerDepartment wd ON wd.departmentFk = ds.id
WHERE wd.workerFk = account.myUser_getId();
RETURN vIsInDepartment;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP FUNCTION IF EXISTS `worker_isWorking` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `worker_isWorking`(vWorkerFk INT) RETURNS tinyint(1)
READS SQL DATA
BEGIN
/**
* Comprueba si el trabajador está trabajando en el momento de la consulta
* @return Devuelve TRUE en caso de que este trabajando. Si se encuentra en un descanso devolverá FALSE
*/
DECLARE vLastIn DATETIME ;
SELECT MAX(timed) INTO vLastIn
FROM vn.workerTimeControl
WHERE userFk = vWorkerFk AND
direction = 'in';
IF (SELECT MOD(COUNT(*),2)
FROM vn.workerTimeControl
WHERE userFk = vWorkerFk AND
timed >= vLastIn
) THEN
RETURN TRUE;
ELSE
RETURN FALSE;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `absoluteInventoryHistory` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `absoluteInventoryHistory`(
vItemFk INT,
vWarehouseFk INT,
vDate DATETIME
)
BEGIN
/**
* Calcula y proporciona un historial de inventario absoluto
* para un artículo específico en un almacén dado
* hasta una fecha determinada.
*
* @param vItemFk Id de artículo
* @param vWarehouseFk Id de almacén
* @param vDate Fecha
*/
DECLARE vCalculatedInventory INT;
DECLARE vToday DATETIME DEFAULT util.VN_CURDATE();
DECLARE vStartDate DATE DEFAULT '2001-01-01';
CREATE OR REPLACE TEMPORARY TABLE tHistoricalPast
ENGINE = MEMORY
SELECT *
FROM (
SELECT tr.landed `date`,
b.quantity input,
NULL `output`,
tr.isReceived ok,
s.name alias,
e.invoiceNumber reference,
e.id id,
tr.isDelivered f5
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
WHERE tr.landed >= vStartDate
AND s.id <> (SELECT supplierFk FROM inventoryConfig)
AND vWarehouseFk IN (tr.warehouseInFk, 0)
AND b.itemFk = vItemFk
AND NOT e.isExcludedFromAvailable
AND NOT e.isRaid
UNION ALL
SELECT tr.shipped,
NULL,
b.quantity,
tr.isDelivered,
s.name,
e.invoiceNumber,
e.id,
tr.isDelivered
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
WHERE tr.shipped >= vStartDate
AND vWarehouseFk = tr.warehouseOutFk
AND s.id <> (SELECT supplierFk FROM inventoryConfig)
AND b.itemFk = vItemFk
AND NOT e.isExcludedFromAvailable
AND NOT e.isRaid
UNION ALL
SELECT t.shipped,
NULL,
m.quantity,
(m.isPicked OR t.isLabeled OR t.refFk IS NOT NULL),
t.nickname,
t.refFk,
t.id,
t.isPrinted
FROM sale m
JOIN ticket t ON t.id = m.ticketFk
JOIN client c ON c.id = t.clientFk
WHERE t.shipped >= vStartDate
AND m.itemFk = vItemFk
AND vWarehouseFk IN (t.warehouseFk, 0)
) t1
ORDER BY `date`, input DESC, ok DESC;
SELECT SUM(input) - SUM(`output`) INTO vCalculatedInventory
FROM tHistoricalPast
WHERE `date` < vDate;
SELECT p1.*, NULL v_virtual
FROM (
SELECT vDate `date`,
vCalculatedInventory input,
NULL `output`,
1 ok,
'Inventario calculado' alias,
'' reference,
0 id,
1 f5
UNION ALL
SELECT *
FROM tHistoricalPast
WHERE `date` >= vDate
) p1;
DROP TEMPORARY TABLE tHistoricalPast;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `addAccountReconciliation` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `addAccountReconciliation`()
BEGIN
/**
* Updates duplicate records in the accountReconciliation table,
* by assigning them a new identifier and then inserts a new entry in the till table.
*/
UPDATE accountReconciliation ar
JOIN (
SELECT id,
calculatedCode,
CONCAT(
calculatedCode,
'(',
ROW_NUMBER() OVER (PARTITION BY calculatedCode ORDER BY id),
')'
) newId
FROM accountReconciliation ar
WHERE calculatedCode IN (
SELECT calculatedCode
FROM accountReconciliation
GROUP BY calculatedCode
HAVING COUNT(*) > 1
)
ORDER BY calculatedCode, id
) sub2 ON ar.id = sub2.id
SET ar.calculatedCode = sub2.newId;
INSERT INTO till(
dated,
isAccountable,
serie,
concept,
`in`,
`out`,
bankFk,
companyFk,
warehouseFk,
supplierAccountFk,
calculatedCode,
InForeignValue,
OutForeignValue,
workerFk
)
SELECT ar.operationDated,
TRUE,
'MB',
ar.concept,
IF(ar.debitCredit = 'credit' AND a.currencyFk = arc.currencyFk, ar.amount, NULL),
IF(ar.debitCredit = 'debit' AND a.currencyFk = arc.currencyFk, ar.amount, NULL),
a.id,
sa.supplierFk,
arc.warehouseFk,
ar.supplierAccountFk,
ar.calculatedCode,
IF(ar.debitCredit = 'credit' AND NOT a.currencyFk = arc.currencyFk, ar.amount, NULL),
IF(ar.debitCredit = 'debit' AND NOT a.currencyFk = arc.currencyFk, ar.amount, NULL),
account.myUser_getId()
FROM accountReconciliation ar
JOIN supplierAccount sa ON sa.id = ar.supplierAccountFk
JOIN accounting a ON a.id = sa.accountingFk
LEFT JOIN till t ON t.calculatedCode = ar.calculatedCode
JOIN accountReconciliationConfig arc
WHERE t.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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)
*/
DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea;
CREATE TEMPORARY TABLE tmp.addressTaxArea
(PRIMARY KEY (addressFk, companyFk))
ENGINE = MEMORY
SELECT CASE
WHEN (NOT IFNULL(auClient.isUeeMember, cClient.isUeeMember) OR NOT cSupplier.isUeeMember)
AND NOT (auSupplier.id <=> auClient.id) THEN
'WORLD'
WHEN cClient.isUeeMember AND cSupplier.isUeeMember AND c.countryFk != s.countryFk AND c.isVies THEN
'CEE'
WHEN a.isEqualizated AND cClient.code = 'ES' 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
LEFT JOIN province pClient ON pClient.id = c.provinceFk
LEFT JOIN autonomy auClient ON auClient.id = pClient.autonomyFk
JOIN supplier s ON s.id = ac.companyFk
JOIN country cSupplier ON cSupplier.id = s.countryFk
LEFT JOIN province pSupplier ON pSupplier.id = s.provinceFk
LEFT JOIN autonomy auSupplier ON auSupplier.id = pSupplier.autonomyFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 = util.VN_CURDATE(), t.maxHour > HOUR(util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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) >= util.VN_CURDATE()
AND IF(TIMESTAMPADD(DAY, -ah.substractDay, vDate) = util.VN_CURDATE(), ah.maxHour > HOUR(util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `agencyVolume` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `agencyVolume`()
BEGIN
/**
* Calculates and presents information on shipment and packaging volumes
* for agencies that are not owned for a specific period.
*/
DECLARE vStarted DATETIME DEFAULT util.VN_CURDATE();
DECLARE vEnded DATETIME DEFAULT util.dayEnd(util.VN_CURDATE());
SELECT ag.id agency_id,
CONCAT(RPAD(c.country, 16,' _') ,' ',ag.name) Agencia,
COUNT(*) expediciones,
SUM(t.packages) Bultos,
SUM(tpe.boxes) Faltan
FROM ticket t
JOIN warehouse w ON w.id = t.warehouseFk
JOIN country c ON w.countryFk = c.id
JOIN address a ON a.id = t.addressFk
JOIN agencyMode am ON am.id = t.agencyModeFk
JOIN agency ag ON ag.id = am.agencyFk
JOIN (
SELECT sv.ticketFk,
CEIL(1000 * SUM(sv.volume) / vc.standardFlowerBox) boxes
FROM ticket t
JOIN saleVolume sv ON sv.ticketFk = t.id
JOIN volumeConfig vc
WHERE t.shipped BETWEEN vStarted AND vEnded
AND (t.packages IS NULL OR NOT t.packages)
GROUP BY t.id
) tpe ON tpe.ticketFk = t.id
WHERE t.shipped BETWEEN vStarted AND vEnded
AND NOT ag.isOwn
GROUP BY ag.id
ORDER BY Agencia;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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_getShipped (vDate, vAddress, vAgencyMode, FALSE);
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `available_traslate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `available_traslate`(
vWarehouseLanding INT,
vDated DATE,
vWarehouseShipment INT)
proc: BEGIN
/**
* Calcular la disponibilidad dependiendo del almacen
* de origen y destino según la fecha.
*
* @param vWarehouseLanding Almacén de llegada
* @param vDated Fecha del calculo para la disponibilidad de articulos
* @param vWarehouseShipment Almacén de destino
*/
DECLARE vDatedFrom DATE;
DECLARE vDatedTo DATETIME;
DECLARE vDatedReserve DATETIME;
DECLARE vDatedInventory DATE;
IF vDated < util.VN_CURDATE() THEN
LEAVE proc;
END IF;
CALL item_getStock (vWarehouseLanding, vDated, NULL);
-- Calcula algunos parámetros necesarios.
SET vDatedFrom = vDated;
SET vDatedTo = util.dayEnd (vDated + INTERVAL 4 DAY);
SELECT inventoried INTO vDatedInventory FROM config;
SELECT SUBTIME(util.VN_NOW(), reserveTime) INTO vDatedReserve
FROM hedera.orderConfig;
-- Calcula el ultimo dia de vida para cada producto.
CREATE OR REPLACE TEMPORARY TABLE tItemRange
(PRIMARY KEY (itemFk))
ENGINE = MEMORY
SELECT c.itemFk, MAX(t.landed) dated
FROM buy c
JOIN entry e ON c.entryFk = e.id
JOIN travel t ON t.id = e.travelFk
JOIN warehouse w ON w.id = t.warehouseInFk
WHERE t.landed BETWEEN vDatedInventory AND vDatedFrom
AND t.warehouseInFk = vWarehouseLanding
AND NOT e.isExcludedFromAvailable
AND NOT e.isRaid
GROUP BY c.itemFk;
-- Tabla con el ultimo dia de last_buy para cada producto
-- que hace un replace de la anterior.
CALL buyUltimate(vWarehouseShipment, util.VN_CURDATE());
INSERT INTO tItemRange
SELECT t.itemFk, tr.landed
FROM tmp.buyUltimate t
JOIN buy b ON b.id = t.buyFk
JOIN entry e ON e.id = b.entryFk
JOIN travel tr ON tr.id = e.travelFk
LEFT JOIN tItemRange i ON t.itemFk = i.itemFk
WHERE t.warehouseFk = vWarehouseShipment
AND NOT e.isRaid
ON DUPLICATE KEY UPDATE tItemRange.dated = GREATEST(tItemRange.dated,
tr.landed);
CREATE OR REPLACE TEMPORARY TABLE tItemRangeLive
(PRIMARY KEY (itemFk))
ENGINE = MEMORY
SELECT ir.itemFk, util.dayEnd(ir.dated + INTERVAL it.life DAY) dated
FROM tItemRange ir
JOIN item i ON i.id = ir.itemFk
JOIN itemType it ON it.id = i.typeFk
HAVING dated >= vDatedFrom OR dated IS NULL;
-- Calcula el ATP.
CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc
(INDEX (itemFk,warehouseFk))
ENGINE = MEMORY
SELECT i.itemFk,
vWarehouseLanding warehouseFk,
i.shipped dated,
i.quantity
FROM itemTicketOut i
JOIN tItemRangeLive ir ON ir.itemFK = i.itemFk
WHERE i.shipped >= vDatedFrom
AND (ir.dated IS NULL OR i.shipped <= ir.dated)
AND i.warehouseFk = vWarehouseLanding
UNION ALL
SELECT b.itemFk,
vWarehouseLanding,
t.landed,
b.quantity
FROM buy b
JOIN entry e ON b.entryFk = e.id
JOIN travel t ON t.id = e.travelFk
JOIN tItemRangeLive ir ON ir.itemFk = b.itemFk
WHERE NOT e.isExcludedFromAvailable
AND b.quantity <> 0
AND NOT e.isRaid
AND t.warehouseInFk = vWarehouseLanding
AND t.landed >= vDatedFrom
AND (ir.dated IS NULL OR t.landed <= ir.dated)
UNION ALL
SELECT i.itemFk, vWarehouseLanding, i.shipped, i.quantity
FROM itemEntryOut i
JOIN tItemRangeLive ir ON ir.itemFk = i.itemFk
WHERE i.shipped >= vDatedFrom
AND (ir.dated IS NULL OR i.shipped <= ir.dated)
AND i.warehouseOutFk = vWarehouseLanding
UNION ALL
SELECT r.item_id, vWarehouseLanding, r.shipment, -r.amount
FROM hedera.order_row r
JOIN hedera.`order` o ON o.id = r.order_id
JOIN tItemRangeLive ir ON ir.itemFk = r.item_id
WHERE r.shipment >= vDatedFrom
AND (ir.dated IS NULL OR r.shipment <= ir.dated)
AND r.warehouse_id = vWarehouseLanding
AND r.created >= vDatedReserve
AND NOT o.confirmed;
CALL item_getAtp(vDated);
CREATE OR REPLACE TEMPORARY TABLE tmp.availableTraslate
(PRIMARY KEY (item_id))
ENGINE = MEMORY
SELECT t.item_id, SUM(stock) available
FROM (
SELECT ti.itemFk item_id, stock
FROM tmp.itemList ti
JOIN tItemRange ir ON ir.itemFk = ti.itemFk
UNION ALL
SELECT itemFk, quantity
FROM tmp.itemAtp
) t
GROUP BY t.item_id
HAVING available <> 0;
DROP TEMPORARY TABLE tmp.itemList, tItemRange, tItemRangeLive;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `balanceNestTree_addChild` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `balanceNestTree_addChild`(
vSelf INT,
vName VARCHAR(45)
)
BEGIN
/**
* Agrega un nuevo nodo hijo a un nodo existente dentro de la estructura
* de árbol de vn.balanceNestTree.
*
* @param vSelf Identificador del nodo
* @param vName Nombre del nuevo nodo hijo
*/
DECLARE vTable VARCHAR(45) DEFAULT util.quoteIdentifier('balanceNestTree');
DECLARE vLeft INT;
CREATE OR REPLACE TEMPORARY TABLE tAux
SELECT 0 lft;
EXECUTE IMMEDIATE CONCAT(
'UPDATE tAux
SET lft = (SELECT lft
FROM ', vTable,
' WHERE id = ?)')
USING vSelf;
SELECT lft INTO vLeft FROM tAux;
EXECUTE IMMEDIATE CONCAT(
'UPDATE ', vTable, '
SET rgt = rgt + 2
WHERE rgt > ?
ORDER BY rgt DESC')
USING vLeft;
EXECUTE IMMEDIATE CONCAT(
'UPDATE ', vTable, '
SET lft = lft + 2
WHERE lft > ?
ORDER BY lft DESC')
USING vLeft;
EXECUTE IMMEDIATE CONCAT(
'INSERT INTO ', vTable, ' (name, lft, rgt)
VALUES(?, ? + 1, ? + 2)')
USING vName,
vLeft,
vLeft;
DROP TEMPORARY TABLE tAux;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `balanceNestTree_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `balanceNestTree_delete`(
vSelf INT
)
BEGIN
/**
* Elimina un nodo dentro de la estructura de árbol de vn.balanceNestTree.
*
* @param vSelf Identificador del nodo
*/
DECLARE vTable VARCHAR(45) DEFAULT util.quoteIdentifier('balanceNestTree');
DECLARE vRight INT;
DECLARE vLeft INT;
DECLARE vWidth INT;
CREATE OR REPLACE TEMPORARY TABLE tAux
SELECT 0 rgt, 0 lft, 0 wdt;
EXECUTE IMMEDIATE CONCAT(
'UPDATE tAux a
JOIN ', vTable, ' t
SET a.rgt = t.rgt,
a.lft = t.lft,
a.wdt = t.rgt - t.lft + 1
WHERE t.id = ?')
USING vSelf;
SELECT rgt, lft, wdt
INTO vRight, vLeft, vWidth
FROM tAux;
EXECUTE IMMEDIATE CONCAT(
'DELETE FROM ', vTable,
' WHERE lft BETWEEN ? AND ?')
USING vLeft, vRight;
EXECUTE IMMEDIATE CONCAT(
'UPDATE ', vTable,
' SET rgt = rgt - ?
WHERE rgt > ?
ORDER BY rgt')
USING vWidth,vRight;
EXECUTE IMMEDIATE CONCAT(
'UPDATE ', vTable,
' SET lft = lft - ?
WHERE lft > ?
ORDER BY lft')
USING vWidth, vRight;
DROP TEMPORARY TABLE tAux;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `balanceNestTree_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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `balanceNestTree_move`(
vSelf INT,
vFather INT
)
BEGIN
/**
* Mueve un nodo dentro de la estructura de árbol de vn.balanceNestTree.
*
* @param vSelf Identificador del nodo
* @param vFather Identificador del nuevo padre del nodo
*/
DECLARE vTable VARCHAR(45) DEFAULT util.quoteIdentifier('balanceNestTree');
DECLARE vRight INT;
DECLARE vLeft INT;
DECLARE vWidth INT;
DECLARE vFatherRight INT;
DECLARE vFatherLeft INT;
DECLARE vGap INT;
CREATE OR REPLACE TEMPORARY TABLE tAux
SELECT 0 rgt, 0 lft, 0 wdt, 0 frg, 0 flf;
-- Averiguamos el ancho de la rama
EXECUTE IMMEDIATE CONCAT(
'UPDATE tAux a
JOIN ', vTable, ' t
SET a.wdt = t.rgt - t.lft + 1
WHERE t.id = ?')
USING vSelf;
-- Averiguamos la posicion del nuevo padre
EXECUTE IMMEDIATE CONCAT(
'UPDATE tAux a
JOIN ', vTable, ' t
SET a.frg = t.rgt,
a.flf = t.lft
WHERE t.id = ?')
USING vFather;
SELECT wdt, frg, flf
INTO vWidth, vFatherRight, vFatherLeft
FROM tAux;
-- 1º Incrementamos los valores de todos los nodos a la derecha
-- del punto de inserción (vFatherRight) , para hacer sitio
EXECUTE IMMEDIATE CONCAT(
'UPDATE ', vTable,
'SET rgt = rgt + ?
WHERE rgt >= ?
ORDER BY rgt DESC')
USING vWidth,
vFatherRight;
EXECUTE IMMEDIATE CONCAT(
'UPDATE ', vTable,
'SET lft = lft + ?
WHERE lft >= ?
ORDER BY lft DESC')
USING vWidth,
vFatherRight;
-- Es preciso recalcular los valores del nodo en el
-- caso de que estuviera a la derecha del nuevo padre
EXECUTE IMMEDIATE CONCAT(
'UPDATE tAux a
JOIN ', vTable, ' t
SET a.rgt = t.rgt,
a.lft = t.lft
WHERE t.id = ?')
USING vSelf;
SELECT lft, rgt, frg - lft
INTO vLeft, vRight, vGap
FROM tAux;
-- 2º Incrementamos el valor de todos los nodos a
-- trasladar hasta alcanzar su nueva posicion
EXECUTE IMMEDIATE CONCAT(
'UPDATE ', vTable,
'SET lft = lft + ?
WHERE lft BETWEEN ? AND ?
ORDER BY lft DESC')
USING vGap,
vLeft,
vRight;
EXECUTE IMMEDIATE CONCAT(
'UPDATE ', vTable,
'SET rgt = rgt + ?
WHERE rgt BETWEEN ? AND ?
ORDER BY rgt DESC')
USING vGap,
vLeft,
vRight;
-- 3º Restaremos a todos los nodos resultantes, a la derecha
-- de la posicion arrancada el ancho de la rama escindida
EXECUTE IMMEDIATE CONCAT(
'UPDATE ', vTable,
'SET lft = lft - ?
WHERE lft > ?
ORDER BY lft')
USING vWidth,
vLeft;
EXECUTE IMMEDIATE CONCAT(
'UPDATE ', vTable,
'SET rgt = rgt - ?
WHERE rgt > ?
ORDER BY rgt')
USING vWidth,
vRight;
DROP TEMPORARY TABLE tAux;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `balance_create` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `balance_create`(
vStartingMonth INT,
vEndingMonth INT,
vCompany INT,
vIsConsolidated BOOLEAN,
vInterGroupSalesIncluded BOOLEAN
)
BEGIN
/**
* Crea un balance financiero para una empresa durante
* un período de tiempo determinado.
*
* @param vStartingMonth Mes de inicio del período
* @param vEndingMonth Mes de finalización del período
* @param vCompany Identificador de la empresa
* @param vIsConsolidated Indica si se trata de un balance consolidado
* @param vInterGroupSalesIncluded Indica si se incluyen las ventas del grupo
*/
DECLARE intGAP INT DEFAULT 7;
DECLARE vYears INT DEFAULT 2;
DECLARE vYear TEXT;
DECLARE vOneYearAgo TEXT;
DECLARE vTwoYearsAgo TEXT;
DECLARE vQuery TEXT;
DECLARE vConsolidatedGroup INT;
DECLARE vStartingDate DATE DEFAULT '2020-01-01';
DECLARE vCurYear INT DEFAULT YEAR(util.VN_CURDATE());
DECLARE vStartingYear INT DEFAULT vCurYear - 2;
DECLARE vTable TEXT;
SET vTable = util.quoteIdentifier('balanceNestTree');
SET vYear = util.quoteIdentifier(vCurYear);
SET vOneYearAgo = util.quoteIdentifier(vCurYear-1);
SET vTwoYearsAgo = util.quoteIdentifier(vCurYear-2);
-- Solicitamos la tabla tmp.nest, como base para el balance.
DROP TEMPORARY TABLE IF EXISTS tmp.nest;
EXECUTE IMMEDIATE CONCAT(
'CREATE TEMPORARY TABLE tmp.nest
SELECT node.id
,CONCAT( REPEAT(REPEAT(" ",?), COUNT(parent.id) - 1),
node.name) name,
node.lft,
node.rgt,
COUNT(parent.id) - 1 depth,
CAST((node.rgt - node.lft - 1) / 2 AS DECIMAL) sons
FROM ', vTable, ' node,
', vTable, ' parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY node.id
ORDER BY node.lft')
USING intGAP;
CREATE OR REPLACE TEMPORARY TABLE tmp.balance
SELECT * FROM tmp.nest;
SELECT companyGroupFk INTO vConsolidatedGroup
FROM company
WHERE id = vCompany;
CREATE OR REPLACE TEMPORARY TABLE tCompanyReceiving
SELECT id companyFk
FROM company
WHERE id = vCompany
OR companyGroupFk = IF(vIsConsolidated, vConsolidatedGroup, NULL);
CREATE OR REPLACE TEMPORARY TABLE tCompanyIssuing
SELECT id companyFk
FROM supplier p;
IF NOT vInterGroupSalesIncluded THEN
DELETE ci
FROM tCompanyIssuing ci
JOIN company e on e.id = ci.companyFk
WHERE e.companyGroupFk = vConsolidatedGroup;
END IF;
-- Se calculan las facturas que intervienen,
-- para luego poder servir el desglose desde aqui.
CREATE OR REPLACE TEMPORARY TABLE tmp.balanceDetail
SELECT cr.companyFk receivingId,
ci.companyFk issuingId,
YEAR(IFNULL(r.bookEntried,IFNULL(r.booked, r.issued))) `year`,
MONTH(IFNULL(r.bookEntried,IFNULL(r.booked, r.issued))) `month`,
expenseFk,
SUM(taxableBase) amount
FROM invoiceIn r
JOIN invoiceInTax ri on ri.invoiceInFk = r.id
JOIN tCompanyReceiving cr on cr.companyFk = r.companyFk
JOIN tCompanyIssuing ci ON ci.companyFk = r.supplierFk
WHERE COALESCE(r.bookEntried, r.booked, r.issued) >= vStartingDate
AND r.isBooked
GROUP BY expenseFk, `year`, `month`, ci.companyFk, cr.companyFk;
INSERT INTO tmp.balanceDetail(
receivingId,
issuingId,
`year`,
`month`,
expenseFk,
amount)
SELECT em.companyFk,
em.companyFk,
`year`,
`month`,
expenseFk,
SUM(em.amount)
FROM expenseManual em
JOIN tCompanyReceiving er ON er.companyFk = em.companyFk
WHERE `year` >= vStartingYear
AND `month` BETWEEN vStartingMonth AND vEndingMonth
GROUP BY expenseFk, `year`, `month`, em.companyFk;
DELETE FROM tmp.balanceDetail
WHERE `month` < vStartingMonth
OR `month` > vEndingMonth;
-- Ahora el balance
EXECUTE IMMEDIATE CONCAT(
'ALTER TABLE tmp.balance
ADD COLUMN ', vTwoYearsAgo ,' INT(10) NULL ,
ADD COLUMN ', vOneYearAgo ,' INT(10) NULL ,
ADD COLUMN ', vYear,' INT(10) NULL ,
ADD COLUMN expenseFk VARCHAR(10) NULL,
ADD COLUMN expenseName VARCHAR(45) NULL');
-- Añadimos los gastos, para facilitar el formulario
UPDATE tmp.balance b
JOIN balanceNestTree bnt on bnt.id = b.id
JOIN expense e ON e.id = bnt.expenseFk COLLATE utf8_general_ci
SET b.expenseFk = e.id COLLATE utf8_general_ci,
b.expenseName = e.name COLLATE utf8_general_ci ;
-- Rellenamos los valores de primer nivel, los que corresponden
-- a los gastos simples.
WHILE vYears >= 0 DO
SET vQuery = CONCAT(
'UPDATE tmp.balance b
JOIN (
SELECT expenseFk, SUM(amount) amount
FROM tmp.balanceDetail
WHERE year = ?
GROUP BY expenseFk
) sub on sub.expenseFk = b.expenseFk COLLATE utf8_general_ci
SET ', util.quoteIdentifier(vCurYear - vYears), ' = - amount');
EXECUTE IMMEDIATE vQuery
USING vCurYear - vYears;
SET vYears = vYears - 1;
END WHILE;
-- Añadimos las ventas.
EXECUTE IMMEDIATE CONCAT(
'UPDATE tmp.balance b
JOIN (
SELECT SUM(IF(year = ?, venta, 0)) y2,
SUM(IF(year = ?, venta, 0)) y1,
SUM(IF(year = ?, venta, 0)) y0,
c.Gasto
FROM bs.ventas_contables c
JOIN tCompanyReceiving cr ON cr.companyFk = c.empresa_id
WHERE month BETWEEN ? AND ?
GROUP BY c.Gasto
) sub ON sub.gasto = b.expenseFk COLLATE utf8_general_ci
SET b.', vTwoYearsAgo, '= IFNULL(b.', vTwoYearsAgo, ', 0) + sub.y2,
b.', vOneYearAgo, '= IFNULL(b.', vOneYearAgo, ', 0) + sub.y1,
b.', vYear, '= IFNULL(b.', vYear, ', 0) + sub.y0')
USING vCurYear-2,
vCurYear-1,
vCurYear,
vStartingMonth,
vEndingMonth;
-- Ventas intra grupo.
IF NOT vInterGroupSalesIncluded THEN
SELECT lft, rgt INTO @groupLft, @groupRgt
FROM tmp.balance b
WHERE TRIM(b.`name`) = 'Grupo';
DELETE
FROM tmp.balance
WHERE lft BETWEEN @groupLft AND @groupRgt;
END IF;
-- Rellenamos el valor de los padres con la suma de los hijos.
CREATE OR REPLACE TEMPORARY TABLE tmp.balance_aux
SELECT * FROM tmp.balance;
EXECUTE IMMEDIATE
CONCAT('UPDATE tmp.balance b
JOIN (
SELECT b1.id,
b1.name,
SUM(b2.', vYear,') thisYear,
SUM(b2.', vOneYearAgo,') oneYearAgo,
SUM(b2.', vTwoYearsAgo,') twoYearsAgo
FROM tmp.nest b1
JOIN tmp.balance_aux b2 on b2.lft BETWEEN b1.lft and b1.rgt
GROUP BY b1.id
)sub ON sub.id = b.id
SET b.', vYear, ' = thisYear,
b.', vOneYearAgo, ' = oneYearAgo,
b.', vTwoYearsAgo, ' = twoYearsAgo');
SELECT *, CONCAT('',IFNULL(expenseFk,'')) newgasto
FROM tmp.balance;
DROP TEMPORARY TABLE IF EXISTS tCompanyReceiving, tCompanyIssuing;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `bankEntity_checkBic` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `bankEntity_checkBic`(vBic VARCHAR(255))
BEGIN
/**
* If the bic length is Incorrect throw exception
*
* @param vBic bic code
*/
DECLARE vConfigBicLenght INT;
SELECT bicLength INTO vConfigBicLenght
FROM vn.bankEntityConfig bec;
IF LENGTH(vBic) <> vConfigBicLenght THEN
CALL util.throw(CONCAT('bic must be of length ', vConfigBicLenght ));
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `bankPolicy_notifyExpired` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `bankPolicy_notifyExpired`()
BEGIN
/**
*
* Manda correo cuando caduca un seguro
* de los leasing
*
*/
INSERT INTO mail (receiver,replyTo,subject,body)
SELECT 'administracion@verdnatura.es' receiver,
'noreply@verdnatura.es' replyTo,
CONCAT('El seguro de la poliza ',a.id,' ',a.bank,' ha finalizado.') subject,
CONCAT('El seguro de la poliza ',a.id,' ',a.bank,' ha finalizado.') body
FROM bankPolicy bp
LEFT JOIN supplier s ON s.id = bp.supplierFk
LEFT JOIN accounting a ON a.id = bp.accountingFk
WHERE bp.insuranceExpired = util.VN_CURDATE();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buyUltimate`(vWarehouseFk SMALLINT, vDated DATE)
BEGIN
/**
* Calcula las últimas compras realizadas hasta una fecha
*
* @param vWarehouseFk Id del almacén
* @param vDated 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, landing
FROM cache.last_buy
WHERE warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL;
CALL buyUltimateFromInterval(vWarehouseFk, util.VN_CURDATE(), vDated);
REPLACE INTO tmp.buyUltimate
SELECT itemFk, buyFk, warehouseFk, landed landing
FROM tmp.buyUltimateFromInterval
WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
AND landed <= vDated
AND NOT isIgnored;
INSERT IGNORE INTO tmp.buyUltimate
SELECT itemFk, buyFk, warehouseFk, landed landing
FROM tmp.buyUltimateFromInterval
WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
AND landed > vDated
ORDER BY isIgnored = FALSE 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 si es NULL se actualizan todos
* @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;
-- Item
DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimateFromInterval;
CREATE TEMPORARY TABLE tmp.buyUltimateFromInterval
(PRIMARY KEY (itemFk, warehouseFk), INDEX(buyFk), INDEX(landed), INDEX(warehouseFk), INDEX(itemFk))
ENGINE = MEMORY
SELECT itemFk,
warehouseFk,
buyFk,
MAX(landed) landed,
isIgnored
FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
b.isIgnored
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
ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk, warehouseFk;
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT
b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed > vEnded
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND b.price2 > 0
AND NOT b.isIgnored
GROUP BY itemFk, warehouseInFk;
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT
b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
b.isIgnored
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.quantity = 0
GROUP BY itemFk, warehouseInFk;
-- ItemOriginal
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT itemFk,
warehouseFk,
buyFk,
MAX(landed) landed,
isIgnored
FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
itemOriginalFk,
b.isIgnored
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
AND b.quantity > 0
AND itemOriginalFk
ORDER BY t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemOriginalFk, warehouseFk;
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT
b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
b.isIgnored
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed > vEnded
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND b.price2 > 0
AND NOT b.isIgnored
AND itemOriginalFk
GROUP BY itemOriginalFk, warehouseInFk;
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT
b.itemFk,
t.warehouseInFk warehouseFk,
b.id buyFk,
t.landed,
b.isIgnored
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.quantity = 0
AND itemOriginalFk
GROUP BY itemOriginalFk, 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_afterUpsert` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 vPackingOut DECIMAL(10,2);
DECLARE vWarehouse INT;
DECLARE vStandardFlowerBox INT;
DECLARE vWarehouseOut INT;
DECLARE vIsMerchandise BOOL;
DECLARE vIsFeedStock BOOL;
DECLARE vWeight DECIMAL(10,2);
DECLARE vPacking INT;
SELECT b.entryFk,
b.itemFk,
i.packingOut,
ic.merchandise,
vc.standardFlowerBox,
b.weight,
b.packing
INTO
vEntryFk,
vItemFk,
vPackingOut,
vIsMerchandise,
vStandardFlowerBox,
vWeight,
vPacking
FROM buy b
LEFT JOIN item i ON i.id = b.itemFk
LEFT JOIN itemType it ON it.id = i.typeFk
LEFT JOIN itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN packaging p ON p.id = b.packagingFk AND NOT p.isBox
JOIN volumeConfig vc ON TRUE
WHERE b.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;
IF vIsMerchandise THEN
REPLACE itemCost SET
itemFk = vItemFk,
warehouseFk = vWarehouse,
cm3 = buy_getUnitVolume(vSelf),
cm3Delivery = IFNULL((vStandardFlowerBox * 1000) / vPackingOut, buy_getUnitVolume(vSelf));
IF vWeight AND vPacking THEN
UPDATE itemCost SET
grams = vWeight * 1000 / vPacking
WHERE itemFk = vItemFk
AND warehouseFk = vWarehouse;
END IF;
END IF;
SELECT isFeedStock INTO vIsFeedStock
FROM warehouse WHERE id = vWarehouseOut;
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;
END IF;
CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck
SELECT vSelf id;
CALL buy_checkItem();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_checkItem` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_checkItem`()
BEGIN
/**
* Checks if the item has weightByPiece or size null on any buy.
*
* @param tmp.buysToCheck(id as INT).
*/
DECLARE hasVolumetricAgency INT;
SELECT a.hasWeightVolumetric INTO hasVolumetricAgency
FROM entry e
JOIN travel t ON t.id = e.travelFk
JOIN agencyMode a ON a.id = t.agencyModeFk
JOIN buy b ON b.entryFk = e.id
JOIN item i ON i.id = b.itemFk
JOIN tmp.buysToCheck bt ON bt.id = b.id
WHERE (i.weightByPiece IS NULL OR i.`size` IS NULL)
AND a.hasWeightVolumetric
LIMIT 1;
DROP TEMPORARY TABLE tmp.buysToCheck;
IF hasVolumetricAgency THEN
CALL util.throw('Item lacks size/weight in purchase line at agency');
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_getSplit` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getSplit`(vSelf INT, vDated DATE)
BEGIN
/**
* Devuelve tantos registros como etiquetas se necesitan para cada uno de los cubos o cajas de
* las ventas correspondientes a la compra que se pasa como parámetro, en los almacenes que tienen
* habilitada la venta de productos con stock virtual, aunque los productos pueden ser de cualquier tipo.
*
* @param vSelf Identificador de vn.buy
* @param vDated Fecha de preparación de las ventas que queremos etiquetar
*/
DECLARE vItemFk INT;
DECLARE vPacking INT;
DECLARE vRemaining INT;
DECLARE vLabels INT;
DECLARE vSaleFk INT;
DECLARE vAmount INT;
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vCounter INT DEFAULT 1;
DECLARE cur CURSOR FOR
SELECT s.id, s.quantity - IFNULL(l.stem, 0)
FROM vn.sale s
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.warehouse w ON w.id = t.warehouseFk
LEFT JOIN vn.saleLabel l ON l.saleFk = s.id
WHERE s.itemFk = vItemFk
AND t.shipped >= vDated
AND w.isLogiflora
AND IFNULL(l.stem, 0) < s.quantity
ORDER BY s.quantity = vRemaining DESC
LOCK IN SHARE MODE;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
-- Obtiene los datos de la compra
SELECT itemFk, packing, quantity
INTO vItemFk, vPacking, vRemaining
FROM vn.buy WHERE id = vSelf;
-- Crea splits de los tickets
CREATE OR REPLACE TEMPORARY TABLE tmp.split
(
id INT,
labels INT DEFAULT 0,
counter INT DEFAULT 0
)
ENGINE = MEMORY;
OPEN cur;
l: LOOP
SET vDone = FALSE;
FETCH cur INTO vSaleFk, vAmount;
IF vDone OR vRemaining = 0 THEN
LEAVE l;
END IF;
SET vAmount = LEAST(vAmount, vRemaining);
SET vRemaining = vRemaining - vAmount;
SET vLabels = vAmount DIV vPacking;
-- Se inserta una linea por cada etiqueta
SET vCounter = 1;
WHILE vLabels >= vCounter DO
INSERT INTO tmp.split
SET
id = vSaleFk,
labels = vLabels,
counter = vCounter;
SET vCounter = vCounter + 1;
END WHILE;
INSERT INTO vn.saleLabel
SET
saleFk = vSaleFk,
stem = vAmount,
label = vLabels
ON DUPLICATE KEY UPDATE
stem = stem + VALUES(stem),
label = label + VALUES(label);
END LOOP;
CLOSE cur;
-- Devuelve los splits creados
SELECT CONCAT(sp.counter,'/',sp.labels) labels,
COALESCE(sfc.nickname, sfa.nickname, a.nickname) destination,
s.itemFk,
i.longName,
i.`size`,
vn.ticketSplitCounter(t.id) counter,
IF(sfa.id OR sfc.id,
a.nickname,
CONCAT(a.id, ' ', p.`name`,' (', c.`code`,')')) destination2
FROM tmp.split sp
JOIN vn.sale s ON sp.id = s.id
JOIN vn.item i ON i.id = s.itemFk
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.address a ON a.id = t.addressFk
JOIN vn.province p ON p.id = a.provinceFk
JOIN vn.country c ON c.id = p.countryFk
LEFT JOIN vn.splitFilter sfa ON sfa.autonomyFk = p.autonomyFk
LEFT JOIN vn.splitFilter sfc ON sfc.clientFk = t.clientFk;
-- Limpia y confirma cambios
DROP TEMPORARY TABLE
tmp.split;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE 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 = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getVolume`()
BEGIN
/**
* Cálculo de volumen en líneas de compra
* @table tmp.buy(buyFk)
*/
SELECT t.name Temp,
CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) *
item_getVolume(b.itemFk, b.packagingFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) carros ,
CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) *
item_getVolume(b.itemFk, b.packagingFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) espais
FROM buy b
JOIN tmp.buy tb ON tb.buyFk = b.id
JOIN volumeConfig vc
JOIN item i ON i.id = b.itemFk
JOIN itemType it ON it.id = i.typeFk
LEFT JOIN temperature t ON t.code = it.temperatureFk
GROUP BY Temp;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_getVolumeByAgency` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getVolumeByAgency`(vDated DATE, vAgencyFk INT)
BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.buy;
CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY;
INSERT INTO tmp.buy
SELECT b.id
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed = vDated
AND t.agencyModeFk IN (0, vAgencyFk);
CALL buy_getVolume();
DROP TEMPORARY TABLE tmp.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_getVolumeByEntry` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getVolumeByEntry`(vEntryFk INT)
BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.buy;
CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY;
INSERT INTO tmp.buy
SELECT b.id
FROM buy b
JOIN entry e ON e.id = b.entryFk
WHERE e.id = vEntryFk;
CALL buy_getVolume();
DROP TEMPORARY TABLE tmp.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_recalcPrices` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_recalcPrices`()
BEGIN
/**
* Recalcula los precios para las compras insertadas en tmp.buyRecalc
*
* @param tmp.buyRecalc (id)
*/
DECLARE vLanded DATE;
DECLARE vWarehouseFk INT;
DECLARE vHasNotPrice BOOL;
DECLARE vBuyingValue DECIMAL(10,4);
DECLARE vPackagingFk VARCHAR(10);
DECLARE vIsWarehouseFloramondo BOOL;
SELECT t.landed, t.warehouseInFk, (w.`name` = 'Floramondo')
INTO vLanded, vWarehouseFk, vIsWarehouseFloramondo
FROM tmp.buyRecalc br
JOIN buy b ON b.id = br.id
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
JOIN warehouse w ON w.id = t.warehouseInFk
LIMIT 1;
CALL rate_getPrices(vLanded, vWarehouseFk);
UPDATE buy b
JOIN tmp.buyRecalc br ON br.id = b.id AND (@buyId := b.id)
LEFT JOIN packaging p ON p.id = b.packagingFk
JOIN item i ON i.id = b.itemFk
JOIN entry e ON e.id = b.entryFk
JOIN itemType it ON it.id = i.typeFk
JOIN travel tr ON tr.id = e.travelFk
JOIN agencyMode am ON am.id = tr.agencyModeFk
JOIN tmp.rate r
JOIN volumeConfig vc
SET b.freightValue = @PF:= IFNULL(((am.m3 * @m3:= item_getVolume(b.itemFk, b.packagingFk) / 1000000)
/ b.packing) * IF(am.hasWeightVolumetric, GREATEST(b.weight / @m3 / vc.aerealVolumetricDensity, 1), 1), 0),
b.comissionValue = @CF:= ROUND(IFNULL(e.commission * b.buyingValue / 100, 0), 3),
b.packageValue = @EF:= IF(vIsWarehouseFloramondo, 0, IFNULL(ROUND(IF(p.isPackageReturnable, p.returnCost / b.packing , p.`value` / b.packing), 3),0)),
b.price3 = @t3:= IF(r.rate3 = 0, b.buyingValue,ROUND((b.buyingValue + @CF + @EF + @PF) / ((100 - r.rate3 - it.promo ) /100) ,2)), -- He añadido que el coste sea igual a tarifa3 si t3 = 0
b.price2 = @t2:= round(@t3 * (1 + ((r.rate2 - r.rate3)/100)),2),
b.price2 = @t2:= IF(@t2 <= @t3,@t3 , @t2);
SELECT (b.buyingValue = b.price2), b.buyingValue, b.packagingFk
INTO vHasNotPrice, vBuyingValue, vPackagingFk
FROM vn.buy b
WHERE b.id = @buyId AND b.buyingValue <> 0.01;
DROP TEMPORARY TABLE tmp.rate;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_recalcPricesByAwb` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_recalcPricesByAwb`(IN awbFk varchar(18))
BEGIN
/**
* inserta en tmp.buyRecalc las compras de un awb
*
* @param awbFk
*/
DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc;
CREATE TEMPORARY TABLE tmp.buyRecalc
SELECT b.id
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
JOIN awb a ON a.id = t.awbFk
WHERE a.code = awbFk;
CALL buy_recalcPrices();
DROP TEMPORARY TABLE tmp.buyRecalc;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_recalcPricesByBuy` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_recalcPricesByBuy`(
vBuyFk INT(11)
)
BEGIN
/**
* Recalcula los precios de una compra
*
* @param vBuyFk
*/
DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc;
CREATE TEMPORARY TABLE tmp.buyRecalc
SELECT vBuyFk id;
CALL buy_recalcPrices();
DROP TEMPORARY TABLE tmp.buyRecalc;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_recalcPricesByEntry` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_recalcPricesByEntry`(
vEntryFk INT(11)
)
BEGIN
/**
* Recalcula los precios de una entrada
*
* @param vEntryFk
*/
DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc;
CREATE TEMPORARY TABLE tmp.buyRecalc
SELECT b.id
FROM buy b
WHERE b.entryFk = vEntryFk;
CALL buy_recalcPrices();
DROP TEMPORARY TABLE tmp.buyRecalc;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_scan` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_scan`(vBarcode VARCHAR(512))
BEGIN
/**
* Busca compras a partir de un código de barras de subasta, las marca como
* escaneadas y como etiquetas impresas y las devuelve.
*
* @param vBarcode Código de compra de una etiqueta de subasta
* @select (buy, do_photo) Identificadores de compra escaneados
*/
CALL edi.ekt_scan(vBarcode);
DROP TEMPORARY TABLE IF EXISTS tBuy;
CREATE TEMPORARY TABLE tBuy
SELECT id buyFk
FROM vn.buy b
LIMIT 0;
INSERT INTO tBuy(buyFk)
SELECT b.id
FROM buy b
JOIN tmp.ekt t ON t.ektFk = b.ektFk
JOIN vn.entry en ON en.id = b.entryFk
JOIN vn.travel tr ON tr.id = en.travelFk
JOIN vn.warehouse w ON w.id = tr.warehouseInFk
JOIN vn.country c ON c.id = w.countryFk AND c.code = 'NL';
SELECT b.id buy, i.doPhoto do_photo, b.stickers - CAST(b.printedStickers AS INT) stickersToPrint
FROM tBuy tb
JOIN vn.buy b ON tb.buyFk = b.id
JOIN vn.item i ON i.id = b.itemFk;
UPDATE vn.buy b
JOIN tBuy tb ON tb.buyFk = b.id
SET b.printedStickers = b.stickers;
DROP TEMPORARY TABLE tmp.ekt, tBuy;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_updateGrouping` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_updateGrouping`(vWarehouseFk INT, vItemFk INT, vGrouping INT)
BEGIN
/**
* Actualiza el grouping de las últimas compras de un artículo
*
* @param vWarehouseFk Id del almacén
* @param vItemFk Id del Artículo
* @param vGrouping Cantidad de grouping
*/
CALL vn.buyUltimate(vWarehouseFk, util.VN_CURDATE());
UPDATE vn.buy b
JOIN tmp.buyUltimate bu ON b.id = bu.buyFk
SET b.`grouping` = vGrouping
WHERE bu.warehouseFk = vWarehouseFk
AND bu.itemFk = vItemFk;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `buy_updatePacking` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_updatePacking`(vWarehouseFk INT, vItemFk INT, vPacking INT)
BEGIN
/**
* Actualiza packing
*
* @param vWarehouseFk warehouse del item
* @param vItemFk id del item
* @param vPacking packing a actualizar
*/
CALL buyUltimate(vWarehouseFk, util.VN_CURDATE());
UPDATE buy b
JOIN tmp.buyUltimate bu ON b.id = bu.buyFk
SET b.packing = vPacking
WHERE bu.warehouseFk = vWarehouseFk
AND bu.itemFk = vItemFk;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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, TRUE);
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_calculate`(
vLanded DATE,
vAddressFk INT,
vAgencyModeFk INT,
vShowExpiredZones BOOLEAN)
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
*/
DECLARE vAvailableCalc INT;
DECLARE vAvailableNoRaidsCalc INT;
DECLARE vShipped DATE;
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;
CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, vShowExpiredZones);
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', -- este campo parece obsoleto
`zoneFk` int(11) NOT NULL,
KEY `itemFk` (`itemFk`),
KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH
) ENGINE=MEMORY DEFAULT CHARSET=utf8;
CALL catalog_componentPrepare();
DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem;
CREATE TEMPORARY TABLE tmp.ticketCalculateItem(
itemFk INT(11) NOT NULL,
available INT(11),
producer VARCHAR(50),
item VARCHAR(50),
size INT(10) UNSIGNED,
stems INT(11),
category VARCHAR(3),
inkFk VARCHAR(3),
image VARCHAR(50),
origin VARCHAR(3),
price DECIMAL(10,2),
priceKg DECIMAL(10,2),
`grouping` INT(10) UNSIGNED,
PRIMARY KEY `itemFk` (`itemFk`)
) 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 `cache`.availableNoRaids_refresh (vAvailableNoRaidsCalc, FALSE, vWarehouseFk, vShipped);
CALL vn.buyUltimate(vWarehouseFk, vShipped);
INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk, zoneFk)
SELECT vWarehouseFk,
a.item_id,
IFNULL(a.available, 0),
bu.buyFk,
vZoneFk
FROM `cache`.available a
LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id
AND anr.calc_id = vAvailableNoRaidsCalc
JOIN tmp.item i ON i.itemFk = a.item_id
JOIN vn.item it ON it.id = i.itemFk
JOIN vn.`zone` z ON z.id = vZoneFk
LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id
LEFT JOIN edi.supplyResponse sr ON sr.ID = it.supplyResponseFk
LEFT JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID
LEFT JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID
LEFT JOIN (SELECT isVNHSupplier, isEarlyBird, TRUE AS itemAllowed
FROM vn.addressFilter af
JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed
FROM vn.address ad
JOIN vn.province p ON p.id = ad.provinceFk
WHERE ad.id = vAddressFk
) sub2 ON sub2.provinceFk <=> IFNULL(af.provinceFk, sub2.provinceFk)
AND sub2.countryFk <=> IFNULL(af.countryFk, sub2.countryFk)
AND sub2.isLogifloraAllowed <=> IFNULL(af.isLogifloraAllowed, sub2.isLogifloraAllowed)
WHERE vWarehouseFk = af.warehouseFk
AND (vShipped < af.beforeDated
OR ISNULL(af.beforeDated)
OR vShipped > af.afterDated
OR ISNULL(af.afterDated))
) sub ON sub.isVNHSupplier = v.isVNHSupplier
AND (sub.isEarlyBird = mp.isEarlyBird OR ISNULL(sub.isEarlyBird))
JOIN vn.agencyMode am ON am.id = vAgencyModeFk
JOIN vn.agency ag ON ag.id = am.agencyFk
JOIN vn.itemType itt ON itt.id = it.typeFk
JOIN vn.itemCategory itc on itc.id = itt.categoryFk
JOIN vn.address ad ON ad.id = vAddressFk
LEFT JOIN vn.clientItemType cit
ON cit.clientFk = ad.clientFk
AND cit.itemTypeFk = itt.id
LEFT JOIN vn.zoneItemType zit
ON zit.zoneFk = vZoneFk
AND zit.itemTypeFk = itt.id
LEFT JOIN vn.agencyModeItemType ait
ON ait.agencyModeFk = vAgencyModeFk
AND ait.itemTypeFk = itt.id
WHERE a.calc_id = vAvailableCalc
AND a.available > 0
AND (sub.itemAllowed OR NOT it.isFloramondo OR anr.available > 0)
AND (ag.isAnyVolumeAllowed OR NOT itt.isUnconventionalSize)
AND (itc.isReclining OR it.`size` IS NULL OR it.`size` < z.itemMaxSize OR z.itemMaxSize IS NULL)
AND cit.id IS NULL
AND zit.id IS NULL
AND ait.id IS NULL;
DROP TEMPORARY TABLE tmp.buyUltimate;
CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk);
INSERT INTO tmp.ticketCalculateItem (
itemFk,
available,
producer,
item,
size,
stems,
category,
inkFk,
image,
origin,
price,
priceKg,
`grouping`)
SELECT
tl.itemFk,
SUM(tl.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,
bl.`grouping`
FROM tmp.ticketLot tl
JOIN item i ON tl.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 price, itemFk, priceKg, MIN(`grouping`) `grouping`
FROM (
SELECT price, itemFk, priceKg, `grouping`
FROM tmp.ticketComponentPrice
WHERE warehouseFk = vWarehouseFk
ORDER BY (rate = 2) DESC, price
LIMIT 10000000000000000000
) sub
GROUP BY itemFk
) bl ON bl.itemFk = tl.itemFk
WHERE tl.zoneFk = vZoneFk AND tl.warehouseFk = vWarehouseFk
GROUP BY tl.itemFk
ON DUPLICATE KEY UPDATE available = available + VALUES(available);
END LOOP;
CLOSE cTravelTree;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentCalculate`(
vZoneFk INT,
vAddressFk INT,
vShipped DATE,
vWarehouseFk INT
)
BEGIN
/**
* Calcula los componentes de los articulos de tmp.ticketLot
*
* @param vZoneFk para calcular el transporte
* @param vAddressFk Consignatario
* @param vShipped dia de salida del pedido
* @param vWarehouseFk warehouse de salida del pedido
* @table tmp.ticketLot (warehouseFk, available, itemFk, buyFk, zoneFk)
* @table tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
*
* @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, `grouping`, price, priceKg)
*/
DECLARE vClientFk INT;
DECLARE vVNHWarehouseFk INT DEFAULT 7;
SELECT clientFk INTO vClientFK
FROM address
WHERE id = vAddressFk;
CREATE OR REPLACE TEMPORARY TABLE tSpecialPrice
(INDEX (itemFk))
ENGINE = MEMORY
SELECT * FROM (
SELECT *
FROM specialPrice
WHERE (clientFk = vClientFk OR clientFk IS NULL)
AND started <= vShipped
AND (ended >= vShipped OR ended IS NULL)
ORDER BY (clientFk = vClientFk) DESC, id DESC
LIMIT 10000000000000000000) t
GROUP BY itemFk;
CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentCalculate
(PRIMARY KEY (itemFk, warehouseFk))
ENGINE = MEMORY
SELECT tl.itemFk,
tl.warehouseFk,
tl.available,
IF(i.hasMinPrice, GREATEST(i.minPrice,IFNULL(pf.rate2, b.price2)),IFNULL(pf.rate2, b.price2)) rate2,
IF(i.hasMinPrice, GREATEST(i.minPrice,IFNULL(pf.rate3, b.price3)),IFNULL(pf.rate3, b.price3)) rate3,
IFNULL(pf.packing, GREATEST(b.grouping, b.packing)) packing,
IFNULL(pf.`grouping`, b.`grouping`) `grouping`,
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
JOIN itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN tSpecialPrice sp ON sp.itemFk = i.id
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 IN (pf.warehouseFk,0)
WHERE vShipped BETWEEN pf.started AND pf.ended
ORDER BY pf.itemFk, pf.warehouseFk DESC
LIMIT 10000000000000000000
) 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.merchandise
AND tl.zoneFk = vZoneFk
AND tl.warehouseFk = vWarehouseFk;
-- Coste
INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost)
SELECT tcc.warehouseFk,
tcc.itemFk,
c2.id,
b.buyingValue + b.freightValue + b.packageValue + b.comissionValue
FROM tmp.ticketComponentCalculate tcc
JOIN vn.component c2 ON c2.code = 'purchaseValue'
JOIN buy b ON b.id = tcc.buyFk;
-- Margen
INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost)
SELECT tcc.warehouseFk,
tcc.itemFk,
c2.id,
tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue
FROM tmp.ticketComponentCalculate tcc
JOIN vn.component c2 ON c2.code = 'margin'
JOIN buy b ON b.id = tcc.buyFk;
CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY
SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk
FROM tmp.ticketComponent tc
JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tc.itemFk AND tcc.warehouseFk = tc.warehouseFk
GROUP BY tc.itemFk, warehouseFk;
-- RECOBRO
INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
SELECT tcb.warehouseFk, tcb.itemFk, c2.id,
ROUND(tcb.base *
LEAST(
MAX(GREATEST(IFNULL(cr.priceIncreasing,0),
IFNULL(cr1.priceIncreasing,0),
IFNULL(cr2.priceIncreasing,0))
),
cc.maxPriceIncreasingRatio),
3)
FROM tmp.ticketComponentBase tcb
JOIN vn.component c2 ON c2.code = 'debtCollection'
JOIN vn.clientConfig cc
JOIN claimRatio cr ON cr.clientFk = vClientFk
LEFT JOIN clientYoke cy1 ON cy1.leftOx = cr.clientFk
LEFT JOIN claimRatio cr1 ON cr1.clientFk = cy1.rightOx
LEFT JOIN clientYoke cy2 ON cy2.rightOx = cr.clientFk
LEFT JOIN claimRatio cr2 ON cr2.clientFk = cy2.leftOx
WHERE GREATEST(
IFNULL(cr.priceIncreasing,0),
IFNULL(cr1.priceIncreasing,0),
IFNULL(cr2.priceIncreasing,0)) > 0.009
GROUP BY tcb.itemFk;
-- Mana auto
INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
SELECT tcb.warehouseFk,
tcb.itemFk,
c2.id,
ROUND(base * wm.pricesModifierRate, 3) manaAuto
FROM tmp.ticketComponentBase tcb
JOIN `client` c on c.id = vClientFk
JOIN workerMana wm ON c.salesPersonFk = wm.workerFk
JOIN vn.component c2 ON c2.code = 'autoMana'
WHERE wm.isPricesModifierActivated
HAVING manaAuto <> 0;
-- Precios especiales
INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
SELECT tcb.warehouseFk,
tcb.itemFk,
c2.id,
GREATEST(
IFNULL(ROUND(tcb.base * c2.tax, 4), 0),
IF(i.hasMinPrice, i.minPrice,0) - tcc.rate3
) cost
FROM tmp.ticketComponentBase tcb
JOIN vn.component c2 ON c2.code = 'lastUnitsDiscount'
JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk
LEFT JOIN tSpecialPrice sp ON sp.itemFk = tcc.itemFk
JOIN vn.item i ON i.id = tcb.itemFk
WHERE sp.value IS NULL
AND i.supplyResponseFk IS NULL;
-- Individual
INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
SELECT tcb.warehouseFk,
tcb.itemFk,
c2.id,
IFNULL(ROUND(tcb.base * c2.tax, 4), 0) cost
FROM tmp.ticketComponentBase tcb
JOIN vn.component c2 ON c2.code = 'individual'
JOIN vn.client c ON c.id = vClientFk
JOIN vn.businessType bt ON bt.code = c.businessTypeFk
WHERE bt.code = 'individual';
-- Venta por paquetes
INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost)
SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3
FROM tmp.ticketComponentCalculate tcc
JOIN vn.component c2 ON c2.code = 'salePerPackage'
JOIN buy b ON b.id = tcc.buyFk
LEFT JOIN tSpecialPrice sp ON sp.itemFk = tcc.itemFk
WHERE sp.value IS NULL;
CREATE OR REPLACE TEMPORARY TABLE tmp.`zone` (INDEX (id))
ENGINE = MEMORY
SELECT vZoneFk id;
CALL zone_getOptionsForShipment(vShipped, TRUE);
-- Reparto
INSERT INTO tmp.ticketComponent
SELECT tcc.warehouseFK,
tcc.itemFk,
c2.id,
z.inflation * ROUND(ic.cm3delivery * (IFNULL(zo.price,5000) - IFNULL(zo.bonus,0)) / (1000 * vc.standardFlowerBox) , 4) cost
FROM tmp.ticketComponentCalculate tcc
JOIN item i ON i.id = tcc.itemFk
JOIN tmp.zoneOption zo ON zo.zoneFk = vZoneFk
JOIN zone z ON z.id = vZoneFk
JOIN agencyMode am ON am.id = z.agencyModeFk
JOIN vn.volumeConfig vc
JOIN vn.component c2 ON c2.code = 'delivery'
LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk
AND ic.itemFk = tcc.itemFk
HAVING cost <> 0;
DROP TEMPORARY TABLE tmp.zoneOption;
CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY
SELECT * FROM tmp.ticketComponent;
-- Precio especial
INSERT INTO tmp.ticketComponent
SELECT tcc.warehouseFk,
tcc.itemFk,
c2.id,
sp.value - SUM(tcc.cost) sumCost
FROM tmp.ticketComponentCopy tcc
JOIN component c ON c.id = tcc.componentFk
JOIN tSpecialPrice sp ON sp.itemFk = tcc.itemFk
JOIN vn.component c2 ON c2.code = 'specialPrices'
WHERE c.classRate IS NULL
AND tcc.warehouseFk = vWarehouseFk
GROUP BY tcc.itemFk, tcc.warehouseFk
HAVING ABS(sumCost) > 0.001;
-- Rappel
INSERT INTO tmp.ticketComponent
SELECT tcc.warehouseFk,
tcc.itemFk,
IFNULL(c.componentFk ,c2.id),
SUM(tcc.cost) * ((1/(1-c.rappel/100)) -1) sumCost
FROM tmp.ticketComponentCopy tcc
JOIN vn.clientChain cc ON cc.clientFk = vClientFk
JOIN vn.`chain` c ON c.id = cc.chainFk
JOIN vn.component c2 ON c2.code = 'rappel'
WHERE tcc.warehouseFk = vWarehouseFk
GROUP BY tcc.itemFk, tcc.warehouseFk;
CREATE OR REPLACE 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;
CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY
SELECT tcc.warehouseFk,
tcc.itemFk,
1 rate,
IF(tcc.groupingMode = 'grouping', 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 = 'grouping' OR tcc.groupingMode IS NULL)
AND (tcc.packing > tcc.`grouping` OR tcc.groupingMode IS NULL)
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;
INSERT INTO tmp.ticketComponentPrice (warehouseFk, itemFk, rate, `grouping`, price, priceKg)
SELECT * FROM (
SELECT * FROM tmp.ticketComponentRate ORDER BY price LIMIT 10000000000000000000
) t
GROUP BY itemFk, warehouseFk, `grouping`;
DROP TEMPORARY TABLE
tmp.ticketComponentCalculate,
tmp.ticketComponentSum,
tmp.ticketComponentBase,
tmp.ticketComponentRate,
tmp.ticketComponentCopy,
tSpecialPrice;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `catalog_componentPrepare` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentPrepare`()
BEGIN
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 `fkItemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC)
)ENGINE=MEMORY DEFAULT CHARSET=utf8;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice;
CREATE TEMPORARY TABLE tmp.ticketComponentPrice (
`warehouseFk` INT UNSIGNED NOT NULL,
`itemFk` INT NOT NULL,
`rate` INT NOT NULL,
`grouping` INT UNSIGNED NOT NULL,
`price` DECIMAL(10,4) NOT NULL,
`priceKg` DECIMAL(10,4),
INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC),
UNIQUE `fkItemWarehouseRate` (`itemFk` ASC, `warehouseFk` ASC, `rate` ASC)
)ENGINE=MEMORY DEFAULT CHARSET=utf8;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `catalog_componentPurge` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentPurge`()
BEGIN
DROP TEMPORARY TABLE
tmp.ticketComponentPrice,
tmp.ticketComponent,
tmp.ticketLot;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`()
BEGIN
/**
* Purges outdated data to optimize performance.
* Exercise caution when executing.
*/
DECLARE v2Months DATE DEFAULT util.VN_CURDATE() - INTERVAL 2 MONTH;
DECLARE v3Months DATE DEFAULT util.VN_CURDATE() - INTERVAL 3 MONTH;
DECLARE v18Months DATE DEFAULT util.VN_CURDATE() - INTERVAL 18 MONTH;
DECLARE v26Months DATE DEFAULT util.VN_CURDATE() - INTERVAL 26 MONTH;
DECLARE v1Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 1 YEAR;
DECLARE v2Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 2 YEAR;
DECLARE v4Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 4 YEAR;
DECLARE v5Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 5 YEAR;
DECLARE vTrashId VARCHAR(15);
DECLARE vCompanyBlk INT;
DELETE FROM workerActivity WHERE created < v2Years;
DELETE FROM ticketParking WHERE created < v2Months;
DELETE FROM routesMonitor WHERE dated < v2Months;
DELETE FROM workerTimeControlLog WHERE created < v2Months;
DELETE FROM `message` WHERE sendDate < v2Months;
DELETE FROM messageInbox WHERE sendDate < v2Months;
DELETE FROM messageInbox WHERE sendDate < v2Months;
DELETE FROM workerTimeControl WHERE timed < v4Years;
DELETE FROM itemShelving WHERE created < util.VN_CURDATE() AND visible = 0;
DELETE FROM ticketDown WHERE created < util.yesterday();
DELETE FROM entryLog WHERE creationDate < v2Months;
DELETE IGNORE FROM expedition WHERE created < v26Months;
DELETE FROM sms WHERE created < v18Months;
DELETE FROM saleTracking WHERE created < v1Years;
DELETE FROM productionError WHERE dated < v1Years;
DELETE FROM ticketTracking WHERE created < v18Months;
DELETE tobs FROM ticketObservation tobs
JOIN ticket t ON tobs.ticketFk = t.id
WHERE t.shipped < v5Years;
DELETE sc.* FROM saleCloned sc JOIN sale s ON s.id = sc.saleClonedFk JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped < v1Years;
DELETE FROM sharingCart where ended < v2Months;
DELETE FROM sharingClient where ended < v2Months;
DELETE tw.* FROM ticketWeekly tw
LEFT JOIN sale s ON s.ticketFk = tw.ticketFk
LEFT JOIN ticketRequest tr ON tr.ticketFk = tw.ticketFk
LEFT JOIN ticketService ts ON ts.ticketFk = tw.ticketFk
WHERE s.id IS NULL
AND tr.id IS NULL
AND ts.id IS NULL;
DELETE FROM claim WHERE ticketCreated < v4Years;
-- Robert ubicacion anterior de travelLog comentario para debug
DELETE FROM zoneEvent WHERE `type` = 'day' AND dated < v3Months;
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 <= v2Months;
DELETE b FROM buy b
JOIN entryConfig e ON e.defaultEntry = b.entryFk
WHERE b.created < v2Months;
DELETE FROM itemShelvingLog WHERE created < v2Months;
DELETE FROM stockBuyed WHERE creationDate < v2Months;
DELETE FROM itemCleanLog WHERE created < util.VN_NOW() - INTERVAL 1 YEAR;
DELETE FROM printQueue WHERE statusCode = 'printed' AND created < v2Months;
DELETE FROM ticketLog WHERE creationDate <= v5Years;
-- Equipos duplicados
DELETE w.*
FROM workerTeam w
JOIN (
SELECT id, team, workerFk, COUNT(*) - 1 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;
DELETE sc
FROM saleComponent sc
JOIN sale s ON s.id= sc.saleFk
JOIN ticket t ON t.id= s.ticketFk
WHERE t.shipped < v18Months;
DELETE c
FROM claim c
JOIN claimState cs ON cs.id = c.claimStateFk
WHERE cs.description = 'Anulado'
AND c.created < v2Months;
DELETE FROM expeditionTruck WHERE eta < v3Months;
DELETE FROM XDiario WHERE FECHA < v3Months OR FECHA IS NULL;
-- Borrar travels sin entradas
CREATE OR REPLACE TEMPORARY TABLE tThermographToDelete
SELECT th.id,th.dmsFk
FROM travel t
LEFT JOIN entry e ON e.travelFk = t.id
JOIN travelThermograph th ON th.travelFk = t.id
WHERE t.shipped < v3Months
AND e.travelFk IS NULL;
SELECT dt.id INTO vTrashId
FROM dmsType dt
WHERE dt.code = 'trash';
UPDATE tThermographToDelete th
JOIN dms d ON d.id = th.dmsFk
SET d.dmsTypeFk = vTrashId;
DELETE th
FROM tThermographToDelete tmp
JOIN travelThermograph th ON th.id = tmp.id;
DELETE t
FROM travel t
LEFT JOIN entry e ON e.travelFk = t.id
WHERE t.shipped < v3Months AND e.travelFk IS NULL;
UPDATE dms d
JOIN dmsType dt ON dt.id = d.dmsTypeFk
SET d.dmsTypeFk = vTrashId
WHERE created < util.VN_CURDATE() - INTERVAL dt.monthToDelete MONTH;
-- borrar entradas sin compras
CREATE OR REPLACE TEMPORARY TABLE tEntryToDelete
SELECT e.*
FROM entry e
LEFT JOIN buy b ON b.entryFk = e.id
JOIN entryConfig ec ON e.id <> ec.defaultEntry
WHERE e.dated < v3Months
AND b.entryFK IS NULL;
DELETE e
FROM entry e
JOIN tEntryToDelete tmp ON tmp.id = e.id
WHERE NOT e.isBooked;
-- borrar de route registros menores a 4 años
CREATE OR REPLACE TEMPORARY TABLE tRouteToDelete
SELECT *
FROM route r
WHERE created < v4Years;
UPDATE tRouteToDelete tmp
JOIN dms d ON d.id = tmp.gestdocFk
SET d.dmsTypeFk = vTrashId;
DELETE r
FROM tRouteToDelete tmp
JOIN route r ON r.id = tmp.id;
-- borrar registros de dua y awb menores a 2 años
CREATE OR REPLACE TEMPORARY TABLE tDuaToDelete
SELECT *
FROM dua
WHERE operated < v2Years;
UPDATE tDuaToDelete tm
JOIN dms d ON d.id = tm.gestdocFk
SET d.dmsTypeFk = vTrashId;
DELETE d
FROM tDuaToDelete tmp
JOIN dua d ON d.id = tmp.id;
DELETE a
FROM awb a
LEFT JOIN travel t ON t.awbFk = a.id
WHERE a.created < v2Years
AND t.id IS NULL;
-- Borra los registros de collection y ticketcollection
DELETE FROM collection WHERE created < v2Months;
DELETE FROM travelLog WHERE creationDate < v3Months;
CALL shelving_clean();
DELETE FROM chat WHERE dated < v5Years;
DELETE tt FROM ticketTracking tt
JOIN ticket t ON tt.ticketFk = t.id
WHERE t.shipped <= v2Months;
DELETE FROM mail WHERE creationDate < v2Months;
DELETE FROM split WHERE dated < v18Months;
DELETE FROM remittance WHERE dated < v18Months;
CREATE OR REPLACE TEMPORARY TABLE tTicketDelete
SELECT DISTINCT tl.originFk ticketFk
FROM ticketLog tl
JOIN (
SELECT MAX(tl.id)ids
FROM ticket t
JOIN ticketLog tl ON tl.originFk = t.id
LEFT JOIN ticketWeekly tw ON tw.ticketFk = t.id
WHERE t.shipped BETWEEN '2000-01-01' AND '2000-12-31'
AND t.isDeleted
AND tw.ticketFk IS NULL
GROUP BY t.id
) sub ON sub.ids = tl.id
WHERE tl.creationDate <= v2Months;
DELETE t
FROM ticket t
JOIN tTicketDelete tmp ON tmp.ticketFk = t.id;
DELETE sl
FROM saleLabel sl
JOIN sale s ON s.id = sl.saleFk
JOIN ticket t ON t.id = s.ticketFk
WHERE t.shipped < v2Months;
-- Tickets Nulos PAK 11/10/2016
SELECT id INTO vCompanyBlk FROM company WHERE code = 'BLK';
UPDATE ticket
SET companyFk = vCompanyBlk
WHERE clientFk = (SELECT id FROM client WHERE name = 'AUTOCONSUMO')
AND companyFk <> vCompanyBlk;
DROP TEMPORARY TABLE tTicketDelete,
tThermographToDelete,
tEntryToDelete,
tDuaToDelete,
tRouteToDelete;
-- Other schemas
DELETE FROM hedera.`order` WHERE date_send < v18Months;
DELETE FROM pbx.cdr WHERE call_date < v18Months;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `clean_logiflora` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clean_logiflora`()
BEGIN
/**
* Elimina las compras y los artículos residuales de logiflora.
*/
DECLARE vDone INT DEFAULT FALSE;
DECLARE vBuyFk INT;
DECLARE vItemFk INT;
DECLARE cur1 CURSOR FOR SELECT id FROM tBuy;
DECLARE cur2 CURSOR FOR SELECT id FROM tItem;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
CREATE OR REPLACE TEMPORARY TABLE tBuy
ENGINE = MEMORY
SELECT b.id
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel tr ON tr.id = e.travelFk
JOIN agencyMode am ON am.id = tr.agencyModeFk
WHERE NOT b.quantity
AND am.code = 'logiflora'
AND e.isRaid;
START TRANSACTION;
OPEN cur1;
read_loop: LOOP
SET vDone = FALSE;
FETCH cur1 INTO vBuyFk;
IF vDone THEN
LEAVE read_loop;
END IF;
DELETE FROM buy WHERE id = vBuyFk;
END LOOP;
CLOSE cur1;
CREATE OR REPLACE TEMPORARY TABLE tItem
ENGINE = MEMORY
SELECT DISTINCT i.id
FROM item i
LEFT JOIN hedera.orderRow o ON o.itemFk = i.id
LEFT JOIN sale s ON s.itemFk = i.id
LEFT JOIN buy b ON b.itemFk = i.id
LEFT JOIN bs.waste w ON w.itemFk = i.id
WHERE i.supplyResponseFk
AND o.id IS NULL
AND b.id IS NULL
AND s.id IS NULL
AND w.itemFk IS NULL
AND i.created < (util.VN_CURDATE() - INTERVAL (SELECT daysToKeepItem FROM floramondoConfig) DAY);
OPEN cur2;
read_loop: LOOP
SET vDone = FALSE;
FETCH cur2 INTO vItemFk;
IF vDone THEN
LEAVE read_loop;
END IF;
DELETE FROM item WHERE id = vItemFk;
END LOOP;
CLOSE cur2;
COMMIT;
DROP TEMPORARY TABLE tBuy, tItem;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clearShelvingList`(vShelvingFk VARCHAR(8))
BEGIN
UPDATE vn.itemShelving
SET visible = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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.client_getDebt(vClientFk, util.VN_CURDATE()) INTO vClientDebt;
INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk)
VALUES (vClientFk, 'Saldo pendiente', vClientDebt, util.VN_CURDATE(), 5);
CALL vn.clientGreugeSpray(vClientFk, TRUE, '', TRUE);
INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk)
SELECT vClientFk, 'Liquidación cliente', sum(amount), util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clientFreeze`()
BEGIN
/**
* Congela diariamente aquellos clientes que son morosos sin recobro,
* pero que no sean trabajadores,
* y que el riesgo no sea menor que cero
* hasta que no se gire la remesa no se congelan a los clientes de giro
*/
DECLARE vIsRemittanced BOOLEAN;
SELECT id into vIsRemittanced
FROM receipt
WHERE invoiceFk LIKE 'REMESA%'
AND payed > util.firstDayOfMonth(util.VN_CURDATE())
LIMIT 1;
DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt;
CREATE TEMPORARY TABLE tmp.clientGetDebt
(INDEX (clientFk))
SELECT clientFk
FROM bs.defaulter
WHERE created = util.VN_CURDATE()
AND amount;
CALL client_getDebt(util.VN_CURDATE());
UPDATE client c
JOIN bi.defaulters d ON d.client = c.id AND d.date = util.VN_CURDATE()
JOIN config ON TRUE
LEFT JOIN recovery r ON r.clientFk = c.id AND r.finished IS NULL
LEFT JOIN payMethod pm ON pm.id = c.payMethodFk
LEFT JOIN tmp.risk rk ON rk.clientFk = c.id
SET c.isFreezed = TRUE,
d.frozened = util.VN_CURDATE()
WHERE (d.amount > config.defaultersMaxAmount
AND rk.risk > 0)
AND c.typeFk = 'normal'
AND r.id IS NULL
AND (vIsRemittanced OR pm.code <> 'bankDraft');
DROP TEMPORARY TABLE tmp.clientGetDebt;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 vDate IS NULL THEN
SET vDate=vIssued;
END IF;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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,
util.VN_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) monthSale
FROM vn.ticket t
JOIN vn.client c ON c.id = t.clientFk
JOIN vn.workerMana wm ON wm.workerFk = c.salesPersonFk
JOIN vn.claimRatio cr ON cr.clientFk = c.id
WHERE wm.workerFk = IF(onlyForHisOwner, vOwner, wm.workerFk)
AND t.shipped >= TIMESTAMPADD(MONTH,-1,util.VN_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, util.VN_CURDATE(), vGreugeTypeFk
FROM tmp.clientList
UNION ALL
SELECT vClientFk, 'Reparto greuge', -vGreuge, util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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
LIMIT 10000000000000000000
) 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clientPackagingOverstockReturn`(vClientFk INT, vGraceDays INT)
BEGIN
DECLARE vNewTicket INT DEFAULT 0;
DECLARE vWarehouseFk INT;
CALL vn.clientPackagingOverstock(vClientFk,vGraceDays);
SELECT id INTO vWarehouseFk
FROM vn.warehouse
WHERE hasConfectionTeam;
CALL vn.ticket_add(
vClientFk
,CURDATE()
,vWarehouseFk -- Algemesi
,442 -- Verdnatura
,NULL -- address
,NULL -- agencia
,NULL -- route
,CURDATE()
,account.myUser_getId()
,TRUE
,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;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clientRemoveWorker`()
BEGIN
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vClientFk INT;
DECLARE rs CURSOR FOR
SELECT c.clientFk
FROM tmp.clientGetDebt c
LEFT JOIN clientRisk r ON r.clientFk = c.clientFk
GROUP BY c.clientFk
HAVING SUM(IFNULL(r.amount,0)) = 0;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt;
CREATE TEMPORARY TABLE tmp.clientGetDebt
SELECT cd.clientFk
FROM bs.clientDied cd
LEFT JOIN clientProtected cp ON cp.clientFk = cd.clientFk
JOIN client c ON c.id = cd.clientFk
JOIN province p ON p.id = c.provinceFk
LEFT JOIN autonomy a ON a.id = p.autonomyFk
JOIN country co ON co.id = p.countryFk
WHERE cd.warning = 'third'
AND cp.clientFk IS NULL
AND co.code NOT IN ('PT')
AND a.name <> 'Canarias'
AND c.salesPersonFk IS NOT NULL;
OPEN rs;
FETCH rs INTO vClientFk;
WHILE NOT vDone DO
CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE);
UPDATE vn.client SET salesPersonFk = NULL WHERE id = vClientFk;
FETCH rs INTO vClientFk;
END WHILE;
CLOSE rs;
DROP TEMPORARY TABLE tmp.clientGetDebt;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `clientRisk_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clientRisk_update`(vClientId INT, vCompanyId INT, vAmount DECIMAL(10,2))
BEGIN
IF vAmount IS NOT NULL
THEN
INSERT INTO clientRisk
SET
clientFk = vClientId,
companyFk = vCompanyId,
amount = vAmount
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `client_checkBalance` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `client_checkBalance`(IN vDateTo DATETIME, IN vIsConciliated BOOL)
BEGIN
/**
* Compara los datos de nuestros clientes con
* los que hay en la base de datos de sage
*
* @param vDateTo
* @param vIsConciliated
* @table tmp.ledgerComparative (id, date, account, debit, credit, companyFk)
*/
DECLARE vDateFrom DATE;
DECLARE vMaxTolerance DECIMAL(10,2);
SELECT util.firstDayOfYear(vDateTo), util.dayEnd(vDateTo), maxTolerance
INTO vDateFrom, vDateTo, vMaxTolerance
FROM vn.ledgerConfig;
SELECT s.nickname,
c.id,
c.accountingAccount,
sub1.mysql,
sub1.sage,
sub1.mysql - sub1.sage difference,
sub1.companyFk,
c.name
FROM client c
JOIN payMethod pm ON pm.id = c.payMethodFk
JOIN (SELECT sub.companyFk,
sub.clientFk,
CAST(ROUND(SUM(sub.mysql), 2) AS DECIMAL(10,2)) mysql,
CAST(ROUND(SUM(sub.sage), 2) AS DECIMAL(10,2)) sage
FROM(SELECT io.companyFk,
io.clientFk,
- io.amount mysql,
0 sage
FROM invoiceOut io
WHERE issued BETWEEN vDateFrom AND vDateTo
UNION ALL
SELECT r.companyFk,
r.clientFk,
r.amountPaid,
0
FROM receipt r
WHERE payed BETWEEN vDateFrom AND vDateTo
AND IF(vIsConciliated,r.isConciliate, TRUE) = TRUE
UNION ALL
SELECT lc.companyFk,
c.id,
0,
- (IFNULL(lc.credit, 0) - IFNULL(lc.debit, 0))
FROM tmp.ledgerComparative lc
JOIN client c ON c.accountingAccount = lc.account
WHERE lc.`date` BETWEEN vDateFrom AND vDateTo
)sub
GROUP BY companyFk, clientFk
) sub1 ON sub1.clientFk = c.id
JOIN supplier s ON s.id = sub1.companyFk
JOIN company co ON co.id = sub1.companyFk
LEFT JOIN clientUnpaid cu ON cu.clientFk = c.id
AND cu.dated BETWEEN vDateFrom AND vDateTo
WHERE pm.outstandingDebt
AND co.code <> 'BLK'
AND cu.clientFk IS NULL
HAVING ABS(difference) > vMaxTolerance
ORDER BY c.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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `client_create` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `client_create`(
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),
vEmail VARCHAR(255),
vUserFk INT
)
BEGIN
/**
* Create new client
*
* @params vFirstname firstName
* @params vSurnames surnames
* @params vFi company code from accounting transactions
* @params vAddress address
* @params vPostcode postCode
* @params vCity city
* @params vProvinceFk province
* @params vCompanyFk company in which he has become a client
* @params vPhone telephone number
* @params vEmail email address
* @params vUserFk user id
*/
DECLARE vPayMethodFk INT;
DECLARE vDueDay INT;
DECLARE vDefaultCredit DECIMAL(10, 2);
DECLARE vIsTaxDataChecked TINYINT(1);
DECLARE vHasCoreVnl BOOLEAN;
DECLARE vMandateTypeFk INT;
SELECT defaultPayMethodFk,
defaultDueDay,
defaultCredit,
defaultIsTaxDataChecked,
defaultHasCoreVnl,
defaultMandateTypeFk
INTO vPayMethodFk,
vDueDay,
vDefaultCredit,
vIsTaxDataChecked,
vHasCoreVnl,
vMandateTypeFk
FROM clientConfig;
INSERT INTO `client`
SET id = vUserFk,
name = CONCAT(vFirstname, ' ', vSurnames),
street = vAddress,
fi = TRIM(vFi),
phone = vPhone,
email = vEmail,
provinceFk = vProvinceFk,
city = vCity,
postcode = vPostcode,
socialName = UPPER(CONCAT(vSurnames, ' ', vFirstname)),
payMethodFk = vPayMethodFk,
dueDay = vDueDay,
credit = vDefaultCredit,
isTaxDataChecked = vIsTaxDataChecked,
hasCoreVnl = vHasCoreVnl,
isEqualizated = FALSE
ON duplicate KEY UPDATE
payMethodFk = vPayMethodFk,
dueDay = vDueDay,
credit = vDefaultCredit,
isTaxDataChecked = vIsTaxDataChecked,
hasCoreVnl = vHasCoreVnl,
isActive = TRUE;
INSERT INTO mandate (clientFk, companyFk, mandateTypeFk)
SELECT vUserFk, vCompanyFk, vMandateTypeFk
WHERE NOT EXISTS (
SELECT id
FROM mandate
WHERE clientFk = vUserFk
AND companyFk = vCompanyFk
AND mandateTypeFk = vMandateTypeFk
);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `client_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `client_getDebt`(vDate DATE)
BEGIN
/**
* Calculates the risk for active clients
*
* @table tmp.clientGetDebt(clientFk)
* @param vDate Maximum date of records
* @return tmp.risk
*/
DECLARE vStarted DATETIME;
DECLARE vEnded DATETIME;
SELECT util.VN_CURDATE() - INTERVAL riskScope MONTH INTO vStarted
FROM clientConfig;
SET vEnded = util.dayEnd(IFNULL(vDate, util.VN_CURDATE()));
CREATE OR REPLACE TEMPORARY TABLE tClientRisk
ENGINE = MEMORY
SELECT cr.clientFk, SUM(cr.amount) amount
FROM clientRisk cr
JOIN tmp.clientGetDebt c ON c.clientFk = cr.clientFk
GROUP BY cr.clientFk;
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, SUM(totalWithVat)
FROM ticket t
JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk
WHERE refFk IS NULL
AND shipped BETWEEN vStarted AND vEnded
GROUP BY t.clientFk;
-- refs #6351 BUG: No cambiar a CREATE OR REPLACE
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
GROUP BY c.id;
DROP TEMPORARY TABLE tClientRisk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `client_getMana` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `client_getMana`()
BEGIN
/**
* Devuelve el mana de los clientes de la tabla tmp.client(id)
* @return tmp.clientMana(id, mana)
*
*/
DECLARE vFromDated DATE;
DELETE tc FROM tmp.client tc
JOIN client c ON c.id = tc.id
WHERE c.typeFk <> 'normal';
SELECT MAX(dated) INTO vFromDated
FROM clientManaCache;
CREATE OR REPLACE TEMPORARY TABLE tmp.clientMana
SELECT id, SUM(mana) mana
FROM
(
SELECT tc.id, cmc.mana
FROM clientManaCache cmc
JOIN tmp.client tc ON tc.id = cmc.clientFk
WHERE cmc.dated = vFromDated
UNION ALL
SELECT tc.id, s.quantity * value
FROM ticket t
JOIN address a ON a.id = t.addressFk
JOIN tmp.client tc ON tc.id = a.clientFk
JOIN sale s on s.ticketFk = t.id
JOIN saleComponent sc on sc.saleFk = s.id
JOIN component comp ON sc.componentFk = comp.id
JOIN componentType ct ON ct.id = comp.typeFk AND ct.code = 'mana'
WHERE t.shipped > vFromDated
AND t.shipped < util.tomorrow()
UNION ALL
SELECT tc.id, -amountPaid
FROM receipt r
JOIN `client` c ON c.id = r.clientFk
JOIN tmp.client tc ON tc.id = c.id
JOIN accounting a ON r.bankFk = a.id
AND a.code = 'mana'
WHERE r.payed > vFromDated
AND r.payed <= util.VN_CURDATE()
UNION ALL
SELECT tc.id, g.amount
FROM greuge g
JOIN `client` c ON c.id = g.clientFk
JOIN tmp.client tc ON tc.id = c.id
JOIN greugeType gt ON gt.id = g.greugeTypeFk AND gt.code = 'mana'
WHERE g.shipped > vFromDated
AND g.shipped <= util.VN_CURDATE()
) sub
GROUP BY 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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `client_getRisk` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `client_getRisk`(
vDate DATE
)
BEGIN
/**
* Retorna el riesgo de los clientes activos.
*
* @param vDate Fecha a calcular
*/
CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt
(PRIMARY KEY (clientFk))
ENGINE = MEMORY
SELECT id clientFk
FROM client
WHERE isActive;
CALL client_getDebt(vDate);
SELECT c.socialName,
r.clientFk,
c.credit,
CAST(r.risk AS DECIMAL (10,2)) risk,
CAST(c.credit - r.risk AS DECIMAL (10,2)) difference,
co.country
FROM client c
JOIN tmp.risk r ON r.clientFk = c.id
JOIN country co ON co.id = c.countryFk
GROUP BY c.id;
DROP TEMPORARY TABLE
tmp.risk,
tmp.clientGetDebt;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `client_RandomList` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `client_RandomList`(vNumber INT)
BEGIN
DECLARE i INT DEFAULT 0;
DECLARE c INT DEFAULT 0;
DECLARE maxClientFk INT;
DROP TEMPORARY TABLE IF EXISTS tmp.client;
CREATE TEMPORARY TABLE tmp.`client`
(id INT AUTO_INCREMENT,
clientFk INT,
isSelected TINYINT(1) NOT NULL DEFAULT 0,
PRIMARY KEY(id),
UNIQUE KEY clientFk (clientFk))
ENGINE = MEMORY;
INSERT INTO tmp.client(clientFk)
SELECT DISTINCT clientFk
FROM vn.invoiceOut
WHERE issued > TIMESTAMPADD(MONTH, -2, util.VN_CURDATE());
SELECT max(id) INTO maxClientFk
FROM tmp.client;
WHILE i < vNumber DO
SET i = i + 1;
WHILE c = 0 DO
SELECT id INTO c
FROM tmp.client
WHERE id = floor(RAND() * maxClientFk) + 1
AND isSelected = FALSE
LIMIT 1;
END WHILE;
-- SELECT i, maxClientFk, c;
UPDATE tmp.client
SET isSelected = TRUE
WHERE id = c;
SET c = 0;
END WHILE;
SELECT c.id, c.name FROM tmp.client tc
JOIN vn.client c ON c.id = tc.clientFk
WHERE isSelected
ORDER 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `client_unassignSalesPerson` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `client_unassignSalesPerson`()
BEGIN
/**
* Elimina la asignación de salesPersonFk de la ficha del clientes
* que no han realizado una compra en los últimos 3 meses y reparte
* su greuge entre el resto de clientes
*/
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vClientFk INT;
DECLARE vCursor CURSOR FOR
SELECT c.clientFk
FROM tClientList c
LEFT JOIN clientRisk r ON r.clientFk = c.clientFk
GROUP BY c.clientFk
HAVING NOT SUM(IFNULL(r.amount, 0));
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
CREATE OR REPLACE TEMPORARY TABLE tClientList
SELECT c.id clientFk
FROM bs.clientDied cd
JOIN client c ON c.id = cd.clientFk
LEFT JOIN clientProtected cp ON cp.clientFk = c.id
LEFT JOIN salesPersonProtected sp ON sp.salesPersonFk = c.salesPersonFk
JOIN province p ON p.id = c.provinceFk
LEFT JOIN autonomy a ON a.id = p.autonomyFk
JOIN country co ON co.id = p.countryFk
WHERE cd.warning = 'third'
AND cp.clientFk IS NULL
AND sp.salesPersonFk IS NULL
AND a.name <> 'Canarias'
AND c.salesPersonFk IS NOT NULL;
OPEN vCursor;
l: LOOP
SET vDone = FALSE;
FETCH vCursor INTO vClientFk;
IF vDone THEN
LEAVE l;
END IF;
CALL clientGreugeSpray(vClientFk, TRUE, '', TRUE);
UPDATE client
SET salesPersonFk = NULL
WHERE id = vClientFk;
END LOOP;
CLOSE vCursor;
DROP TEMPORARY TABLE tClientList;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cmrPallet_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `cmrPallet_add`(vExpeditionPalletFk INT, vCmrFk INT)
BEGIN
/**
* Añade registro a tabla cmrPallet.
*
* @param vExpeditionPalletFk Id de expeditionPallet
* @param vCmrFk Id de cmrPallet
*/
DECLARE vIsACurrentExpeditionPallet BOOL;
DECLARE vIsACurrentCMR BOOL;
DECLARE vYesterday DATE;
SET vYesterday = util.yesterday();
SELECT COUNT(*) INTO vIsACurrentExpeditionPallet
FROM vn.expeditionPallet cp
WHERE cp.id = vExpeditionPalletFk
AND cp.built >= vYesterday;
IF !vIsACurrentExpeditionPallet THEN
CALL util.throw('expeditionPalletNotExist');
END IF;
SELECT COUNT(*) INTO vIsACurrentCMR
FROM vn.cmr c
WHERE c.id = vCmrFk
AND c.created >= vYesterday;
IF vIsACurrentCMR THEN
INSERT INTO cmrPallet (cmrFk, expeditionPalletFk)
VALUES(vCmrFk, vExpeditionPalletFk);
ELSE
Call util.throw('cmrNotExist');
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `collectionPlacement_get`(
vParamFk INT(11),
vIsPicker bool)
BEGIN
/**
* Devuelve el listado de ubicaciones a las que hay que ir
* para preparar una colección o ticket de manera ordenada
*
* @param vParamFk Identificador de collection o Identificador de ticket
* @param vIsPicker Booleano para distinguer el sacador del revisador
*/
DECLARE vCalcFk INT;
DECLARE vWarehouseFk INT;
DECLARE vCurrentYear INT DEFAULT YEAR(util.VN_NOW());
CREATE OR REPLACE TEMPORARY TABLE tSale
(INDEX(ticketFk), INDEX(saleFk), INDEX(itemFk))
ENGINE = MEMORY
SELECT s.ticketFk, s.id saleFk, s.itemFk, s.quantity
FROM ticketCollection tc
JOIN sale s ON s.ticketFk = tc.ticketFk
WHERE tc.collectionFk = vParamFk
UNION ALL
SELECT s.ticketFk, s.id, s.itemFk, s.quantity
FROM sale s
WHERE s.ticketFk = vParamFk;
SELECT t.warehouseFk
INTO vWarehouseFk
FROM ticket t
JOIN tSale ts ON ts.ticketFk = t.id
JOIN warehouse w ON w.id = t.warehouseFk
LIMIT 1;
CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk);
CREATE OR REPLACE TEMPORARY TABLE tGrouping
(INDEX(itemFk))
ENGINE = MEMORY
SELECT b.itemFk,
CASE b.groupingMode
WHEN NULL THEN 1
WHEN 'packing' THEN b.packing
ELSE b.`grouping`
END `grouping`
FROM buy b
JOIN cache.last_buy lb ON lb.buy_id = b.id
WHERE lb.warehouse_id = vWarehouseFk
GROUP BY b.itemFk;
CREATE OR REPLACE TEMPORARY TABLE tSalePlacementList
(INDEX(saleFk), INDEX(`order`))
ENGINE = MEMORY
SELECT ts.saleFk,
ts.itemFk,
CAST(0 AS DECIMAL(10,0)) saleOrder,
IF(ish.visible > 0 OR iss.id, 1, 100000) *
IFNULL(p2.pickingOrder, p.pickingOrder) `order`,
TO_SECONDS(IF(iss.id,
iss.created - INTERVAL vCurrentYear YEAR,
ish.created - INTERVAL YEAR(ish.created) YEAR)) priority,
CONCAT(
IF(iss.id,
CONCAT('< ', IFNULL(wk.`code`, '---'),' > '),
''),
p.`code`) COLLATE utf8_general_ci placement,
sh.priority shelvingPriority,
sh.code COLLATE utf8_general_ci shelving,
ish.created,
ish.visible,
IFNULL(
IF(st.code = 'previousByPacking', ish.packing, g.`grouping`),
1) `grouping`,
st.code = 'previousPrepared' isPreviousPrepared,
iss.id itemShelvingSaleFk,
ts.ticketFk,
iss.id,
st.saleFk salePreviousPrepared,
iss.userFk,
ts.quantity
FROM tSale ts
LEFT JOIN (SELECT DISTINCT saleFk
FROM saleTracking st
JOIN state s ON s.id = st.stateFk
WHERE st.isChecked
AND s.semaphore = 1) st ON st.saleFk = ts.saleFk
JOIN itemShelving ish ON ish.itemFk = ts.itemFk
JOIN shelving sh ON sh.code = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector sc ON sc.id = p.sectorFk
JOIN sectorType st ON st.id = sc.typeFk
JOIN warehouse w ON w.id = sc.warehouseFk
LEFT JOIN tGrouping g ON g.itemFk = ts.itemFk
LEFT JOIN itemShelvingSale iss ON iss.saleFk = ts.saleFk
AND iss.itemShelvingFk = ish.id
LEFT JOIN worker wk ON wk.id = iss.userFk
LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = ts.saleFk
LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk
LEFT JOIN parking p2 ON p2.id = sg.parkingFk
WHERE w.id = vWarehouseFk
AND NOT sc.isHideForPickers
HAVING (iss.id AND st.saleFk) OR salePreviousPrepared IS NULL;
CREATE OR REPLACE TEMPORARY TABLE tSalePlacementList2
(INDEX(saleFk), INDEX(olderPriority))
ENGINE = MEMORY
SELECT saleFk, priority olderPriority
FROM (SELECT saleFk, priority
FROM tSalePlacementList
ORDER BY isPreviousPrepared DESC,
itemShelvingSaleFk IS NULL DESC,
visible >= quantity DESC,
visible > 0 DESC,
IFNULL(shelvingPriority, 0) DESC,
priority
LIMIT 10000000000000000000
)sub
GROUP BY saleFk;
UPDATE tSalePlacementList tsp
JOIN (SELECT s1.saleFk, `order` saleOrder
FROM tSalePlacementList s1
JOIN tSalePlacementList2 s2 ON s2.saleFk = s1.saleFk
AND s2.olderPriority = s1.priority
) sub ON sub.saleFk = tsp.saleFk
SET tsp.saleOrder = sub.saleOrder;
-- Anula el orden de antigüedad y ordena por ubicación
UPDATE tSalePlacementList
SET saleOrder = `order`;
SELECT spl.*
FROM tSalePlacementList spl
JOIN sale s ON s.id = spl.saleFk
ORDER BY saleOrder,
isPreviousPrepared DESC,
itemShelvingSaleFk DESC,
IF(vIsPicker, visible = 0, TRUE),
s.quantity <= spl.visible DESC,
shelvingPriority DESC,
priority;
DROP TEMPORARY TABLE
tSale,
tGrouping,
tSalePlacementList,
tSalePlacementList2;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `collection_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_addItem`(
vBarccodeFk INT,
vQuantity INT,
vTicketFk INT
)
BEGIN
/**
* Add a sales line to the ticket with the indicated amount.
*
* @param vBarcodeFk barcode on the item label
* @param vQuantity quantity to be added to the ticket
* @param vTicketFk ticket to which the sales line is added
*/
DECLARE vConcept VARCHAR(50);
DECLARE vItemFk INT;
DECLARE vSaleFk INT;
DECLARE vDescription VARCHAR(50);
DECLARE vItemName VARCHAR(50);
SELECT barcodeToItem(vBarccodeFk) INTO vItemFk;
SELECT CONCAT(getUser(),
' ',
DATE_FORMAT(util.VN_NOW(), '%H:%i' ),
' ',
i.name
) INTO vConcept
FROM item i
WHERE i.id = vItemFk;
SELECT name INTO vItemName FROM item WHERE id = vBarccodeFk;
SELECT CONCAT('Añadido articulo ',
vItemName,
' cantidad:',
vQuantity
) INTO vDescription;
INSERT INTO ticketLog
SET originFk = vTicketFk,
userFk = getUser(),
`action` = 'update',
`description` = vDescription;
INSERT INTO sale
SET itemFk = vItemFk,
ticketFk = vTicketFk,
concept = vConcept,
quantity = vQuantity,
isAdded = TRUE;
SELECT LAST_INSERT_ID() INTO vSaleFk;
UPDATE sale
SET originalQuantity = 0
WHERE id = vSaleFk;
CALL sale_calculateComponent(vSaleFk, 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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `collection_assign` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign`(
vUserFk INT,
OUT vCollectionFk INT
)
BEGIN
/**
* Comprueba si existen colecciones libres que se ajustan
* al perfil del usuario y le asigna la más antigua.
* Añade un registro al semillero de colecciones.
*
* @param vUserFk Id de usuario
* @param vCollectionFk Id de colección
*/
DECLARE vHasTooMuchCollections BOOL;
DECLARE vItemPackingTypeFk VARCHAR(1);
DECLARE vWarehouseFk INT;
DECLARE vLockName VARCHAR(215);
DECLARE vLockTime INT DEFAULT 30;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
IF vLockName IS NOT NULL THEN
DO RELEASE_LOCK(vLockName);
END IF;
RESIGNAL;
END;
-- Si hay colecciones sin terminar, sale del proceso
CALL collection_get(vUserFk);
SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0,
collection_assign_lockname
INTO vHasTooMuchCollections,
vLockName
FROM productionConfig pc
LEFT JOIN tCollection ON TRUE;
DROP TEMPORARY TABLE tCollection;
IF vHasTooMuchCollections THEN
CALL util.throw('Hay colecciones pendientes');
END IF;
SELECT warehouseFk, itemPackingTypeFk
INTO vWarehouseFk, vItemPackingTypeFk
FROM operator
WHERE workerFk = vUserFk;
SET vLockName = CONCAT_WS('/',
vLockName,
vWarehouseFk,
vItemPackingTypeFk
);
IF NOT GET_LOCK(vLockName, vLockTime) THEN
CALL util.throw(CONCAT('Cannot get lock: ', vLockName));
END IF;
-- Se eliminan las colecciones sin asignar que estan obsoletas
INSERT INTO ticketTracking(stateFk, ticketFk)
SELECT s.id, tc.ticketFk
FROM `collection` c
JOIN ticketCollection tc ON tc.collectionFk = c.id
JOIN `state` s ON s.code = 'PRINTED_AUTO'
JOIN productionConfig pc
WHERE c.workerFk IS NULL
AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime;
DELETE c.*
FROM `collection` c
JOIN productionConfig pc
WHERE c.workerFk IS NULL
AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime;
-- Se añade registro al semillero
INSERT INTO collectionHotbed(userFk)
VALUES(vUserFk);
-- Comprueba si hay colecciones disponibles que se ajustan a su configuracion
SELECT MIN(c.id)
INTO vCollectionFk
FROM `collection` c
JOIN operator o
ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL)
AND o.numberOfWagons = c.wagons
AND o.trainFk = c.trainFk
AND o.warehouseFk = c.warehouseFk
AND c.workerFk IS NULL
AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL)
JOIN (
SELECT tc.collectionFk, SUM(sv.volume) volume
FROM ticketCollection tc
JOIN saleVolume sv ON sv.ticketFk = tc.ticketFk
WHERE sv.shipped >= util.VN_CURDATE()
GROUP BY tc.collectionFk
) sub ON sub.collectionFk = c.id
AND (volume <= o.volumeLimit OR o.volumeLimit IS NULL)
WHERE o.workerFk = vUserFk;
IF vCollectionFk IS NULL THEN
CALL collection_new(vUserFk, vCollectionFk);
END IF;
UPDATE `collection`
SET workerFk = vUserFk
WHERE id = vCollectionFk;
DO RELEASE_LOCK(vLockName);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `collection_assign2` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign2`(
vUserFk INT,
OUT vCollectionFk INT
)
proc:BEGIN
/**
* Comprueba si existen colecciones libres que se ajustan
* al perfil del usuario y le asigna la más antigua.
* Añade un registro al semillero de colecciones.
*
* @param vUserFk Id de usuario
* @param vCollectionFk Id de colección
*/
DECLARE vHasTooMuchCollections BOOL;
DECLARE vLockTime INT DEFAULT 15;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
DO RELEASE_LOCK('collection_assign2');
RESIGNAL;
END;
-- Si hay colecciones sin terminar, sale del proceso
CALL collection_get(vUserFk);
SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0
INTO vHasTooMuchCollections
FROM tCollection
JOIN productionConfig pc ;
DROP TEMPORARY TABLE tCollection;
IF vHasTooMuchCollections THEN
CALL util.throw('Hay colecciones pendientes');
LEAVE proc;
END IF;
IF NOT GET_LOCK('collection_assign2',vLockTime) THEN
LEAVE proc;
END IF;
-- Se eliminan las colecciones sin asignar que estan obsoletas
INSERT INTO ticketTracking(stateFk, ticketFk)
SELECT s.id, tc.ticketFk
FROM `collection` c
JOIN ticketCollection tc ON tc.collectionFk = c.id
JOIN `state` s ON s.code = 'PRINTED_AUTO'
JOIN productionConfig pc
WHERE c.workerFk IS NULL
AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime;
DELETE c.*
FROM `collection` c
JOIN productionConfig pc
WHERE c.workerFk IS NULL
AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime;
-- Se añade registro al semillero
INSERT INTO collectionHotbed(userFk)
VALUES(vUserFk);
-- Comprueba si hay colecciones disponibles que se ajustan a su configuracion
SELECT MIN(c.id)
INTO vCollectionFk
FROM `collection` c
JOIN operator o
ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL)
AND o.numberOfWagons = c.wagons
AND o.trainFk = c.trainFk
AND o.warehouseFk = c.warehouseFk
AND c.workerFk IS NULL
AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL)
JOIN (
SELECT tc.collectionFk, SUM(sv.volume) volume
FROM ticketCollection tc
JOIN saleVolume sv ON sv.ticketFk = tc.ticketFk
WHERE sv.shipped >= util.VN_CURDATE()
GROUP BY tc.collectionFk
) sub ON sub.collectionFk = c.id
AND (volume <= o.volumeLimit OR o.volumeLimit IS NULL)
WHERE o.workerFk = vUserFk;
IF vCollectionFk IS NULL THEN
CALL collection_new(vUserFk, vCollectionFk);
END IF;
UPDATE `collection`
SET workerFk = vUserFk
WHERE id = vCollectionFk;
DO RELEASE_LOCK('collection_assign2');
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `collection_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_get`(vWorkerFk INT)
BEGIN
/**
* Obtiene colección del sacador si tiene líneas pendientes.
*
* @param vWorkerFk id del worker.
* @table Devuelve tabla temporal con las colecciones pendientes
*/
DROP TEMPORARY TABLE IF EXISTS tCollection;
CREATE TEMPORARY TABLE tCollection
SELECT c.id collectionFk,
date(c.created) created,
COUNT(DISTINCT tc.ticketFk) ticketTotalCount
FROM collection c
JOIN ticketCollection tc ON tc.collectionFk = c.id
JOIN sale s ON s.ticketFk = tc.ticketFk
JOIN ticketState ts ON ts.ticketFk = tc.ticketFk
JOIN state s2 ON s2.id = ts.stateFk
JOIN productionConfig pc
JOIN vn.state ss on ss.code = 'PREPARED'
LEFT JOIN vn.saleTracking st on st.saleFk = s.id AND st.stateFk = ss.id
WHERE c.workerFk = vWorkerFk
AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge
AND s.quantity != 0
AND s2.order < pc.pendingCollectionsOrder
GROUP BY c.id
HAVING COUNT(*) > COUNT(DISTINCT st.id);
SELECT * FROM tCollection;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `collection_getTickets` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_getTickets`(vParamFk INT)
BEGIN
/**
* Selecciona los tickets de una colección/ticket
* @param vParamFk ticketFk/collectionFk
* @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observaciones
*/
DECLARE vItemPackingTypeFk VARCHAR(1);
-- Si los sacadores son los de pruebas, pinta los colores
SELECT itemPackingTypeFk INTO vItemPackingTypeFk
FROM vn.collection
WHERE id = vParamFk;
SELECT t.id ticketFk,
IF (!(vItemPackingTypeFk <=> 'V'), cc.code,CONCAT(SUBSTRING('ABCDEFGH',tc.wagon, 1),'-',tc.`level` )) `level`,
am.name agencyName,
t.warehouseFk,
w.id salesPersonFk,
IFNULL(tob.description,'') observaciones,
cc.rgb
FROM vn.ticket t
LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk
LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21
LEFT JOIN vn.collectionColors cc
ON cc.wagon = tc.wagon
AND cc.shelve = tc.`level`
AND cc.trainFk = c2.trainFk -- PAK 23/12/21
LEFT JOIN vn.zone z ON z.id = t.zoneFk
LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
LEFT JOIN vn.client c ON c.id = t.clientFk
LEFT JOIN vn.worker w ON w.id = c.salesPersonFk
LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id
AND tob.observationTypeFk = 1
WHERE t.id = vParamFk
AND t.shipped >= util.yesterday()
UNION ALL
SELECT t.id ticketFk,
IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`,
am.name agencyName,
t.warehouseFk,
w.id salesPersonFk,
IFNULL(tob.description, '') observaciones,
IF(!(vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb`
FROM vn.ticket t
JOIN vn.ticketCollection tc ON t.id = tc.ticketFk
LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21
LEFT JOIN vn.collectionColors cc
ON cc.wagon = tc.wagon
AND cc.shelve = tc.`level`
AND cc.trainFk = c2.trainFk -- PAK 23/12/21
LEFT JOIN vn.zone z ON z.id = t.zoneFk
LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
LEFT JOIN vn.client c ON c.id = t.clientFk
LEFT JOIN vn.worker w ON w.id = c.salesPersonFk
LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id
AND tob.observationTypeFk = 1
WHERE tc.collectionFk = vParamFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `collection_kill` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_kill`(vSelf INT)
BEGIN
/**
* Elimina una coleccion y coloca sus tickets en OK
*/
INSERT INTO ticketTracking(stateFk, ticketFk)
SELECT s.id, ticketFk
FROM vn.ticketCollection tc
JOIN vn.state s ON s.code = 'OK'
WHERE tc.collectionFk = vSelf;
DELETE FROM vn.collection
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `collection_make` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_make`()
proc:BEGIN
/**
* Genera colecciones de tickets sin asignar trabajador a partir de la tabla
* vn.collectionHotbed.
*/
DECLARE vUserFk INT;
DECLARE vCounter INT;
DECLARE vMaxCollectionWithoutUser INT;
DECLARE vHasEnoughFreeCollections BOOL;
DECLARE vDone INT DEFAULT FALSE;
DECLARE cur1 CURSOR FOR
SELECT DISTINCT userFk
FROM vn.collectionHotbed;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SELECT maxCollectionWithoutUser
INTO vMaxCollectionWithoutUser
FROM vn.productionConfig pc;
SELECT (vMaxCollectionWithoutUser - COUNT(*)) <= 0
INTO vHasEnoughFreeCollections
FROM vn.collection c
JOIN vn.operator o
ON o.numberOfWagons = c.wagons
AND o.trainFk = c.trainFk
AND o.itemPackingTypeFk = c.itemPackingTypeFk
WHERE c.workerFk IS NULL
AND o.workerFk = vUserFk;
IF vHasEnoughFreeCollections THEN
LEAVE proc;
END IF;
OPEN cur1;
read_loop: LOOP
SET vDone = FALSE;
FETCH cur1 INTO vUserFk;
IF vDone THEN
LEAVE read_loop;
END IF;
SET vCounter = vMaxCollectionWithoutUser;
WHILE vCounter > 0 DO
SET vCounter = vCounter - 1;
CALL vn.collection_new(vUserFk, @vCollectionFk);
END WHILE;
DELETE
FROM vn.collectionHotbed
WHERE userFk = vUserFk;
END LOOP;
CLOSE cur1;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_new`(vUserFk INT, OUT vCollectionFk INT)
BEGIN
/**
* Genera colecciones de tickets sin asignar trabajador.
*
* @param vUserFk Identificador de account.user
*/
DECLARE vWarehouseFk INT;
DECLARE vWagons INT;
DECLARE vTrainFk INT;
DECLARE vLinesLimit INT DEFAULT NULL;
DECLARE vTicketLines INT;
DECLARE vVolumeLimit DECIMAL DEFAULT NULL;
DECLARE vTicketVolume DECIMAL;
DECLARE vMaxTickets INT;
DECLARE vStateFk VARCHAR(45);
DECLARE vFirstTicketFk INT;
DECLARE vHour INT;
DECLARE vMinute INT;
DECLARE vWorkerCode VARCHAR(3);
DECLARE vWagonCounter INT DEFAULT 0;
DECLARE vTicketFk INT;
DECLARE vItemPackingTypeFk VARCHAR(1);
DECLARE vHasAssignedTickets BOOLEAN;
DECLARE vHasUniqueCollectionTime BOOL;
DECLARE vDone INT DEFAULT FALSE;
DECLARE vLockName VARCHAR(215);
DECLARE vLockTime INT DEFAULT 30;
DECLARE vFreeWagonFk INT;
DECLARE c1 CURSOR FOR
SELECT ticketFk, `lines`, m3
FROM tmp.productionBuffer
WHERE ticketFk <> vFirstTicketFk
ORDER BY HH,
mm,
productionOrder DESC,
m3 DESC,
agency,
zona,
routeFk,
ticketFk
LIMIT vMaxTickets;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
IF vLockName IS NOT NULL THEN
DO RELEASE_LOCK(vLockName);
END IF;
RESIGNAL;
END;
SELECT pc.ticketTrolleyMax * o.numberOfWagons,
pc.hasUniqueCollectionTime,
w.code,
o.warehouseFk,
o.itemPackingTypeFk,
st.code,
o.numberOfWagons,
o.trainFk,
o.linesLimit,
o.volumeLimit,
pc.collection_new_lockname
INTO vMaxTickets,
vHasUniqueCollectionTime,
vWorkerCode,
vWarehouseFk,
vItemPackingTypeFk,
vStateFk,
vWagons,
vTrainFk,
vLinesLimit,
vVolumeLimit,
vLockName
FROM productionConfig pc
JOIN worker w ON w.id = vUserFk
JOIN state st ON st.`code` = 'ON_PREPARATION'
JOIN operator o ON o.workerFk = vUserFk;
SET vLockName = CONCAT_WS('/',
vLockName,
vWarehouseFk,
vItemPackingTypeFk
);
IF NOT GET_LOCK(vLockName, vLockTime) THEN
CALL util.throw(CONCAT('Cannot get lock: ', vLockName));
END IF;
-- Se prepara el tren, con tantos vagones como sea necesario.
CREATE OR REPLACE TEMPORARY TABLE tTrain
(wagon INT,
shelve INT,
liters INT,
`lines`INT,
height INT,
ticketFk INT,
PRIMARY KEY(wagon, shelve))
ENGINE = MEMORY;
WHILE vWagons > vWagonCounter DO
SET vWagonCounter = vWagonCounter + 1;
INSERT INTO tTrain(wagon, shelve, liters, `lines`, height)
SELECT vWagonCounter, cv.`level` , cv.liters , cv.`lines` , cv.height
FROM collectionVolumetry cv
WHERE cv.trainFk = vTrainFk
AND cv.itemPackingTypeFk = vItemPackingTypeFk;
END WHILE;
-- Esto desaparecerá cuando tengamos la table cache.ticket
CALL productionControl(vWarehouseFk, 0);
ALTER TABLE tmp.productionBuffer
ADD COLUMN liters INT,
ADD COLUMN height INT;
-- Se obtiene nº de colección.
INSERT INTO collection
SET itemPackingTypeFk = vItemPackingTypeFk,
trainFk = vTrainFk,
wagons = vWagons,
warehouseFk = vWarehouseFk;
SELECT LAST_INSERT_ID() INTO vCollectionFk;
-- Los tickets de recogida en Algemesí sólo se sacan si están asignados.
-- Los pedidos con riesgo no se sacan aunque se asignen.
DELETE pb.*
FROM tmp.productionBuffer pb
JOIN state s ON s.id = pb.state
WHERE (pb.agency = 'REC_ALGEMESI'
AND s.code <> 'PICKER_DESIGNED')
OR pb.problem LIKE '%RIESGO%';
-- Comprobamos si hay tickets asignados. En ese caso, nos centramos
-- exclusivamente en esos tickets y los sacamos independientemente
-- de problemas o tamaños
SELECT COUNT(*) INTO vHasAssignedTickets
FROM tmp.productionBuffer pb
JOIN state s ON s.id = pb.state
WHERE s.code = 'PICKER_DESIGNED'
AND pb.workerCode = vWorkerCode;
-- Se dejan en la tabla tmp.productionBuffer sólo aquellos tickets adecuados
IF vHasAssignedTickets THEN
DELETE pb.*
FROM tmp.productionBuffer pb
JOIN state s ON s.id = pb.state
WHERE s.code <> 'PICKER_DESIGNED'
OR pb.workerCode <> vWorkerCode;
ELSE
DELETE pb.*
FROM tmp.productionBuffer pb
JOIN state s ON s.id = pb.state
JOIN agencyMode am ON am.id = pb.agencyModeFk
JOIN agency a ON a.id = am.agencyFk
JOIN productionConfig pc
WHERE pb.shipped <> util.VN_CURDATE()
OR (pb.ubicacion IS NULL AND a.isOwn)
OR (NOT s.isPreparable AND NOT s.isPrintable)
OR pb.collectionH IS NOT NULL
OR pb.collectionV IS NOT NULL
OR pb.collectionN IS NOT NULL
OR (NOT pb.H AND pb.V > 0 AND vItemPackingTypeFk = 'H')
OR (NOT pb.V AND vItemPackingTypeFk = 'V')
OR (pc.isPreviousPreparationRequired AND pb.previousWithoutParking)
OR LENGTH(pb.problem) > 0
OR (pb.lines >= vLinesLimit AND vLinesLimit IS NOT NULL)
OR (pb.m3 >= vVolumeLimit AND vVolumeLimit IS NOT NULL);
END IF;
-- Es importante que el primer ticket se coja en todos los casos
SELECT ticketFk,
HH,
mm,
`lines`,
m3
INTO vFirstTicketFk,
vHour,
vMinute,
vTicketLines,
vTicketVolume
FROM tmp.productionBuffer
ORDER BY HH,
mm,
productionOrder DESC,
m3 DESC,
agency,
zona,
routeFk,
ticketFk
LIMIT 1;
-- Hay que excluir aquellos que no tengan la misma hora de preparacion, si procede
IF vHasUniqueCollectionTime THEN
DELETE FROM tmp.productionBuffer
WHERE HH <> vHour
OR mm <> vMinute;
END IF;
SET vTicketFk = vFirstTicketFk;
SET @lines = 0;
SET @volume = 0;
OPEN c1;
read_loop: LOOP
SET vDone = FALSE;
-- Buscamos un ticket que cumpla con los requisitos en el listado
IF ((vTicketLines + @lines) <= vLinesLimit OR vLinesLimit IS NULL)
AND ((vTicketVolume + @volume) <= vVolumeLimit OR vVolumeLimit IS NULL) THEN
CALL ticket_splitItemPackingType(vTicketFk, vItemPackingTypeFk);
DROP TEMPORARY TABLE tmp.ticketIPT;
UPDATE tmp.productionBuffer pb
JOIN (
SELECT SUM(litros) liters,
@lines:= COUNT(*) + @lines,
COUNT(*) `lines`,
MAX(i.`size`) height,
@volume := SUM(sv.volume) + @volume,
SUM(sv.volume) volume
FROM saleVolume sv
JOIN sale s ON s.id = sv.saleFk
JOIN item i ON i.id = s.itemFk
WHERE sv.ticketFk = vTicketFk
) sub
SET pb.liters = sub.liters,
pb.`lines` = sub.`lines`,
pb.height = sub.height
WHERE pb.ticketFk = vTicketFk;
UPDATE tTrain tt
JOIN tmp.productionBuffer pb ON pb.ticketFk = vTicketFk
SET tt.ticketFk = pb.ticketFk
WHERE tt.liters >= pb.liters
AND tt.`lines` >= pb.`lines`
AND (tt.height >= pb.height OR vItemPackingTypeFk <> 'V')
AND tt.ticketFk IS NULL
ORDER BY wagon,
shelve,
tt.liters,
tt.`lines`,
tt.height
LIMIT 1;
-- Si no le encuentra una balda adecuada, intentamos darle un carro entero si queda alguno libre
IF NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN
SELECT tt.wagon
INTO vFreeWagonFk
FROM tTrain tt
LEFT JOIN (
SELECT DISTINCT wagon
FROM tTrain
WHERE ticketFk IS NOT NULL
) nn ON nn.wagon = tt.wagon
WHERE nn.wagon IS NULL
ORDER BY wagon
LIMIT 1;
IF vFreeWagonFk THEN
UPDATE tTrain
SET ticketFk = vFirstTicketFk
WHERE wagon = vFreeWagonFk;
-- Se anulan el resto de carros libres para que sólo uno lleve un pedido excesivo
DELETE tt.*
FROM tTrain tt
LEFT JOIN (
SELECT DISTINCT wagon
FROM tTrain
WHERE ticketFk IS NOT NULL
) nn ON nn.wagon = tt.wagon
WHERE nn.wagon IS NULL;
END IF;
END IF;
FETCH c1 INTO vTicketFk, vTicketLines, vTicketVolume;
IF vDone OR NOT (SELECT COUNT(*) FROM tTrain WHERE ticketFk IS NULL) THEN
LEAVE read_loop;
END IF;
ELSE
FETCH c1 INTO vTicketFk, vTicketLines, vTicketVolume;
IF vDone THEN
LEAVE read_loop;
END IF;
END IF;
END LOOP;
CLOSE c1;
IF (SELECT COUNT(*) FROM tTrain WHERE ticketFk) THEN
UPDATE collection c
JOIN state st ON st.code = 'ON_PREPARATION'
SET c.stateFk = st.id
WHERE c.id = vCollectionFk;
-- Asigna las bandejas
INSERT IGNORE INTO ticketCollection(ticketFk, collectionFk, `level`, wagon, liters)
SELECT tt.ticketFk, vCollectionFk, tt.shelve, tt.wagon, tt.liters
FROM tTrain tt
WHERE tt.ticketFk IS NOT NULL
ORDER BY tt.wagon, tt.shelve;
-- Actualiza el estado de los tickets
CALL collection_setState(vCollectionFk, vStateFk);
-- Aviso para la preparacion previa
INSERT INTO ticketDown(ticketFk, collectionFk)
SELECT tc.ticketFk, tc.collectionFk
FROM ticketCollection tc
WHERE tc.collectionFk = vCollectionFk;
CALL sales_mergeByCollection(vCollectionFk);
UPDATE `collection` c
JOIN (
SELECT COUNT(*) saleTotalCount,
SUM(s.isPicked <> 0) salePickedCount
FROM ticketCollection tc
JOIN sale s ON s.ticketFk = tc.ticketFk
WHERE tc.collectionFk = vCollectionFk
AND s.quantity > 0
) sub
SET c.saleTotalCount = sub.saleTotalCount,
c.salePickedCount = sub.salePickedCount
WHERE c.id = vCollectionFk;
ELSE
DELETE FROM `collection`
WHERE id = vCollectionFk;
SET vCollectionFk = NULL;
END IF;
DO RELEASE_LOCK(vLockName);
DROP TEMPORARY TABLE
tTrain,
tmp.productionBuffer;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `collection_printSticker` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_printSticker`(
vSelf INT,
vLabelCount INT
)
BEGIN
/**
* Prints a yellow label from a collection or a ticket
*
* @param vSelf collection or ticket
* @param vLabelCount number of times the collection has been printed
*/
DECLARE vPrintArgs JSON DEFAULT JSON_OBJECT('collectionOrTicketFk', vSelf);
IF vLabelCount IS NULL THEN
INSERT INTO ticketTrolley
SELECT ticketFk, 1
FROM ticketCollection
WHERE collectionFk = vSelf
ON DUPLICATE KEY UPDATE labelCount = labelCount + 1;
ELSE
SET vPrintArgs = JSON_MERGE_PATCH(vPrintArgs, JSON_OBJECT('labelCount', vLabelCount));
END IF;
CALL report_print(
'LabelCollection',
(SELECT o.labelerFk FROM operator o WHERE o.workerFk = account.myUser_getId()),
account.myUser_getId(),
vPrintArgs,
'high'
);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `collection_setParking` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_setParking`(IN `vCollectionFk` VARCHAR(8), IN `vParkingFk` INT)
proc: BEGIN
/**
* Aparca una colección en un parking.
*
* @param vCollectionFk Id de la colección
* @param vParkingFk Id del parking
*/
REPLACE vn.ticketParking(ticketFk, parkingFk)
SELECT tc.ticketFk, vParkingFk
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `collection_setState` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_setState`(vSelf INT, vStateCode VARCHAR(255) COLLATE utf8_general_ci)
BEGIN
/**
* Modifica el estado de los tickets de una colección.
*
* @param vSelf el id del colección
* @param vStateCode estado a modificar de los tickets
*/
DECLARE vTicketFk INT;
DECLARE vDone INT DEFAULT FALSE;
DECLARE vCursor CURSOR FOR
SELECT DISTINCT ticketFk
FROM ticketCollection tc
WHERE tc.collectionFk = vSelf;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
OPEN vCursor;
read_loop: LOOP
FETCH vCursor INTO vTicketFk;
IF vDone THEN
LEAVE read_loop;
END IF;
CALL ticket_setState(vTicketFk, vStateCode);
END LOOP;
CLOSE vCursor;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `company_getFiscaldata` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `company_getFiscaldata`(workerFk INT)
BEGIN
DECLARE vCompanyFk INT;
SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk)
INTO vCompanyFk
FROM vn.routeConfig rc
LEFT JOIN userConfig uc ON uc.userFk = workerFk;
SELECT
s.name AS name ,
s.NIF AS nif ,
s.street AS street ,
s.city AS city ,
s.postCode AS postCode
FROM vn.company c
JOIN vn.worker w ON w.id = c.workerManagerFk
JOIN vn.supplier s ON s.id = c.id
WHERE c.id = vCompanyFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `company_getSuppliersDebt` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `company_getSuppliersDebt`(vSelf INT, vMonthsAgo INT)
BEGIN
/**
* Generates a temporary table containing outstanding payments to suppliers.
*
* @param vSelf company id
* @param vMonthAgo time interval to be consulted
*/
DECLARE vStartingDate DATETIME DEFAULT TIMESTAMPADD (MONTH,- vMonthsAgo,util.VN_CURDATE());
DECLARE vCurrencyEuroFk INT;
DECLARE vStartDate DATE;
DECLARE vInvalidBalances DOUBLE;
SELECT dated, invalidBalances INTO vStartDate, vInvalidBalances FROM supplierDebtConfig;
SELECT id INTO vCurrencyEuroFk FROM currency WHERE code = 'EUR';
DROP TEMPORARY TABLE IF EXISTS tOpeningBalances;
CREATE TEMPORARY TABLE tOpeningBalances (
supplierFk INT NOT NULL,
companyFk INT NOT NULL,
openingBalances DOUBLE NOT NULL,
closingBalances DOUBLE NOT NULL,
currencyFk INT NOT NULL,
PRIMARY KEY (supplierFk, companyFk, currencyFk)
) ENGINE = MEMORY;
-- Calculates the opening and closing balance for each supplier
INSERT INTO tOpeningBalances
SELECT supplierFk,
companyFk,
SUM(amount * isBeforeStarting) AS openingBalances,
SUM(amount) closingBalances,
currencyFk
FROM (
SELECT p.supplierFk,
p.companyFk,
IF (p.currencyFk = vCurrencyEuroFk, p.amount, p.divisa) AS amount,
p.dueDated < vStartingDate isBeforeStarting,
p.currencyFk
FROM payment p
WHERE p.received > vStartDate
AND p.companyFk = vSelf
UNION ALL
SELECT r.supplierFk,
r.companyFk,
- IF (r.currencyFk = vCurrencyEuroFk, rv.amount, rv.foreignValue) AS Total,
rv.dueDated < vStartingDate isBeforeStarting,
r.currencyFk
FROM invoiceIn r
INNER JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk
WHERE r.issued > vStartDate
AND r.isBooked
AND r.companyFk = vSelf
) sub GROUP BY companyFk, supplierFk, currencyFk;
DROP TEMPORARY TABLE IF EXISTS tPendingDuedates;
CREATE TEMPORARY TABLE tPendingDuedates (
id INT auto_increment,
expirationId INT,
dated DATE,
supplierFk INT NOT NULL,
companyFk INT NOT NULL,
amount DECIMAL(10, 2) NOT NULL,
currencyFk INT NOT NULL,
pending DECIMAL(10, 2) DEFAULT 0,
balance DECIMAL(10, 2) DEFAULT 0,
endingBalance DECIMAL(10, 2) DEFAULT 0,
isPayment BOOLEAN,
isReconciled BOOLEAN,
PRIMARY KEY (id),
INDEX (supplierFk, companyFk, currencyFk)
) ENGINE = MEMORY;
INSERT INTO tPendingDuedates (
expirationId,
dated,
supplierFk,
companyFk,
amount,
currencyFk,
isPayment,
isReconciled
)SELECT p.id,
p.dueDated,
p.supplierFk,
p.companyFk,
IF (p.currencyFk = vCurrencyEuroFk, p.amount, p.divisa),
p.currencyFk,
TRUE isPayment,
p.isConciliated
FROM payment p
WHERE p.dueDated >= vStartingDate
AND p.companyFk = vSelf
UNION ALL
SELECT r.id,
rv.dueDated,
r.supplierFk,
r.companyFk,
-IF (r.currencyFk = vCurrencyEuroFk, rv.amount, rv.foreignValue),
r.currencyFk,
FALSE isPayment,
TRUE
FROM invoiceIn r
LEFT JOIN tOpeningBalances si ON r.companyFk = si.companyFk
AND r.supplierFk = si.supplierFk
AND r.currencyFk = si.currencyFk
JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk
WHERE rv.dueDated >= vStartingDate
AND (si.closingBalances IS NULL OR si.closingBalances <> 0)
AND r.isBooked
AND r.companyFk = vSelf
ORDER BY supplierFk, companyFk, companyFk, dueDated, isPayment DESC, id;
-- Now, we calculate the outstanding amount for each receipt in descending order
SET @risk := 0.0;
SET @supplier := 0.0;
SET @company := 0.0;
SET @moneda := 0.0;
SET @pending := 0.0;
SET @day := util.VN_CURDATE();
UPDATE tPendingDuedates vp
LEFT JOIN tOpeningBalances si ON vp.companyFk = si.companyFk
AND vp.supplierFk = si.supplierFk
AND vp.currencyFk = si.currencyFk
SET vp.balance = @risk := (
IF (
@company <> vp.companyFk
OR @supplier <> vp.supplierFk
OR @moneda <> vp.currencyFk,
IFNULL(si.openingBalances, 0),
@risk
) +
vp.amount
),
-- if there is a change of company or supplier or currency, the balance is reset
vp.pending = @pending := IF (
@company <> vp.companyFk
OR @supplier <> vp.supplierFk
OR @moneda <> vp.currencyFk
OR @day <> vp.dated,
vp.amount * (NOT vp.isPayment),
@pending + vp.amount
),
vp.companyFk = @company := vp.companyFk,
vp.supplierFk = @supplier := vp.supplierFk,
vp.currencyFk = @moneda := vp.currencyFk,
vp.dated = @day := vp.dated,
vp.balance = @risk,
vp.pending = @pending;
CREATE OR REPLACE TEMPORARY TABLE tRowsToDelete ENGINE = MEMORY
SELECT expirationId,
dated,
supplierFk,
companyFk,
currencyFk,
balance
FROM tPendingDuedates
WHERE balance < vInvalidBalances
AND balance > - vInvalidBalances;
DELETE vp.*
FROM tPendingDuedates vp
JOIN tRowsToDelete rd ON (
vp.dated < rd.dated
OR (vp.dated = rd.dated AND vp.expirationId <= rd.expirationId)
)
AND vp.supplierFk = rd.supplierFk
AND vp.companyFk = rd.companyFk
AND vp.currencyFk = rd.currencyFk
WHERE NOT vp.isPayment;
SELECT vp.expirationId,
vp.dated,
vp.supplierFk,
vp.companyFk,
vp.currencyFk,
vp.amount,
vp.pending,
vp.balance,
s.payMethodFk,
vp.isPayment,
vp.isReconciled,
vp.endingBalance,
cr.amount clientRiskAmount,
co.CEE
FROM tPendingDuedates vp
LEFT JOIN supplier s ON s.id = vp.supplierFk
LEFT JOIN client c ON c.fi = s.nif
LEFT JOIN clientRisk cr ON cr.clientFk = c.id
AND cr.companyFk = vp.companyFk
LEFT JOIN supplierAccount sa ON sa.supplierFk = s.id
LEFT JOIN bankEntity be ON be.id = sa.bankEntityFk
LEFT JOIN country co ON co.id = be.countryFk;
DROP TEMPORARY TABLE tOpeningBalances;
DROP TEMPORARY TABLE tPendingDuedates;
DROP TEMPORARY TABLE tRowsToDelete;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `comparative_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `comparative_add`()
BEGIN
/**
* Inserts sales records less than one month old in comparative.
*/
DECLARE vMaxPeriod INT;
DECLARE vPeriod INT;
DECLARE vWeek INT;
DECLARE vConfigPeriod INT;
DECLARE vConfigWeek INT;
SELECT period, week INTO vConfigPeriod, vConfigWeek
FROM comparativeAddConfig;
SELECT IFNULL(MAX(timePeriod), 0) INTO vMaxPeriod
FROM comparative;
SELECT period - vConfigPeriod,
week
INTO vPeriod,
vWeek
FROM `time`
WHERE dated = util.VN_CURDATE();
IF vMaxPeriod < vPeriod AND vWeek > vConfigWeek THEN
DELETE FROM comparative WHERE timePeriod BETWEEN vMaxPeriod AND vPeriod;
INSERT INTO comparative(
timePeriod,
itemFk,
warehouseFk,
quantity,
price,
countryFk
)
SELECT tm.period,
s.itemFk,
t.warehouseFk,
sum(s.quantity),
sum(v.importe),
p.countryFk
FROM bs.ventas v
JOIN time tm ON tm.dated = v.fecha
JOIN sale s ON s.id = v.Id_Movimiento
JOIN itemType tp ON tp.id = v.tipo_id
JOIN itemCategory ic ON ic.id = tp.categoryFk
JOIN ticket t ON t.id = s.ticketFk
JOIN client c ON c.id = t.clientFk
JOIN warehouse w ON w.id = t.warehouseFk
JOIN address ad ON ad.id = t.addressFk
LEFT JOIN province p ON p.id = ad.provinceFk
WHERE tm.period BETWEEN vMaxPeriod AND vPeriod
AND c.typeFk <> 'loses'
AND NOT w.code = 'inv'
GROUP BY p.countryFk, s.itemFk, tm.period, t.warehouseFk;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `confection_controlSource` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `confection_controlSource`(
vDated DATE,
vScopeDays INT,
vMaxAlertLevel INT,
vWarehouseFk INT
)
BEGIN
/**
* Obtiene la información para el control de confección,
* ya sean tickets y/o entradas.
*
* @param vDated Fecha a calcular
* @param vScopeDays Número de días desde hoy en adelante que entran en el cálculo.
* @param vMaxAlertLevel Id nivel de alerta
* @param vWarehouseFk Id de almacén
*/
DECLARE vEndingDate DATETIME DEFAULT util.dayEnd(vDated) + INTERVAL vScopeDays DAY;
SELECT t.shipped,
t.id ticketFk,
s.id saleFk,
s.quantity,
s.concept,
ABS(s.reserved) isReserved,
i.category,
it.name itemType,
t.nickname,
wh.name warehouse,
t.warehouseFk warehouseFk,
a.provinceFk,
am.agencyFk,
ct.description,
stock.visible,
stock.available
FROM ticket t
JOIN agencyMode am ON am.id = t.agencyModeFk
JOIN warehouse wh ON wh.id = t.warehouseFk
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
JOIN itemType it ON it.id = i.typeFk
JOIN confectionType ct ON ct.id = it.making
JOIN `address` a on a.id = t.addressFk
LEFT JOIN ticketState tls on tls.ticketFk = t.id
LEFT JOIN
(
SELECT item_id,
SUM(visible) visible,
SUM(available) available
FROM (
SELECT a.item_id,
0 visible,
a.available
FROM cache.cache_calc cc
LEFT JOIN cache.available a ON a.calc_id = cc.id
WHERE cc.cache_id IN ('visible', 'available')
AND cc.params = CONCAT(vWarehouseFk, "/", util.VN_CURDATE())
UNION ALL
SELECT v.item_id,
v.visible,
0
FROM cache.cache_calc cc
LEFT JOIN cache.visible v ON v.calc_id = cc.id
WHERE cc.cacheName IN ('visible', 'available')
AND cc.params = vWarehouseFk
) sub
GROUP BY item_id
) stock ON stock.item_id = s.itemFk
WHERE it.making
AND tls.alertLevel < vMaxAlertLevel
AND wh.hasConfectionTeam
AND t.shipped BETWEEN vDated AND vEndingDate
AND s.quantity > 0
UNION ALL
SELECT tr.shipped,
e.id,
NULL,
b.quantity,
i.name,
NULL,
i.category,
NULL,
whi.name,
who.name,
NULL,
NULL,
NULL,
ct.description,
NULL,
NULL
FROM buy b
JOIN `entry` e ON e.id = b.entryFk
JOIN travel tr ON tr.id = e.travelFk
JOIN warehouse whi ON whi.id = tr.warehouseInFk
JOIN warehouse who ON who.id = tr.warehouseOutFk
JOIN item i ON i.id = b.itemFk
JOIN itemType it ON it.id = i.typeFk
JOIN confectionType ct ON ct.id = it.making
WHERE who.hasConfectionTeam
AND it.making
AND tr.shipped BETWEEN vDated AND vEndingDate;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `conveyorExpedition_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `conveyorExpedition_Add`(vStarted DATETIME, vEnded DATETIME)
BEGIN
DECLARE startingMinute INT;
TRUNCATE vn.conveyorExpedition;
INSERT INTO vn.conveyorExpedition( expeditionFk,
created,
length,
width,
height,
routeFk,
productionMinute,
truck,
criterion,
conveyorBuildingClassFk)
SELECT e.id,
e.created,
10 * p.depth as depth,
10 * p.width as width,
10 * p.height as height,
IFNULL(t.routeFk,am.agencyFk) routeFk,
hour(e.created) * 60 + minute(e.created),
IFNULL(et.description , a.name),
IFNULL(t.routeFk,am.agencyFk) criterion,
IFNULL(p.conveyorBuildingClassFk , pc.defaultConveyorBuildingClass)
FROM vn.expedition e
JOIN vn.ticket t ON t.id = e.ticketFk
JOIN vn.packaging p ON p.id = e.packagingFk
LEFT JOIN vn.zone z ON z.id = t.zoneFk
LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
LEFT JOIN vn.agency a ON a.id = am.agencyFk
LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk
LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk
JOIN vn.packagingConfig pc
WHERE t.warehouseFk IN (60,1,44)
AND e.created BETWEEN vStarted AND vEnded
AND p.height < 140
AND p.width < 60
AND p.depth < 125;
SELECT MIN(productionMinute) INTO startingMinute
FROM vn.conveyorExpedition ce ;
UPDATE vn.conveyorExpedition
SET productionMinute = productionMinute - startingMinute;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `creditInsurance_getRisk` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `creditInsurance_getRisk`()
BEGIN
/**
* Devuelve el riesgo de los clientes que estan asegurados
*/
CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt
(PRIMARY KEY (clientFk))
ENGINE = MEMORY
SELECT * FROM (
SELECT cc.client clientFk, ci.grade
FROM creditClassification cc
JOIN creditInsurance ci ON cc.id = ci.creditClassification
WHERE dateEnd IS NULL
ORDER BY ci.creationDate DESC
LIMIT 10000000000000000000) t1
GROUP BY clientFk;
CALL client_getDebt(util.VN_CURDATE());
SELECT c.id,
c.name,
c.credit clientCredit,
c.creditInsurance solunion,
CAST(r.risk AS DECIMAL(10,0)) risk,
CAST(c.creditInsurance - r.risk AS DECIMAL(10,0)) riskAlive,
cac.invoiced billedAnnually,
c.dueDay,
cgd.grade,
c2.country
FROM tmp.clientGetDebt cgd
LEFT JOIN tmp.risk r ON r.clientFk = cgd.clientFk
JOIN client c ON c.id = cgd.clientFk
JOIN bs.clientAnnualConsumption cac ON c.id = cac.clientFk
JOIN country c2 ON c2.id = c.countryFk
GROUP BY c.id;
DROP TEMPORARY TABLE
tmp.risk,
tmp.clientGetDebt;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `creditRecovery` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `creditRecovery`()
BEGIN
/**
* Actualiza el crédito de los clientes
*/
DECLARE EXIT HANDLER FOR SQLSTATE '45000'
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
UPDATE `client` c
JOIN payMethod pm ON pm.id = c.payMethodFk
SET c.credit = 0
WHERE pm.`code` = 'card';
DROP TEMPORARY TABLE IF EXISTS tCreditClients;
CREATE TEMPORARY TABLE tCreditClients
SELECT clientFk, IF(credit > recovery, credit - recovery, 0) newCredit
FROM (
SELECT r.clientFk,
r.amount recovery,
(sub2.created + INTERVAL r.period DAY) deadLine,
sub2.amount credit
FROM recovery r
JOIN (
SELECT clientFk, amount, created
FROM (
SELECT clientFk, amount, created
FROM clientCredit
ORDER BY created DESC
LIMIT 10000000000000000000
) sub
GROUP BY clientFk
) sub2 ON sub2.clientFk = r.clientFk
WHERE r.finished IS NULL OR r.finished >= util.VN_CURDATE()
GROUP BY r.clientFk
HAVING deadLine <= util.VN_CURDATE()
) sub3
WHERE credit > 0;
UPDATE client c
JOIN tCreditClients cc ON cc.clientFk = c.id
SET c.credit = newCredit;
DROP TEMPORARY TABLE tCreditClients;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `department_getHasMistake` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `department_getHasMistake`()
BEGIN
/**
* Obtiene los sectores a los cuales les ponemos errores
*
*/
SELECT id, name
FROM department
WHERE hasToMistake <> 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `deviceLog_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `deviceLog_add`(vWorkerFk INT, vAppName VARCHAR(45), vAppVersion VARCHAR(45), vAndroid_id VARCHAR(64))
BEGIN
/**
* Inserta registro en tabla devicelog el log del usuario conectado.
*
* @param vAppName es el nombre de la app
* @param vAppVersion es la versión de la app
* @param vAndroid_id es el android_id del dispositivo que se ha logueado
*/
INSERT INTO deviceLog (userFK, nameApp, versionApp, android_id)
VALUES(vWorkerFk, vAppName, vAppVersion, vAndroid_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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `deviceProductionUser_exists` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `deviceProductionUser_exists`(vUserFk INT)
BEGIN
/* SELECT COUNT(*) AS UserExists
FROM vn.deviceProductionUser dpu
WHERE dpu.userFk = vUserFk;*/
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `deviceProductionUser_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `deviceProductionUser_getWorker`(vAndroid_id VARCHAR(64))
BEGIN
/**
* Selecciona si hay registrado un device con un android_id
*
* @param vAndroid_id el número android_id del dispositivo
*/
SELECT account.user_getNameFromId(dpu.userFk)
FROM deviceProductionUser dpu
JOIN deviceProduction dp ON dpu.deviceProductionFk = dp.id
WHERE dp.android_id = vAndroid_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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `deviceProduction_getnameDevice` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `deviceProduction_getnameDevice`(vAndroid_id VARCHAR(64))
BEGIN
/**
* Selecciona el id del dispositivo que corresponde al vAndroid_id.
*
* @param vAndroid_id el número android_id del dispositivo
*/
SELECT dp.id
FROM deviceProduction dp
WHERE dp.android_id = vAndroid_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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `device_checkLogin` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `device_checkLogin`(vUserFk INT, vAndroidID VARCHAR(50))
BEGIN
/*
* Comprueba si está registrado el dispositivo mediante su androidId
*
* @param vUSerFk el id del user
* @param vAndroidID es el identificador android_id del dispositivo
*/
DECLARE vIsAuthorized BOOL DEFAULT TRUE;
DECLARE vIsDepartment BOOL;
DECLARE vIsAllUsersAllowed BOOL;
DECLARE vMessage VARCHAR(200);
SELECT dpc.isAllUsersallowed INTO vIsAllUsersAllowed
FROM vn.deviceProductionConfig dpc;
IF NOT vIsAllUsersAllowed THEN
SELECT COUNT(*) INTO vIsDepartment
FROM vn.workerDepartment dp
JOIN department d ON d.id = dp.departmentFk
WHERE dp.workerFk = vUserFk AND d.hasToCheckLogin;
IF vIsDepartment THEN
SELECT COUNT(*) INTO vIsAuthorized
FROM vn.deviceProductionUser dpu
JOIN vn.deviceProduction dp ON dp.id = dpu.deviceProductionFk
WHERE dpu.userFk = vUserFk
AND dp.android_id = vAndroidID;
IF NOT vIsAuthorized THEN
SET vMessage = 'Usuario no autorizado';
END IF;
END IF;
END IF;
SELECT vIsAuthorized,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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `duaInvoiceInBooking`(vDuaFk INT)
BEGIN
/**
* Genera el asiento de un DUA y marca las entradas como confirmadas
*
* @param vDuaFk Id del dua a recalcular
*/
DECLARE done BOOL DEFAULT FALSE;
DECLARE vInvoiceFk INT;
DECLARE vASIEN BIGINT DEFAULT 0;
DECLARE vCounter INT DEFAULT 0;
DECLARE rs CURSOR FOR
SELECT DISTINCT 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.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.isBooked = TRUE,
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 invoiceIn_booking(vInvoiceFk);
IF vCounter > 0 OR vASIEN > 0 THEN
UPDATE XDiario x
JOIN ledgerConfig lc ON lc.lastBookEntry = x.ASIEN
SET x.ASIEN = vASIEN;
ELSE
SELECT lastBookEntry INTO vASIEN FROM ledgerConfig;
END IF;
SET vCounter = vCounter + 1;
FETCH rs INTO vInvoiceFk;
END WHILE;
CLOSE rs;
UPDATE dua
SET ASIEN = vASIEN
WHERE id = vDuaFk;
UPDATE invoiceIn ii
JOIN duaInvoiceIn dii ON dii.invoiceInFk = ii.id
SET ii.isBooked = TRUE
WHERE dii.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `duaParcialMake`(vDuaFk INT)
BEGIN
DECLARE vNewDuaFk INT;
INSERT INTO dua(companyFk)
SELECT 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `duaTaxBooking`(vDuaFk INT)
BEGIN
DECLARE vBookNumber INT;
DECLARE vBookDated DATE;
DECLARE vDiff DECIMAL(10,2);
DECLARE vApunte BIGINT;
SELECT ASIEN, IFNULL(bookEntried, util.VN_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(dt.base * dt.rate / 100) EUROHABER,
'R',
d.companyFk,
vDuaFk,
vDuaFk
FROM duaTax dt
JOIN dua d ON d.id = dt.duaFk
WHERE dt.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(c.code = 'ES', 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
LIMIT 10000000000000000000
) tba
GROUP BY rate
) tr ON tr.rate = dt.rate
JOIN supplier s ON s.id = d.companyFk
JOIN country c ON c.id = s.countryFk
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `duaTax_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `duaTax_doRecalc`(vDuaFk INT)
BEGIN
/**
* Borra los valores de duaTax y los vuelve a crear en base a la tabla duaEntry
*
* @param vDuaFk Id del dua a recalcular
*/
DELETE FROM duaTax
WHERE duaFk = vDuaFk;
INSERT INTO duaTax(duaFk, taxClassFk, base)
SELECT vDuaFk, taxClassFk, SUM(sub.totalBase)
FROM intrastat ist
JOIN
(SELECT i.intrastatFk,
CAST(SUM(b.quantity *
b.buyingValue *
de.customsValue /
de.value)
* di.totalAmount /
bi.totalAmount AS DECIMAL(10,2)
) totalBase
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)
) totalAmount
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
) bi ON bi.intrastatFk = i.intrastatFk
JOIN(
SELECT intrastatFk, SUM(amount) totalAmount
FROM duaIntrastat
WHERE duaFk = vDuaFk
GROUP BY intrastatFK
) di ON di.intrastatFk = i.intrastatFk
WHERE de.duaFk = vDuaFk
GROUP BY i.intrastatFk
HAVING totalBase
)sub ON ist.id = sub.intrastatFk
GROUP BY ist.taxClassFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ediTables_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ediTables_Update`()
BEGIN
INSERT IGNORE INTO vn.genus(name)
SELECT latin_genus_name
FROM edi.genus ;
INSERT IGNORE INTO vn.specie(name)
SELECT LCASE(latin_species_name)
FROM edi.specie ;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ektEntryAssign_setEntry` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ektEntryAssign_setEntry`()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE vEntryFk INT;
DECLARE vTravelFk INT;
DECLARE vId INT;
DECLARE vLanded DATE DEFAULT util.VN_CURDATE();
DECLARE cur1 CURSOR FOR SELECT id FROM vn.ektEntryAssign;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
IF HOUR(util.VN_NOW()) > 12 THEN
SET vLanded = TIMESTAMPADD(DAY,1,vLanded);
END IF;
OPEN cur1;
read_loop: LOOP
SET done = FALSE;
SET vEntryFk = 0;
FETCH cur1 INTO vId;
IF done THEN
LEAVE read_loop;
END IF;
SELECT IFNULL(e.id,0) INTO vEntryFk
FROM vn.entry e
JOIN vn.travel tr ON tr.id = e.travelFk
JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk
AND ea.warehouseInFk = tr.warehouseInFk
AND ea.agencyModeFk = tr.agencyModeFk
AND ea.supplierFk = e.supplierFk
WHERE ea.id = vId
AND tr.landed = vLanded
LIMIT 1;
IF NOT vEntryFk THEN
SELECT IFNULL(e.id,0) INTO vEntryFk
FROM vn.entry e
JOIN vn.travel tr ON tr.id = e.travelFk
JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk
AND ea.warehouseInFk = tr.warehouseInFk
AND ea.agencyModeFk = tr.agencyModeFk
WHERE ea.id = vId
AND tr.landed = vLanded
AND ea.supplierFk IS NULL
LIMIT 1;
END IF;
IF NOT vEntryFk THEN
SET vTravelFk = 0;
SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk
FROM vn.travel tr
JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk
AND ea.warehouseInFk = tr.warehouseInFk
AND ea.agencyModeFk = tr.agencyModeFk
WHERE ea.id = vId
AND tr.landed = vLanded;
IF NOT vTravelFk THEN
INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk)
SELECT vLanded, vLanded, warehouseInFk, warehouseOutFk, agencyModeFk
FROM vn.ektEntryAssign
WHERE id = vId;
SELECT MAX(tr.id) INTO vTravelFk
FROM vn.travel tr
JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk
AND ea.warehouseInFk = tr.warehouseInFk
AND ea.agencyModeFk = tr.agencyModeFk
WHERE ea.id = vId
AND tr.landed = vLanded;
END IF;
INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk)
SELECT vTravelFk, IFNULL(ea.supplierFk,s.id), c.id, cu.id
FROM vn.supplier s
JOIN vn.company c ON c.code = 'VNL'
JOIN vn.currency cu ON cu.code = 'EUR'
JOIN vn.ektEntryAssign ea ON ea.id = vId
WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN';
SELECT MAX(id) INTO vEntryFk
FROM vn.entry
WHERE travelFk = vTravelFk;
END IF;
UPDATE vn.ektEntryAssign
SET entryFk = vEntryFk
WHERE id = vId;
END LOOP;
CLOSE cur1;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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(util.VN_NOW(), '%Y-%m-%d %H:00:00'),
`activeTime` = vActiveTime,
`consumption` = CAST(IFNULL((vConsumption / 3600) * vActiveTime, 0) AS DECIMAL(10,2))
ON DUPLICATE KEY UPDATE
`activeTime` = `activeTime` + vActiveTime,
`consumption` = `consumption` + CAST(VALUES(`consumption`) AS DECIMAL(10,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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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, agencyModeFk, ref, isDelivered, isReceived)
SELECT LEAST(shipped, vDated), vDated, warehouseInFk, warehouseOutFk, agencyModeFk, CONCAT(account.myUser_getName(),' ', 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entryWithItem` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entryWithItem`(vShipmentWarehouse INT, vLandingWarehouse INT,vSale INT, vVolume INT, netCost DECIMAL(10,2), vInOutDate DATE)
BEGIN
DECLARE vTravel INT;
DECLARE vEntry INT;
DECLARE vBucket VARCHAR(10);
DECLARE vSupplierFk INT;
SET vSupplierFk = IF (vLandingWarehouse = 1, 850, 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.agencyModeFk IS NULL 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)
VALUES (vInOutDate, vInOutDate, vLandingWarehouse, vShipmentWarehouse);
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;
SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1;
END IF;
INSERT INTO buy(itemFk,quantity, entryFk, packagingFk, packing, stickers, buyingValue, price2, price3)
SELECT itemFk,
quantity,
vEntry,
vBucket,
1 packing,
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entry_checkBooked` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_checkBooked`(
vSelf INT
)
BEGIN
/**
* Comprueba si una entrada está contabilizada,
* y si lo está retorna un throw.
*
* @param vSelf Id de entrada
*/
DECLARE vIsBooked BOOL;
SELECT isBooked INTO vIsBooked
FROM `entry`
WHERE id = vSelf;
IF vIsBooked AND NOT IFNULL(@isModeInventory, FALSE) THEN
CALL util.throw('Entry is already booked');
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entry_checkPackaging` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_checkPackaging`(vEntryFk INT)
BEGIN
/**
* Comprueba que los campos package y packaging no sean nulos
*
* @param vEntryFk Id de entrada
*/
DECLARE vpackageOrPackingNull INT;
SELECT count(*) INTO vpackageOrPackingNull
FROM buy b
WHERE b.entryFk = vEntryFk
AND (b.packing IS NULL OR b.packagingFk IS NULL);
IF vpackageOrPackingNull THEN
CALL util.throw("packageOrPackingNull");
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entry_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_clone`(vSelf INT)
BEGIN
/**
* clones an entry.
*
* @param vSelf The entry id
*/
DECLARE vNewEntryFk INT;
START TRANSACTION;
CALL entry_cloneHeader(vSelf, vNewEntryFk, NULL);
CALL entry_copyBuys(vSelf, vNewEntryFk);
COMMIT;
SELECT vNewEntryFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entry_cloneHeader` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_cloneHeader`(
vSelf INT,
OUT vNewEntryFk INT,
vTravelFk INT
)
BEGIN
/**
* Clones an entry header.
*
* @param vSelf The entry id
* @param vTravelFk Travel for the new entry or %NULL to use the source entry travel
* @param vNewEntryFk The new entry id
*/
INSERT INTO entry(
travelFk,
supplierFk,
dated,
isExcludedFromAvailable,
isRaid,
commission,
currencyFk,
companyFk,
clonedFrom,
typeFk
)
SELECT IFNULL(vTravelFk, travelFk),
supplierFk,
dated,
isExcludedFromAvailable,
isRaid,
commission,
currencyFk,
companyFk,
vSelf,
typeFk
FROM entry
WHERE id = vSelf;
SET vNewEntryFk = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entry_cloneWithoutBuy` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_cloneWithoutBuy`(vSelf INT, OUT vNewEntryFk INT)
BEGIN
/**
* Clona una entrada sin compras
*
* @param vSelf Identificador de vn.entry
* @param vNewEntryFk Identificador de la nueva entrada
*/
START TRANSACTION;
CALL entry_cloneHeader(vSelf, vNewEntryFk, NULL);
UPDATE entry d JOIN entry s ON s.id = vSelf
SET d.`reference` = s.`reference`,
d.loadPriority = s.loadPriority
WHERE d.id = vNewEntryFk;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entry_copyBuys` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_copyBuys`(vSelf INT, vCopyTo INT)
BEGIN
/**
* Copies an entry buys to another buy.
*
* @param vSelf The entry id
* @param vCopyTo The destination entry id
*/
INSERT INTO buy(
entryFk,
itemFk,
quantity,
buyingValue,
freightValue,
isIgnored,
stickers,
packing,
`grouping`,
groupingMode,
containerFk,
comissionValue,
packageValue,
packagingFk,
price1,
price2,
price3,
minPrice,
isChecked,
location,
weight,
itemOriginalFk
)
SELECT vCopyTo,
itemFk,
quantity,
buyingValue,
freightValue,
isIgnored,
stickers,
packing,
`grouping`,
groupingMode,
containerFk,
comissionValue,
packageValue,
packagingFk,
price1,
price2,
price3,
minPrice,
isChecked,
location,
weight,
itemOriginalFk
FROM buy
WHERE entryFk = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entry_fixMisfit` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_fixMisfit`(
vSelf INT
)
BEGIN
/**
* Arregla el descuadre de una entrada, agregando registros en vn.buy
* para compensar la diferencia * entre las etiquetas impresas y las esperadas
*
* @param vSelf Identificador de la entrada
*/
INSERT INTO vn.buy(entryFk, itemFk)
SELECT vSelf, i.id
FROM vn.item i
WHERE i.description = 'MISFIT'
LIMIT 1;
INSERT INTO vn.buy(
entryFk,
itemFk,
quantity,
buyingValue,
freightValue,
isIgnored,
stickers,
packing,
`grouping`,
groupingMode,
containerFk,
comissionValue,
packageValue,
location,
packagingFk,
price1,
price2,
price3,
minPrice,
weight)
SELECT vSelf,
itemFk,
SUM(CAST(printedStickers AS INT) - stickers) * packing quantity,
buyingValue,
freightValue,
TRUE isIgnored,
CAST(printedStickers AS INT) - stickers,
packing,
`grouping`,
groupingMode,
containerFk,
comissionValue,
packageValue,
location,
packagingFk,
price1,
price2,
price3,
minPrice,
weight
FROM buy b
WHERE b.entryFk = vSelf
AND b.printedStickers <> b.stickers
GROUP BY itemFk
HAVING 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 */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_getRate`(vSelf INT)
BEGIN
/**
* Prepara una tabla con las tarifas aplicables en funcion de la fecha
* y el almacén
*
* @param vSelf Id de la tabla entry
* @return tmp.rate (rate0, rate1, rate2, rate3)
*/
DECLARE vDated DATE;
DECLARE vWarehouseFk INT;
SELECT t.landed, t.warehouseInFk INTO vDated, vWarehouseFk
FROM entry e
JOIN travel t ON t.id = e.travelFk
WHERE e.id = vSelf;
CALL rate_getPrices(vDated, 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entry_getTransfer` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_getTransfer`(
vSelf INT
)
BEGIN
/**
* Retorna los artículos trasladables a partir de una entrada.
*
* @param vSelf Id de entrada
*/
DECLARE vDateShipped DATE;
DECLARE vDateLanded DATE;
DECLARE vWarehouseIn INT;
DECLARE vWarehouseOut INT;
DECLARE vCalcVisible INT;
DECLARE vInventoryDate DATE DEFAULT getInventoryDate();
SELECT shipped, landed, warehouseInFk, warehouseOutFk
INTO vDateShipped, vDateLanded, vWarehouseIn, vWarehouseOut
FROM travel t
JOIN entry e ON e.travelFk = t.id
WHERE e.id = vSelf;
CALL rate_getPrices(vDateShipped, vWarehouseIn);
-- Traslado en almacen origen
CREATE OR REPLACE TEMPORARY TABLE tBuy
(PRIMARY KEY (itemFk), INDEX(buyFk))
ENGINE = MEMORY
SELECT *
FROM (
SELECT b.itemFk, b.id buyFk
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed BETWEEN vInventoryDate AND vDateShipped
AND NOT b.isIgnored
AND b.price2 >= 0
ORDER BY (vWarehouseOut = t.warehouseInFk) DESC, t.landed DESC
LIMIT 10000000000000000000
) sub
GROUP BY itemFk;
IF vDateShipped >= util.VN_CURDATE() THEN
CALL `cache`.visible_refresh(vCalcVisible, TRUE, vWarehouseOut);
CREATE OR REPLACE TEMPORARY TABLE tItem (
`itemFk` int(10) unsigned NOT NULL,
`visible` int(11) NOT NULL DEFAULT 0,
`available` int(11) NOT NULL DEFAULT 0,
`visibleLanding` int(11) NOT NULL DEFAULT 0,
`availableLanding` int(11) NOT NULL DEFAULT 0,
UNIQUE INDEX i USING HASH (itemFk)
) ENGINE = MEMORY;
INSERT INTO tItem(itemFk, visible)
SELECT item_id itemFk, visible
FROM `cache`.visible
WHERE calc_id = vCalcVisible
AND visible;
CALL `cache`.visible_refresh(vCalcVisible, TRUE, vWarehouseIn);
INSERT INTO tItem(itemFk, visibleLanding)
SELECT item_id, `visible`
FROM `cache`.`visible` v
WHERE v.calc_id = vCalcVisible
AND v.`visible`
ON DUPLICATE KEY UPDATE visibleLanding = v.`visible`;
CALL available_traslate(vWarehouseOut, vDateShipped, NULL);
INSERT INTO tItem(itemFk, available)
SELECT a.item_id, a.available
FROM tmp.availableTraslate a
WHERE a.available
ON DUPLICATE KEY UPDATE available = a.available;
CALL available_traslate(vWarehouseIn, vDateLanded, vWarehouseOut);
INSERT INTO tItem(itemFk, availableLanding)
SELECT a.item_id, a.available
FROM tmp.availableTraslate a
WHERE a.available
ON DUPLICATE KEY UPDATE availableLanding = a.available;
ELSE
CALL item_getStock(vWarehouseOut, vDateShipped, NULL);
CREATE OR REPLACE TEMPORARY TABLE tItem
(UNIQUE INDEX i USING HASH (itemFk))
ENGINE = MEMORY
SELECT itemFk,
`visible`,
available,
0 visibleLanding,
0 availableLanding
FROM tmp.itemList;
END IF;
CALL buyUltimateFromInterval(vWarehouseIn,vInventoryDate, vDateLanded);
CREATE OR REPLACE TEMPORARY TABLE tTransfer
ENGINE = MEMORY
SELECT it.code `type`,
it.categoryFk,
i.typeFk,
i.id itemFk,
i.name item,
i.`size`,
i.category,
i.inkFk,
o.code originCode,
b2.quantity,
i.stems,
CAST(ti.visible AS DECIMAL(10,0)) vis1,
CAST(ti.available AS DECIMAL(10,0)) ava1,
CAST(ti.visibleLanding AS DECIMAL(10,0)) vis2,
CAST(ti.availableLanding AS DECIMAL(10,0)) ava2,
COALESCE(b2.`grouping`, b.`grouping`) `grouping`,
COALESCE(b2.packing, b.packing) packing,
COALESCE(b3.groupingMode, b2.groupingMode, b.groupingMode) package,
IFNULL(p.name, s.nickname) productor,
TRUE tinta,
b.packagingFk,
b2.id buyFk,
b2.stickers,
b.ektFk,
it.workerFk,
pa.volume,
IFNULL(pa.width, 0) width,
IFNULL(pa.`depth`, 0) `depth`,
IFNULL(pa.height, 0) height,
IFNULL(b.buyingValue, 0) buyingValue,
IFNULL(b.comissionValue, 0) comissionValue,
IFNULL(b.freightValue, 0) freightValue,
am.m3,
e.commission,
pa.isPackageReturnable,
IFNULL(pa2.value, pa.value) `value`,
r.rate3 r3,
r.rate2 r2,
it.promo,
b.`grouping` groupingOrigin,
b.packing packingOrigin,
b.id buyFkOrigin,
pa.returnCost,
b.weight
FROM item i
JOIN tItem ti ON ti.itemFk = i.id
LEFT JOIN producer p ON p.id = i.producerFk
LEFT JOIN itemType it ON it.id = i.typeFk
JOIN itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN origin o ON o.id = i.originFk
LEFT JOIN tBuy lb ON lb.itemFk = i.id
LEFT JOIN buy b ON b.id = lb.buyFk
LEFT JOIN packaging pa ON pa.id = b.packagingFk
LEFT JOIN entry e2 ON e2.id = b.entryFk
LEFT JOIN supplier s ON s.id = e2.supplierFk
LEFT JOIN entry e ON e.id = vSelf
LEFT JOIN travel tr ON tr.id = e.travelFk
LEFT JOIN agencyMode am ON am.id = tr.agencyModeFk
LEFT JOIN buy b2 ON b2.itemFk = i.id
AND b2.entryFk = vSelf
LEFT JOIN packaging pa2 ON pa2.id = b.packagingFk
LEFT JOIN tmp.rate r ON TRUE
LEFT JOIN tmp.buyUltimateFromInterval bufi ON bufi.itemFk = i.id
LEFT JOIN buy b3 ON b3.id = bufi.buyFk
WHERE ic.display
AND NOT e.isRaid
AND (ti.visible OR ti.available)
ORDER BY i.typeFk, i.name, i.id, i.size, i.category, o.name;
CREATE INDEX tIndex USING HASH ON tTransfer (itemFk);
SELECT *,
quantity - MOD(quantity , `grouping`) subQuantity,
MOD(quantity, `grouping`) soll,
ROUND((IF(volume > 0,volume, width * `depth` *
IF(height = 0, `size` + 10, height))) /
packing, 0) cm3,
buyingValue + comissionValue + freightValue cost,
@carriage := ROUND((IF(volume > 0, volume, width * `depth` *
IF(height = 0, `size` + 10, height))) *
m3 / 1000000 / Packing, 3) carriage,
@comission := ROUND((buyingValue + comissionValue + freightValue) *
commission / 100, 3) commission,
ROUND(@packaging := (returnCost + IF(isPackageReturnable, 0, value))
/ packing, 3) packaging,
@cost := IFNULL((buyingValue + comissionValue + freightValue), 0) +
IFNULL(@packaging, 0) +
IFNULL(@carriage, 0) +
IFNULL(@comission, 0) expense,
@rate3 := ROUND(@cost / ( (100 - r3 - promo) / 100), 2) rate3,
ROUND(@rate3 * (1 + ((r2 - r3)/100)), 2) rate2,
FALSE selected
FROM tTransfer;
DROP TEMPORARY TABLE IF EXISTS
tTransfer,
tItem,
tBuy,
tmp.buyUltimateFromInterval,
tmp.rate,
tmp.itemList;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entry_lock` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_lock`(vSelf INT)
BEGIN
/**
* Lock the indicated entry
* @vSelf params entry id
*/
UPDATE `entry`
SET lockerUserFk = account.myUser_getId(),
locked = util.VN_NOW()
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entry_moveNotPrinted` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_moveNotPrinted`(vSelf INT,
vDays INT,
vChangeEntry BOOL,
OUT vNewEntryFk INT)
BEGIN
/**
* Crea una entrada a futuro y divide las lineas de buy de
* la entrada original en función de las etiquetas impresas
*
* @param vSelf Identificador de entry
* @param vDays Número de dias a futuro que se quiere la nueva entrada
* @param vChangeEntry Si se modifica la entrada original
*
* @return vNewEntryFk Identificador de la nueva entrada
*/
DECLARE vNewTravelFk INT;
DECLARE vTravelFk INT;
DECLARE vInvoiceAmountOldEntryFk DECIMAL(10,2);
DECLARE vInvoiceAmountNewEntry DECIMAL(10,2);
DECLARE vIsOrdered BOOL;
DECLARE vIsConfirmed BOOL;
DECLARE vInvoiceNumber VARCHAR(50);
DECLARE vTypeFk VARCHAR(100);
SELECT travelFk, isOrdered, isConfirmed, invoiceNumber, typeFk INTO vTravelFk, vIsOrdered, vIsConfirmed, vInvoiceNumber, vTypeFk
FROM entry
WHERE id = vSelf;
CALL travel_clone(vTravelFk, vDays, vNewTravelFk);
CALL entry_cloneWithoutBuy(vSelf, vNewEntryFk);
UPDATE entry e
SET e.travelFk = vNewTravelFk,
e.evaNotes = CONCAT('No impresas de: ', vSelf, ' ', IFNULL(e.evaNotes,'')),
e.isOrdered = vIsOrdered,
e.isConfirmed = vIsConfirmed,
e.invoiceNumber = vInvoiceNumber,
e.typeFk = vTypeFk
WHERE e.id = vNewEntryFk;
IF vChangeEntry THEN
UPDATE buy b
SET b.entryFk = vNewEntryFk
WHERE b.printedStickers = 0
AND b.entryFk = vSelf;
END IF;
INSERT INTO buy(entryFk,
itemFk,
quantity,
buyingValue,
freightValue,
isIgnored,
stickers,
packing,
`grouping`,
groupingMode,
containerFk,
comissionValue,
packageValue,
packagingFk,
price1,
price2,
price3,
minPrice,
workerFk,
weight,
itemOriginalFk)
SELECT vNewEntryFk,
itemFk,
((stickers - CAST(printedStickers AS INT)) * packing) quantity,
buyingValue,
freightValue,
isIgnored,
(stickers - CAST(printedStickers AS INT)) stickers,
packing,
`grouping`,
groupingMode,
containerFk,
comissionValue,
packageValue,
packagingFk,
price1,
price2,
price3,
minPrice,
workerFk,
weight,
itemOriginalFk
FROM buy b
WHERE b.entryFk = vSelf
AND b.printedStickers != b.stickers;
IF vChangeEntry THEN
UPDATE buy
SET stickers = printedStickers,
quantity = printedStickers * packing
WHERE entryFk = vSelf;
ELSE
INSERT INTO buy(entryFk, itemFk)
SELECT vSelf, i.id
FROM item i
WHERE i.description = 'MISFIT'
LIMIT 1;
INSERT INTO buy(entryFk,
itemFk,
quantity,
buyingValue,
freightValue,
isIgnored,
stickers,
packing,
`grouping`,
groupingMode,
containerFk,
comissionValue,
packageValue,
location,
packagingFk,
price1,
price2,
price3,
minPrice)
SELECT vSelf,
itemFk,
(CAST(printedStickers AS INT) - stickers) * packing quantity,
buyingValue,
freightValue,
TRUE isIgnored,
CAST(printedStickers AS INT) - stickers,
packing,
`grouping`,
groupingMode,
containerFk,
comissionValue,
packageValue,
location,
packagingFk,
price1,
price2,
price3,
minPrice
FROM buy
WHERE entryFk = vSelf
AND printedStickers != stickers;
END IF;
SELECT SUM(IFNULL(b.buyingValue * b.quantity, 0)) INTO vInvoiceAmountOldEntryFk
FROM buy b
WHERE b.entryFk = vSelf;
UPDATE entry e
JOIN buy b ON b.entryFk = e.id
SET e.reference = CONCAT(e.reference,'(1)'),
e.invoiceAmount = vInvoiceAmountOldEntryFk
WHERE e.id = vSelf;
SELECT SUM(IFNULL(b.buyingValue * b.quantity, 0)) INTO vInvoiceAmountNewEntry
FROM buy b
WHERE b.entryFk = vNewEntryFk;
UPDATE entry e
JOIN buy b ON b.entryFk = e.id
SET e.reference = CONCAT(e.reference,'(2)'),
e.invoiceAmount = vInvoiceAmountNewEntry
WHERE e.id = vNewEntryFk;
UPDATE entry
SET gestDocFk = (SELECT gestDocFk FROM entry WHERE id = vSelf LIMIT 1)
WHERE id = vNewEntryFk;
INSERT INTO duaEntry (duaFk, entryFk)
SELECT duaFk, vNewEntryFk FROM duaEntry WHERE entryFk = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entry_notifyChanged` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_notifyChanged`(vSelf INT, vBuyFk INT, vOldValues VARCHAR(512), vNewValues VARCHAR(512))
BEGIN
DECLARE vEmail VARCHAR(255);
DECLARE vFields VARCHAR(100);
DECLARE vMessage TEXT;
SELECT e.mailToNotify INTO vEmail
FROM entryConfig e
LIMIT 1;
SET vFields = CONCAT_WS(',',
'entryFk',
'itemFk',
'quantity',
'price1',
'price2',
'price3'
);
SET vMessage = util.formatTable(vFields, vOldValues, vNewValues);
CALL mail_insert(
vEmail,
NULL,
CONCAT(
'Se ha modificado una línea de la entrada ', vSelf
,' siendo inventario o anterior al mismo'
),
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entry_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_recalc`()
BEGIN
/**
* Comprueba que las ventas creadas entre un rango de fechas tienen componentes
*
* @param vCreatedFrom inicio del rango
* @param vCreatedTo fin del rango
*/
DECLARE v_done BOOL DEFAULT FALSE;
DECLARE vEntryFk INTEGER;
DECLARE vCur CURSOR FOR
SELECT id FROM tmp.recalcEntryCommision;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET v_done = TRUE;
OPEN vCur;
l: LOOP
SET v_done = FALSE;
FETCH vCur INTO vEntryFk;
IF v_done THEN
LEAVE l;
END IF;
CALL buy_recalcPricesByEntry(vEntryFk);
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entry_splitByShelving` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_splitByShelving`(vShelvingFk VARCHAR(3), vFromEntryFk INT, vToEntryFk INT)
BEGIN
/**
* Divide las compras entre dos entradas de acuerdo con lo ubicado en una matr�cula
*
* @param vShelvingFk Identificador de vn.shelving
* @param vFromEntryFk Entrada origen
* @param vToEntryFk Entrada destino
*/
DECLARE vBuyFk INT;
DECLARE vIshStickers INT;
DECLARE vBuyStickers INT;
DECLARE vDone BOOLEAN DEFAULT FALSE;
DECLARE cur CURSOR FOR
SELECT bb.id buyFk,
FLOOR(ish.visible / ish.packing) ishStickers,
bb.stickers buyStickers
FROM vn.itemShelving ish
JOIN (SELECT b.id, b.itemFk, b.stickers
FROM vn.buy b
WHERE b.entryFk = vFromEntryFk
ORDER BY b.stickers DESC
LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk
AND bb.stickers >= FLOOR(ish.visible / ish.packing)
WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci
GROUP BY ish.id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
-- Cantidades de la matrícula que exceden la de las entradas
SELECT ish.itemFk,
i.longName,
FLOOR(ish.visible / ish.packing) AS etiEnMatricula,
bb.stickers etiEnEntrada
FROM vn.itemShelving ish
JOIN vn.item i ON i.id = ish.itemFk
LEFT JOIN (SELECT b.id, b.itemFk, b.stickers
FROM vn.buy b
WHERE b.entryFk = vFromEntryFk
ORDER BY b.stickers DESC
LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk
WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci
AND IFNULL(bb.stickers,0) < FLOOR(ish.visible / ish.packing)
GROUP BY ish.id;
OPEN cur;
read_loop: LOOP
SET vDone = FALSE;
FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers;
IF vDone THEN
LEAVE read_loop;
END IF;
IF vIshStickers = vBuyStickers THEN
UPDATE vn.buy
SET entryFk = vToEntryFk
WHERE id = vBuyFk;
ELSE
UPDATE vn.buy
SET stickers = stickers - vIshStickers,
quantity = stickers * packing
WHERE id = vBuyFk;
INSERT INTO vn.buy(entryFk,
itemFk,
quantity,
buyingValue,
freightValue,
isIgnored,
stickers,
packing,
`grouping`,
groupingMode,
containerFk,
comissionValue,
packageValue,
location,
packagingFk,
price1,
price2,
price3,
minPrice,
workerFk,
isChecked,
isPickedOff,
ektFk,
weight,
deliveryFk,
itemOriginalFk)
SELECT
vToEntryFk,
itemFk,
vIshStickers * packing,
buyingValue,
freightValue,
isIgnored,
vIshStickers,
packing,
`grouping`,
groupingMode,
containerFk,
comissionValue,
packageValue,
location,
packagingFk,
price1,
price2,
price3,
minPrice,
workerFk,
isChecked,
isPickedOff,
ektFk,
weight,
deliveryFk,
itemOriginalFk
FROM vn.buy
WHERE id = vBuyFk;
UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID();
END IF;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entry_splitMisfit` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_splitMisfit`(vSelf INT)
BEGIN
/* Divide una entrada, pasando los registros que ha insertado vn.entry_fixMisfit de la entrada original
* a la nueva
*/
DECLARE vNewEntryFk INT;
DECLARE vBuyFk INT;
SELECT MAX(b.id) INTO vBuyFk
FROM vn.buy b
JOIN vn.item i ON i.id = b.itemFk
WHERE b.entryFk = vSelf
AND i.description = 'MISFIT';
INSERT INTO vn.entry(supplierFk, dated, travelFk, currencyFk, companyFk)
SELECT supplierFk, dated, travelFk, currencyFk, companyFk
FROM vn.entry e
WHERE e.id = vSelf;
SET vNewEntryFk = LAST_INSERT_ID();
UPDATE vn.buy b
SET b.entryFk = vNewEntryFk
WHERE b.entryFk = vSelf
AND b.id > vBuyFk;
SELECT vNewEntryFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entry_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_unlock`(vSelf INT)
BEGIN
/**
* Unlock the indicated entry
* @vSelf params entry id
*/
UPDATE `entry`
SET lockerUserFk = NULL,
locked = NULL
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entry_updateComission` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_updateComission`(vCurrency INT)
BEGIN
/**
* Actualiza la comision de las entradas de hoy a futuro y las recalcula
*
* @param vCurrency id del tipo de moneda(SAR,EUR,USD,GBP,JPY)
*/
DECLARE vCurrencyName VARCHAR(25);
DECLARE vComission INT;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
CREATE OR REPLACE TEMPORARY TABLE tmp.recalcEntryCommision
SELECT e.id
FROM vn.entry e
JOIN vn.travel t ON t.id = e.travelFk
JOIN vn.warehouse w ON w.id = t.warehouseInFk
WHERE t.shipped >= util.VN_CURDATE()
AND e.currencyFk = vCurrency;
SET vComission = currency_getCommission(vCurrency);
UPDATE vn.entry e
JOIN tmp.recalcEntryCommision tmp ON tmp.id = e.id
SET e.commission = vComission;
SELECT `name` INTO vCurrencyName
FROM currency
WHERE id = vCurrency;
CALL entry_recalc();
COMMIT;
SELECT util.notification_send(
'entry-update-comission',
JSON_OBJECT('currencyName', vCurrencyName, 'referenceCurrent', vComission),
NULL
);
DROP TEMPORARY TABLE tmp.recalcEntryCommision;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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,
t.routeFk,
t.packages bultos,
ts.alertLevel,
a.street,
a.city,
a.postalCode,
a.id addressFk,
w.name 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.freightItemFk > 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expeditionPallet_build` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionPallet_build`(IN vExpeditions JSON, IN vArcId INT, IN vWorkerFk INT, OUT vPalletFk INT)
BEGIN
/** Construye un pallet de expediciones.
*
* Primero comprueba si esas expediciones ya pertenecen a otro pallet,
* en cuyo caso actualiza ese pallet.
*
* @param vExpeditions JSON_ARRAY con esta estructura [exp1, exp2, exp3, ...]
* @param vArcId INT Identificador de vn.arcRead
* @param vWorkerFk INT Identificador de vn.worker
* @param out vPalletFk Identificador de vn.expeditionPallet
*/
DECLARE vCounter INT;
DECLARE vExpeditionFk INT;
DECLARE vTruckFk INT;
DECLARE vPrinterFk INT;
DROP TEMPORARY TABLE IF EXISTS tExpedition;
CREATE TEMPORARY TABLE tExpedition
SELECT
e.id expeditionFk,
r.id routeFk,
ep.id palletFk
FROM
vn.expedition e,
vn.route r,
vn.expeditionPallet ep
LIMIT 0;
ALTER TABLE tExpedition ADD PRIMARY KEY (expeditionFk);
SET vCounter = JSON_LENGTH(vExpeditions);
WHILE vCounter DO
SET vCounter = vCounter - 1;
SET vExpeditionFk = JSON_EXTRACT(vExpeditions,CONCAT("$[", vCounter, "]"));
INSERT IGNORE INTO tExpedition(expeditionFk, routeFk, palletFk)
SELECT vExpeditionFk, t.routeFk, es.palletFk
FROM vn.expedition e
LEFT JOIN vn.ticket t ON t.id = e.ticketFk
LEFT JOIN vn.expeditionScan es ON es.expeditionFk = e.id
WHERE e.id = vExpeditionFk;
END WHILE;
SELECT palletFk INTO vPalletFk
FROM (
SELECT palletFk, count(*) n
FROM tExpedition
WHERE palletFk > 0
GROUP BY palletFk
ORDER BY n DESC
LIMIT 100 ) sub
LIMIT 1;
IF vPalletFk IS NULL THEN
SELECT expeditionTruckFk
INTO vTruckFk
FROM (
SELECT rm.expeditionTruckFk, count(*) n
FROM vn.routesMonitor rm
JOIN tExpedition e ON e.routeFk = rm.routeFk
GROUP BY expeditionTruckFk
ORDER BY n DESC
LIMIT 1) sub;
IF vTruckFk IS NULL THEN
CALL util.throw ('TRUCK_NOT_AVAILABLE');
END IF;
INSERT INTO vn.expeditionPallet(truckFk)
VALUES(vTruckFk);
SET vPalletFk = LAST_INSERT_ID();
END IF;
INSERT INTO vn.expeditionScan(expeditionFk, palletFk, workerFk)
SELECT expeditionFk, vPalletFk, vWorkerFk
FROM tExpedition
ON DUPLICATE KEY UPDATE palletFk = vPalletFk, workerFk = vWorkerFk;
SELECT printerFk INTO vPrinterFk
FROM vn.arcRead
WHERE id = vArcId;
CALL vn.report_print(
'LabelPalletExpedition',
vPrinterFk,
account.myUser_getId(),
JSON_OBJECT('palletFk', vPalletFk, 'userFk', account.myUser_getId()),
'high'
);
UPDATE vn.expeditionPallet SET isPrint = TRUE WHERE id = vPalletFk;
DROP TEMPORARY TABLE tExpedition;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expeditionPallet_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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionPallet_Del`(vPalletFk INT)
BEGIN
DELETE FROM vn.expeditionPallet
WHERE id = vPalletFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expeditionPallet_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionPallet_List`(vTruckFk INT)
BEGIN
SELECT ep.id Pallet,
count(DISTINCT t.routeFk) Rutas,
count(DISTINCT e.id) Eti
FROM vn.expeditionPallet ep
LEFT JOIN vn.expeditionScan es ON es.palletFk = ep.id
LEFT JOIN vn.expedition e ON e.id = es.expeditionFk
LEFT JOIN vn.ticket t ON t.id = e.ticketFk
WHERE ep.truckFk = vTruckFk
GROUP BY ep.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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expeditionPallet_printLabel` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionPallet_printLabel`(vSelf INT)
BEGIN
/**
* Calls the report_print procedure and passes it
* the necessary parameters for printing.
*
* @param vSelf expeditioPallet id.
*/
DECLARE vPrinterFk INT;
DECLARE vUserFk INT DEFAULT account.myUser_getId();
SELECT o.labelerFk INTO vPrinterFk
FROM operator o
WHERE o.workerFk = vUserFk;
CALL vn.report_print(
'LabelPalletExpedition',
vPrinterFk,
account.myUser_getId(),
JSON_OBJECT('palletFk', vSelf, 'userFk', vUserFk),
'high'
);
UPDATE vn.expeditionPallet
SET isPrint = TRUE
WHERE id = vSelf;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expeditionPallet_View` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionPallet_View`(vPalletFk INT)
BEGIN
SELECT ep.id Pallet,
t.routeFk Rutas,
count(*) Cajas
FROM vn.expeditionPallet ep
LEFT JOIN vn.expeditionScan es ON es.palletFk = ep.id
LEFT JOIN vn.expedition e ON e.id = es.expeditionFk
LEFT JOIN vn.ticket t ON t.id = e.ticketFk
WHERE ep.id = vPalletFk
GROUP BY t.routeFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expeditionScan_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionScan_Add`(vPalletFk INT, vTruckFk INT)
BEGIN
DECLARE vTotal INT DEFAULT 0;
IF vPalletFk = 0 THEN -- Nuevo pallet
INSERT INTO vn.expeditionPallet(truckFk)
VALUES(vTruckFk);
SELECT LAST_INSERT_ID() INTO vPalletFk;
END IF;
SELECT COUNT(expeditionFk) INTO vTotal FROM vn.expeditionScan WHERE palletFk = vPalletFk;
IF vTotal <> 0 THEN
SELECT expeditionFk,
palletFk
FROM vn.expeditionScan
WHERE palletFk = vPalletFk;
ELSE
SELECT 0 expeditionFk,vPalletFk palletFk;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expeditionScan_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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionScan_Del`(vScanFk INT)
BEGIN
DELETE FROM vn.expeditionScan
WHERE id = vScanFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expeditionScan_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionScan_List`(vPalletFk INT)
BEGIN
SELECT es.id,
t.routeFk Ruta,
t.id Ticket,
e.counter Caja,
es.expeditionFk
FROM vn.expeditionScan es
JOIN vn.expedition e ON e.id = es.expeditionFk
JOIN vn.ticket t ON t.id = e.ticketFk
WHERE es.palletFk = vPalletFk
ORDER BY Ruta, Ticket, Caja;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expeditionScan_Put` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionScan_Put`(vPalletFk INT, vExpeditionFk INT)
BEGIN
REPLACE vn.expeditionScan(expeditionFk, palletFk)
VALUES(vExpeditionFk, vPalletFk);
SELECT LAST_INSERT_ID() INTO vPalletFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expeditionState_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_add`(vParam INT, vStateCode VARCHAR(100))
BEGIN
/**
* Inserta nuevos registros en la tabla vn.expeditionState, segun el parámetro
*
* @param vParam Identificador de vn.expedition o de vn.route
* @param vStateCode Corresponde a vn.expeditionStateType.code
*/
IF (SELECT COUNT(*) FROM vn.route r WHERE r.id = vParam) THEN
INSERT INTO vn.expeditionState(expeditionFk, typeFk)
SELECT e.id, est.id
FROM vn.expedition e
JOIN vn.ticket t ON t.id = e.ticketFk
JOIN vn.expeditionStateType est ON est.code = vStateCode
WHERE t.routeFk = vParam;
ELSE
INSERT INTO vn.expeditionState(expeditionFk, typeFk)
SELECT vParam, est.id
FROM vn.expeditionStateType est
WHERE est.code = vStateCode;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expeditionState_addByAdress` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByAdress`(vAdressFk INT, vRouteFk INT, vStateCode VARCHAR(100))
BEGIN
/**
* Inserta nuevos registros en la tabla vn.expeditionState
*
* @param vAdressFk Identificador de vn.ticket
* @param vRouteFk Identificador de vn.route
* @param vStateCode Corresponde a vn.expeditionStateType.code
*/
INSERT INTO vn.expeditionState(expeditionFk, typeFk)
SELECT e.id, est.id
FROM vn.expedition e
JOIN vn.expeditionStateType est ON est.code = vStateCode
JOIN vn.ticket t ON t.id = e.ticketFk
WHERE t.addressFk = vAdressFk AND t.routeFk = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expeditionState_addByExpedition` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByExpedition`(vExpeditionFk INT, vStateCode VARCHAR(100))
BEGIN
/**
* Inserta nuevos registros en la tabla vn.expeditionState
*
* @param vExpeditionFk Identificador de vn.expedition
* @param vStateCode Corresponde a vn.expeditionStateType.code
*/
INSERT INTO vn.expeditionState(expeditionFk, typeFk)
SELECT vExpeditionFk, est.id
FROM vn.expeditionStateType est
WHERE est.code = vStateCode;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expeditionState_addByPallet` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByPallet`(vPalletFk INT, vStateCode VARCHAR(100))
BEGIN
/**
* Inserta nuevos registros en la tabla vn.expeditionState
*
* @param vPalletFk Identificador de vn.expedition
* @param vStateCode Corresponde a vn.expeditionStateType.code
*/
DECLARE hasExpeditions BOOL;
DROP TEMPORARY TABLE IF EXISTS tExpeditionScan;
CREATE TEMPORARY TABLE tExpeditionScan
SELECT expeditionFk, est.id typeFk
FROM vn.expeditionScan e
JOIN vn.expeditionStateType est ON est.code = vStateCode
WHERE e.palletFk = vPalletFk;
SELECT COUNT(*) INTO hasExpeditions FROM tExpeditionScan;
IF NOT hasExpeditions THEN
DROP TEMPORARY TABLE tExpeditionScan;
CALL util.throw('palletDoesNotExist');
END IF;
INSERT INTO vn.expeditionState(expeditionFk, typeFk)
SELECT expeditionFk, typeFk
FROM tExpeditionScan;
DROP TEMPORARY TABLE tExpeditionScan;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expeditionState_addByRoute` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByRoute`(vRouteFk INT, vStateCode VARCHAR(100))
BEGIN
/**
* Inserta nuevos registros en la tabla vn.expeditionState, por rutas
*
* @param vRouteFk Identificador de vn.route
* @param vStateCode Corresponde a vn.expeditionStateType.code
*/
INSERT INTO vn.expeditionState(expeditionFk, typeFk)
SELECT e.id, est.id
FROM vn.expedition e
JOIN vn.ticket t ON t.id = e.ticketFk
JOIN vn.expeditionStateType est ON est.code = vStateCode
WHERE t.routeFk = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expeditionTruck_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionTruck_Add`(vHour VARCHAR(5), vDescription VARCHAR(45))
BEGIN
INSERT INTO vn.expeditionTruck(eta,description)
VALUES(CONCAT(util.VN_CURDATE(), ' ', vHour), 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expeditionTruck_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionTruck_List`()
BEGIN
SELECT id truckFk,
eta,
description Destino
FROM expeditionTruck
WHERE eta BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
ORDER BY eta;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_getFromRoute` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_getFromRoute`(vRouteFk INT)
BEGIN
/**
* Obtiene las expediciones a partir de una ruta
* @param vRouteFk Id de la ruta
*/
SELECT e.id,
e.ticketFk,
t.routeFk,
ts.alertLevel,
a.street,
a.city,
a.postalCode,
t.addressFk,
a.nickname,
sub2.itemPackingTypeConcat,
est.code
FROM expedition e
JOIN ticket t ON t.id = e.ticketFk
JOIN ticketState ts ON ts.ticketFk = e.ticketFk
JOIN address a ON t.addressFk = a.id
JOIN route r ON r.id = t.routeFk
LEFT JOIN warehouse w ON t.warehouseFk = w.id
LEFT JOIN (SELECT sub.ticketFk,
CONCAT('(', GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk ORDER BY sub.items DESC SEPARATOR ','), ') ') itemPackingTypeConcat
FROM (SELECT s.ticketFk , i.itemPackingTypeFk, COUNT(*) items
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
WHERE t.routeFk = vRouteFk
GROUP BY t.id,i.itemPackingTypeFk)sub
GROUP BY sub.ticketFk
) sub2 ON sub2.ticketFk = t.id
LEFT JOIN expeditionStateType est ON est.id = e.stateTypeFk
WHERE t.routeFk = vRouteFk AND e.freightItemFk <> FALSE
ORDER BY r.created, t.priority 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_getState` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_getState`(vExpeditionFk INT)
BEGIN
DECLARE vTicketsPendientes INT;
DECLARE vEtiquetasTotales INT;
DECLARE vEtiquetasEscaneadas INT;
DECLARE vRouteFk INT;
SELECT t.routeFk INTO vRouteFk
FROM vn.ticket t
JOIN vn.expedition e ON e.ticketFk = t.id
WHERE e.id = vExpeditionFk;
SELECT COUNT(*) INTO vTicketsPendientes
FROM vn.ticket t
LEFT JOIN vn.expedition e ON e.ticketFk = t.id
WHERE t.routeFk = vRouteFk
AND ISNULL(e.id);
SELECT COUNT(*) INTO vEtiquetasTotales
FROM vn.expedition e
JOIN vn.ticket t ON t.id = e.ticketFk
WHERE t.routeFk = vRouteFk;
SELECT COUNT(*) INTO vEtiquetasEscaneadas
FROM vn.expeditionScan es
JOIN vn.expedition e ON e.id = es.expeditionFk
JOIN vn.ticket t ON t.id = e.ticketFk
WHERE t.routeFk = vRouteFk;
SELECT e.ticketFk ticket,
t.nickname cliente,
a.city ciudad,
p.name provincia,
z.name zonaTicket,
am.name zonaRuta,
t.routeFk ruta,
rm.beachFk ubicacion,
et.eta ,
et.description camion,
vTicketsPendientes AS ticketsPendientes,
vEtiquetasTotales AS etiquetasTotales,
vEtiquetasEscaneadas AS etiquetasEscaneadas
FROM vn.expedition e
JOIN vn.ticket t ON t.id = e.ticketFk
JOIN vn.address a ON a.id = t.addressFk
JOIN vn.province p ON p.id = a.provinceFk
JOIN vn.`zone`z ON z.id = t.zoneFk
LEFT JOIN vn.route r ON r.id = t.routeFk
LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk
LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id
LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk
WHERE e.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `expedition_StateGet` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_StateGet`(vExpeditionFk INT)
BEGIN
/* Devuelve una "ficha" con todos los datos relativos a la expedición
*
* param vExpeditionFk
*/
DECLARE vTicketsPendientes INT;
DECLARE vEtiquetasTotales INT;
DECLARE vEtiquetasEscaneadas INT;
DECLARE vEtiquetasLeidasSorter INT;
DECLARE vRouteFk INT;
SELECT t.routeFk INTO vRouteFk
FROM vn.ticket t
JOIN vn.expedition e ON e.ticketFk = t.id
WHERE e.id = vExpeditionFk;
SELECT COUNT(*) INTO vTicketsPendientes
FROM vn.ticket t
LEFT JOIN vn.expedition e ON e.ticketFk = t.id
WHERE t.routeFk = vRouteFk
AND ISNULL(e.id);
SELECT COUNT(*) INTO vEtiquetasTotales
FROM vn.expedition e
JOIN vn.ticket t ON t.id = e.ticketFk
WHERE t.routeFk = vRouteFk;
SELECT COUNT(*) INTO vEtiquetasEscaneadas
FROM vn.expeditionScan es
JOIN vn.expedition e ON e.id = es.expeditionFk
JOIN vn.ticket t ON t.id = e.ticketFk
WHERE t.routeFk = vRouteFk;
SELECT COUNT(*) INTO vEtiquetasLeidasSorter
FROM srt.expedition e
JOIN vn.expedition ve ON ve.id = e.id
LEFT JOIN vn.expeditionScan es ON es.expeditionFk = e.id
JOIN vn.ticket t ON t.id = ve.ticketFk
WHERE t.routeFk = vRouteFk
AND e.created != e.updated
AND ISNULL(es.expeditionFk);
SELECT e.ticketFk ticket,
t.nickname cliente,
a.city ciudad,
p.name provincia,
z.name zonaTicket,
am.name zonaRuta,
t.routeFk ruta,
rm.beachFk ubicacion,
et.eta ,
et.description camion,
vTicketsPendientes AS ticketsPendientes,
vEtiquetasTotales AS etiquetasTotales,
vEtiquetasEscaneadas AS etiquetasEscaneadas,
vEtiquetasLeidasSorter AS etiquetasSorter
FROM vn.expedition e
JOIN vn.ticket t ON t.id = e.ticketFk
JOIN vn.address a ON a.id = t.addressFk
JOIN vn.province p ON p.id = a.provinceFk
JOIN vn.`zone`z ON z.id = t.zoneFk
LEFT JOIN vn.route r ON r.id = t.routeFk
LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk
LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id
LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk
WHERE e.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `freelance_getInfo` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `freelance_getInfo`(workerFk INT)
BEGIN
SELECT s.name, s.street, s.city, s.nif, s.postCode
FROM route r
JOIN agencyMode am ON r.agencyModeFk = am.id
JOIN agency a ON am.agencyFk = a.id
JOIN supplierAgencyTerm sat ON a.id = sat.agencyFk
JOIN supplier s ON sat.supplierFk = s.id
WHERE r.workerFk = workerFk
ORDER BY r.id DESC
LIMIT 1;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `fv_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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `fv_pca`()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE vTicketFk INT;
DECLARE vSaleFk INT;
DECLARE vClonTicket INT DEFAULT 0;
DECLARE cur1 CURSOR FOR
SELECT s.ticketFk, s.id
FROM vn.sale s
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.item i ON i.id = s.itemFk
JOIN vn.itemType it ON it.id = i.typeFk
WHERE t.shipped BETWEEN '2020-10-18' AND '2020-10-31'
AND it.code IN ('ANT','ANS','ORQ','TRO')
and t.warehouseFk = 1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur1;
FETCH cur1 INTO vTicketFk, vSaleFk;
WHILE done = 0 DO
SELECT t.id INTO vClonTicket
FROM vn.ticket t
JOIN (SELECT addressFk, shipped FROM vn.ticket WHERE id = vTicketFk) sub USING(addressFk, shipped)
WHERE t.warehouseFk = 44
LIMIT 1;
SELECT vTicketFk, vClonTicket;
IF vClonTicket = 0 THEN
INSERT INTO ticket (
clientFk,
shipped,
addressFk,
agencyModeFk,
nickname,
warehouseFk,
companyFk,
landed,
zoneFk,
zonePrice,
zoneBonus,
routeFk
)
SELECT
clientFk,
shipped,
addressFk,
agencyModeFk,
nickname,
44,
companyFk,
landed,
zoneFk,
zonePrice,
zoneBonus,
routeFk
FROM ticket
WHERE id = vTicketFk;
SET vClonTicket = LAST_INSERT_ID();
SELECT 'lstID', vClonTicket;
/*
INSERT INTO ticketObservation(ticketFk, observationTypeFk, description)
SELECT vTicketFk, ao.observationTypeFk, ao.description
FROM addressObservation ao
JOIN ticket t ON t.addressFk = ao.addressFk
WHERE t.id = vClonTicket;
*/
INSERT INTO ticketLog
SET originFk = vTicketFk, userFk = account.myUser_getId(), `action` = 'insert',
description = CONCAT('Ha creado el ticket:', ' ', vClonTicket, ' clonando el ', vTicketFk);
END IF;
UPDATE vn.sale
SET ticketFk = vClonTicket
WHERE id = vSaleFk;
SET vClonTicket = 0;
SET done = 0;
FETCH cur1 INTO vTicketFk, vSaleFk;
END WHILE;
CLOSE cur1;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `getDayExpeditions`()
BEGIN
SELECT
e.id as expeditionFk,
date_format(e.created,'%Y-%m-%d') as expeditionDate,
e.ticketFk,
t.routeFk as routeFk
FROM expedition e
INNER JOIN ticket t ON t.id = e.ticketFk
WHERE DATE(e.created) = util.VN_CURDATE();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `getInfoDelivery` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `getInfoDelivery`(vRouteFk INT)
BEGIN
SELECT s.name, s.street, s.city, s.nif, s.postCode FROM vn.route r
JOIN vn.agencyMode am ON r.agencyModeFk = am.id
JOIN vn.agency a ON am.agencyFk = a.id
JOIN vn.supplier s ON a.supplierFk = s.id
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `getTaxBases` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `getTaxBases`()
BEGIN
/**
* Calcula y devuelve en número de bases imponibles postivas y negativas
* Requiere la tabla temporal tmp.ticketToInvoice(id)
*
* returns tmp.taxBases
*/
CREATE OR REPLACE TEMPORARY TABLE tmp.ticket
(KEY (ticketFk))
ENGINE = MEMORY
SELECT id ticketFk
FROM tmp.ticketToInvoice;
CALL ticket_getTax(NULL);
DROP TEMPORARY TABLE IF EXISTS tmp.taxBases;
CREATE TEMPORARY TABLE tmp.taxBases
ENGINE = MEMORY
SELECT
SUM(taxableBase > 0) as positive,
SUM(taxableBase < 0) as negative
FROM(
SELECT SUM(taxableBase) taxableBase
FROM tmp.ticketTax
GROUP BY pgcFk
) 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `greuge_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `greuge_add`()
BEGIN
/**
* Group inserts into vn.greuge and then deletes the records just inserted
*/
DECLARE vDated DATE;
SELECT DATE_SUB(util.VN_CURDATE(), INTERVAL yearsToDelete YEAR) INTO vDated
FROM vn.greugeConfig;
INSERT INTO vn.greuge(clientFk, description, amount, shipped, created, greugeTypeFk)
SELECT clientFk, 'Suma agrupada', SUM(amount), MAX(shipped), MAX(created), greugeTypeFk
FROM vn.greuge
WHERE shipped <= vDated AND description <> 'Suma agrupada'
GROUP BY clientFk, greugeTypeFk;
DELETE
FROM vn.greuge
WHERE shipped <= vDated AND description <> 'Suma agrupada';
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `greuge_notifyEvents` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `greuge_notifyEvents`()
BEGIN
/**
* Notify to detect wrong greuges.
*/
DECLARE vTimeStart DATETIME;
DECLARE vTimeEnd DATETIME;
DECLARE vMaxPercentToWrong DECIMAL(10,2);
DECLARE vJSON JSON;
DECLARE vArray JSON;
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vHasData BOOL DEFAULT FALSE;
DECLARE vCounter INT DEFAULT 0;
DECLARE myCur CURSOR FOR
SELECT JSON_OBJECT(
'ticketId', g.ticketFk,
'clientId', g.clientFk,
'description', g.description,
'amount', g.amount
)
FROM greuge g
JOIN greugeType gt ON gt.id = g.greugeTypeFk
JOIN ticket t ON t.id = g.ticketFk
WHERE g.created BETWEEN vTimeStart AND util.dayEnd(vTimeEnd)
AND g.amount > (t.totalWithVat * (vMaxPercentToWrong / 100))
AND gt.code = 'freightDifference'
AND SIGN(t.totalWithVat)
ORDER BY g.clientFk;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SELECT IFNULL(DATE(lastNotifyCheck), util.VN_CURDATE()) INTO vTimeStart
FROM greugeConfig;
SET vTimeEnd = util.VN_NOW();
SELECT maxPercentToWrong INTO vMaxPercentToWrong
FROM greugeConfig
LIMIT 1;
IF vMaxPercentToWrong IS NULL THEN
CALL util.throw('Greuge max percent to wrong is not configured');
END IF;
SET vArray = JSON_ARRAY();
OPEN myCur;
myCur: LOOP
FETCH myCur INTO vJSON;
IF vDone THEN
LEAVE myCur;
END IF;
SET vArray = JSON_MERGE(vArray, vJSON);
SET vCounter = vCounter + 1;
SET vHasData = TRUE;
END LOOP;
CLOSE myCur;
IF vHasData THEN
SELECT util.notification_send(
'greuge-wrong',
JSON_OBJECT('tickets', JSON_EXTRACT(vArray, '$')),
account.myUser_getId()
);
END IF;
UPDATE greugeConfig
SET lastNotifyCheck = vTimeEnd;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `inventoryMake`(vInventoryDate DATE)
BEGIN
/**
* Recalculate the inventories
*
* @param vInventoryDate date for the new inventory
*/
DECLARE vDone BOOL;
DECLARE vEntryFk INT;
DECLARE vTravelFk INT;
DECLARE vDateLastInventory DATE;
DECLARE vDateYesterday DATETIME DEFAULT vInventoryDate - INTERVAL 1 SECOND;
DECLARE vWarehouseOutFkInventory INT;
DECLARE vInventorySupplierFk INT;
DECLARE vAgencyModeFkInventory INT;
DECLARE vMaxRecentInventories INT;
DECLARE vWarehouseFk INT;
DECLARE cWarehouses CURSOR FOR
SELECT id
FROM warehouse
WHERE isInventory;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SELECT inventorySupplierFk INTO vInventorySupplierFk FROM entryConfig LIMIT 1;
SELECT inventoried INTO vDateLastInventory FROM config LIMIT 1;
SELECT maxRecentInventories,
warehouseOutFk,
agencyModeFk
INTO vMaxRecentInventories,
vWarehouseOutFkInventory,
vAgencyModeFkInventory
FROM inventoryConfig
LIMIT 1;
IF vDateLastInventory IS NULL
OR vInventorySupplierFk IS NULL
OR vMaxRecentInventories IS NULL
OR vInventoryDate IS NULL
OR vWarehouseOutFkInventory IS NULL
OR vAgencyModeFkInventory IS NULL THEN
CALL util.throw('Some config parameters are not set');
END IF;
START TRANSACTION;
OPEN cWarehouses;
-- Environment variable to disable the triggers of the affected tables
SET @isModeInventory := TRUE;
l: LOOP
SET vDone = FALSE;
SET vEntryFk = NULL;
SET vTravelFk = NULL;
FETCH cWarehouses INTO vWarehouseFk;
IF vDone THEN
LEAVE l;
END IF;
-- Generate travel, if it does not exist
SELECT id INTO vTravelFk
FROM travel
WHERE warehouseOutFk = vWarehouseOutFkInventory
AND warehouseInFk = vWarehouseFk
AND landed = vInventoryDate
AND agencyModeFk = vAgencyModeFkInventory
AND ref = 'inventario'
LIMIT 1;
IF vTravelFk IS NULL THEN
INSERT INTO travel
SET warehouseOutFk = vWarehouseOutFkInventory,
warehouseInFk = vWarehouseFk,
shipped = vInventoryDate,
landed = vInventoryDate,
agencyModeFk = vAgencyModeFkInventory,
ref = 'inventario',
isDelivered = TRUE,
isReceived = TRUE;
SELECT LAST_INSERT_ID() INTO vTravelFk;
END IF;
-- Generate an entry if it does not exist, or we empty it
SELECT id INTO vEntryFk
FROM entry
WHERE supplierFk = vInventorySupplierFk
AND travelFk = vTravelFk
AND typeFk = 'inventory';
IF vEntryFk IS NULL THEN
INSERT INTO entry
SET supplierFk = vInventorySupplierFk,
isConfirmed = TRUE,
isOrdered = TRUE,
travelFk = vTravelFk,
typeFk = 'inventory';
SELECT LAST_INSERT_ID() INTO vEntryFk;
ELSE
DELETE FROM buy WHERE entryFk = vEntryFk;
END IF;
-- Prepare the auxiliary table
CREATE OR REPLACE TEMPORARY TABLE tInventory (
itemFk INT(11) NOT NULL PRIMARY KEY,
quantity int(11) DEFAULT '0',
buyingValue decimal(10,4) DEFAULT '0.0000',
freightValue decimal(10,3) DEFAULT '0.000',
packing int(11) DEFAULT '1',
`grouping` smallint(5) unsigned NOT NULL DEFAULT '1',
groupingMode enum('grouping', 'packing') DEFAULT NULL,
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;
-- Buys
INSERT INTO tInventory(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 = vWarehouseFk
AND tr.landed BETWEEN vDateLastInventory AND vDateYesterday
AND NOT isRaid
GROUP BY b.itemFk;
-- Transfers
INSERT INTO tInventory(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 = vWarehouseFk
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;
-- Sales
INSERT INTO tInventory(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 = vWarehouseFk
AND t.shipped BETWEEN vDateLastInventory AND vDateYesterday
GROUP BY s.itemFk
) sub
ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity,0) + sub.saleOut;
-- Update values of the last purchase
UPDATE tInventory inv
JOIN cache.last_buy lb ON lb.item_id = inv.itemFk AND lb.warehouse_id = vWarehouseFk
JOIN buy b ON b.id = lb.buy_id
JOIN item i ON i.id = b.itemFk
LEFT JOIN producer p ON p.id = i.producerFk
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.packagingFk,
inv.price1 = b.price1,
inv.price2 = b.price2,
inv.price3 = b.price3,
inv.minPrice = b.minPrice,
inv.producer = p.name;
INSERT INTO buy(itemFk,
quantity,
buyingValue,
freightValue,
packing,
`grouping`,
groupingMode,
comissionValue,
packageValue,
packagingFk,
price1,
price2,
price3,
minPrice,
entryFk)
SELECT itemFk,
GREATEST(quantity, 0),
buyingValue,
freightValue,
packing,
`grouping`,
groupingMode,
comissionValue,
packageValue,
packageFk,
price1,
price2,
price3,
minPrice,
vEntryFk
FROM tInventory;
-- Update the 'lastUsed' field of the item
UPDATE item i
JOIN tInventory i2 ON i2.itemFk = i.id
SET i.lastUsed = NOW()
WHERE i2.quantity;
DROP TEMPORARY TABLE tInventory;
END LOOP;
CLOSE cWarehouses;
UPDATE config SET inventoried = vInventoryDate;
CREATE OR REPLACE TEMPORARY TABLE tEntryToDelete
(INDEX(entryId)) ENGINE = MEMORY
SELECT e.id entryId,
t.id travelId
FROM travel t
JOIN `entry` e ON e.travelFk = t.id
JOIN (
SELECT t.shipped
FROM travel t
JOIN `entry` e ON e.travelFk = t.id
WHERE e.supplierFk = vInventorySupplierFk
AND t.shipped <= vInventoryDate
GROUP BY t.shipped
ORDER BY t.shipped DESC
OFFSET vMaxRecentInventories ROWS
) sub
WHERE e.supplierFk = vInventorySupplierFk
AND t.shipped IN (sub.shipped);
DELETE e
FROM `entry` e
JOIN tEntryToDelete tmp ON tmp.entryId = e.id;
DELETE IGNORE t
FROM travel t
JOIN tEntryToDelete tmp ON tmp.travelId = t.id;
SET @isModeInventory := FALSE;
DROP TEMPORARY TABLE IF EXISTS tEntryToDelete;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `inventoryMakeLauncher`()
BEGIN
/**
* Recalculate the inventories of all warehouses
*/
CALL inventoryMake(
util.VN_CURDATE() -
INTERVAL (SELECT daysInPastForInventory FROM inventoryConfig LIMIT 1) DAY
);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `inventory_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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `inventory_repair`()
BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.lastEntry;
CREATE TEMPORARY TABLE tmp.lastEntry
(PRIMARY KEY (buyFk))
SELECT
i.id AS itemFk,
w.id AS warehouseFk,
w.name AS warehouse,
tr.landed,
b.id AS buyFk,
b.entryFk,
b.isIgnored,
b.price2,
b.price3,
b.stickers,
b.packing,
b.grouping,
b.groupingMode,
b.weight,
i.stems,
b.quantity,
b.buyingValue,
b.packagingFk ,
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.packagingFk = "--" OR b.price2 = 0 OR b.buyingValue = 0) AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())) AND s.name = 'INVENTARIO';
DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOk;
CREATE TEMPORARY TABLE tmp.lastEntryOk
(PRIMARY KEY (buyFk))
SELECT
i.id AS itemFk,
w.id AS warehouseFk,
w.name AS warehouse,
tr.landed,
b.id AS buyFk,
b.entryFk,
b.isIgnored,
b.price2,
b.price3,
b.stickers,
b.packing,
b.grouping,
b.groupingMode,
b.weight,
i.stems,
b.quantity,
b.buyingValue,
b.packagingFk,
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.packagingFk != "--" AND b.price2 != 0 AND b.packing != 0 AND b.buyingValue > 0 AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-2,util.VN_CURDATE()))
ORDER BY tr.landed DESC;
DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOkGroup;
CREATE TEMPORARY TABLE tmp.lastEntryOkGroup
(INDEX (warehouseFk,itemFk))
SELECT *
FROM tmp.lastEntryOk tmp
GROUP BY tmp.itemFk,tmp.warehouseFk;
UPDATE buy b
JOIN tmp.lastEntry lt ON lt.buyFk = b.id
JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk
SET b.packagingFk = eo.packagingFk WHERE b.packagingFk = "--";
UPDATE buy b
JOIN tmp.lastEntry lt ON lt.buyFk = b.id
JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk
SET b.price2 = eo.price2 WHERE b.price2 = 0 ;
UPDATE buy b
JOIN tmp.lastEntry lt ON lt.buyFk = b.id
JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk
SET b.buyingValue = eo.buyingValue WHERE b.buyingValue = 0;
DROP TEMPORARY TABLE tmp.lastEntry;
DROP TEMPORARY TABLE tmp.lastEntryOk;
DROP TEMPORARY TABLE tmp.lastEntryOkGroup;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceExpenseMake` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceExpenseMake`(IN vInvoice INT)
BEGIN
/* Inserta las partidas de gasto correspondientes a la factura
* REQUIERE tabla tmp.ticketToInvoice
* @param vInvoice Numero de factura
*/
DELETE FROM invoiceOutExpense
WHERE invoiceOutFk = vInvoice;
INSERT INTO invoiceOutExpense(invoiceOutFk, expenseFk, amount)
SELECT vInvoice,
expenseFk,
SUM(ROUND(quantity * price * (100 - discount)/100,2)) amount
FROM tmp.ticketToInvoice t
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
GROUP BY i.expenseFk
HAVING amount != 0;
INSERT INTO invoiceOutExpense(invoiceOutFk, expenseFk, amount)
SELECT vInvoice,
tst.expenseFk,
SUM(ROUND(ts.quantity * ts.price ,2)) amount
FROM tmp.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceFromAddress` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceFromAddress`(vMaxTicketDate DATETIME,vAddress INT,vCompany INT)
BEGIN
DECLARE vMinDateTicket DATE DEFAULT TIMESTAMPADD(MONTH, -3, util.VN_CURDATE());
SET vMaxTicketDate = util.dayEnd(vMaxTicketDate);
DROP TEMPORARY TABLE IF EXISTS `tmp`.`ticketToInvoice`;
CREATE TEMPORARY TABLE `tmp`.`ticketToInvoice`
(PRIMARY KEY (`id`))
ENGINE = MEMORY
SELECT id
FROM ticket
WHERE (shipped BETWEEN vMinDateTicket AND vMaxTicketDate)
AND addressFk = vAddress
AND refFk IS NULL
AND companyFk = vCompany;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceFromClient` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceFromClient`(
IN vMaxTicketDate datetime,
IN vClientFk INT,
IN vCompanyFk INT)
BEGIN
DECLARE vMinTicketDate DATE;
SET vMinTicketDate = util.firstDayOfYear(vMaxTicketDate - INTERVAL 1 YEAR);
SET vMaxTicketDate = util.dayend(vMaxTicketDate);
DROP TEMPORARY TABLE IF EXISTS `tmp`.`ticketToInvoice`;
CREATE TEMPORARY TABLE `tmp`.`ticketToInvoice`
(PRIMARY KEY (`id`))
ENGINE = MEMORY
SELECT id FROM ticket t
WHERE t.clientFk = vClientFk
AND t.refFk IS NULL
AND t.companyFk = vCompanyFk
AND t.shipped BETWEEN vMinTicketDate 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 */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceFromTicket`(IN vTicket INT)
BEGIN
DROP TEMPORARY TABLE IF EXISTS `tmp`.`ticketToInvoice`;
CREATE TEMPORARY TABLE `tmp`.`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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceInDueDay_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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInDueDay_calculate`(vInvoiceInFk INT)
BEGIN
/**
* Calcula los vctos. de una factura recibida
* En caso de haberlos informado previamente o que el proveedor sea español, no los recalculará
*
* @param vInvoiceInFk Factura recibida
*/
DECLARE vCompanyCountryCode VARCHAR(3);
DECLARE vHasDueDayTax BOOL;
DECLARE vHasDueDay BOOL;
SELECT c.code, IFNULL(a.isUeeMember, TRUE AND co.code ='ES')
INTO vCompanyCountryCode, vHasDueDayTax
FROM invoiceIn ii
JOIN supplier su ON su.id = ii.companyFk
LEFT JOIN country c ON c.id = su.countryFk
LEFT JOIN supplier s ON s.id = ii.supplierFk
LEFT JOIN country co ON co.id = s.countryFk
LEFT JOIN province p ON p.id = s.provinceFk
LEFT JOIN autonomy a ON a.id = p.autonomyFk
WHERE ii.id = vInvoiceInFk;
SELECT COUNT(*) INTO vHasDueDay
FROM invoiceInDueDay iid
WHERE iid.invoiceInFk = vInvoiceInFk;
IF NOT vHasDueDay AND vCompanyCountryCode = 'ES' THEN
SET @cont := 0;
INSERT INTO invoiceInDueDay (
invoiceInFk,
dueDated,
amount,
foreignValue
)
SELECT vInvoiceInFk,
IF(payDay,
IF(getNextDueDate(issued, pdd.detail, payDay) < created,
created,
getNextDueDate(issued, pdd.detail, payDay)),
GREATEST(created, issued + INTERVAL pdd.detail DAY)),
IF((@cont := @cont + 1) < cont,
TRUNCATE(venc / cont, 2),
venc - (TRUNCATE(venc / cont, 2) * (cont - 1))),
IF(@cont < cont,
TRUNCATE(foreignValue / cont, 2),
foreignValue - (TRUNCATE(foreignValue / cont, 2) * (cont - 1)))
FROM (
SELECT SUM((1 + (IFNULL(ti.PorcentajeIva, 0) / 100) * vHasDueDayTax)
* iit.taxableBase) / COUNT(DISTINCT(pdd.detail)) venc,
SUM(iit.foreignValue) / COUNT(DISTINCT(pdd.detail)) foreignValue,
s.payDemFk,
ii.companyFk,
COUNT(DISTINCT(pdd.detail)) cont,
s.payDay,
ii.issued,
DATE(ii.created) + INTERVAL 2 DAY created
FROM invoiceIn ii
JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id
LEFT JOIN sage.TiposIva ti ON ti.CodigoIva= iit.taxTypeSageFk
JOIN supplier s ON s.id = ii.supplierFk
JOIN payDemDetail pdd ON pdd.id = s.payDemFk
WHERE ii.id = vInvoiceInFk
GROUP BY ii.id
)sub
JOIN payDemDetail pdd ON pdd.id = sub.payDemFk
GROUP BY pdd.detail;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceInDueDay_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInDueDay_recalc`(vInvoiceInFk INT)
BEGIN
DELETE FROM invoiceInDueDay
WHERE invoiceInFk = vInvoiceInFk;
CALL invoiceInDueDay_calculate(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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInTaxMakeByDua`(
vDuaFk INT
)
BEGIN
/**
* Borra los valores de duaTax y sus vctos. y los vuelve a
* crear en base a la tabla duaEntry.
*
* @param vDuaFk Id del dua a recalcular
*/
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vInvoiceInFk INT;
DECLARE vInvoices CURSOR FOR
SELECT DISTINCT invoiceInFk
FROM entry e
JOIN duaEntry de ON de.entryFk = e.id
WHERE de.duaFk = vDuaFk;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN vInvoices;
l: LOOP
SET vDone = FALSE;
FETCH vInvoices INTO vInvoiceInFk;
IF vDone THEN
LEAVE l;
END IF;
CALL invoiceInTax_recalc(vInvoiceInFk);
CALL invoiceInDueDay_recalc(vInvoiceInFk);
END LOOP;
CLOSE vInvoices;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceInTax_afterUpsert` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInTax_afterUpsert`(vInvoiceInFk INT)
BEGIN
/**
* Triggered actions when a invoiceInTax is updated or inserted.
*
* @param vInvoiceInFk The invoiceIn id
*/
DECLARE vTaxRowLimit INT;
DECLARE vLines INT;
DECLARE vHasDistinctTransactions INT;
SELECT taxRowLimit INTO vTaxRowLimit FROM invoiceInConfig;
SELECT COUNT(*) INTO vLines
FROM invoiceInTax
WHERE invoiceInFk = vInvoiceInFk
AND (taxTypeSageFk OR transactionTypeSageFk);
IF vLines >= vTaxRowLimit THEN
CALL util.throw (CONCAT('The maximum number of lines is ', vTaxRowLimit));
END IF;
SELECT COUNT(DISTINCT transactionTypeSageFk) INTO vHasDistinctTransactions
FROM invoiceIn ii
JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id
JOIN invoiceInSerial iis ON iis.code = ii.serial
WHERE ii.id = vInvoiceInFk
AND iis.taxAreaFk = 'CEE'
AND transactionTypeSageFk;
IF vHasDistinctTransactions > 1 THEN
CALL util.throw ('This invoice does not allow different types of transactions');
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceInTax_getFromDua` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInTax_getFromDua`(vDuaFk INT)
BEGIN
/**
* Borra los valores de duaTax y sus vctos. y los vuelve a crear en base a la tabla duaEntry
*
* @param vDuaFk Id del dua a recalcular
*/
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vInvoiceInFk INT;
DECLARE vInvoices CURSOR FOR
SELECT DISTINCT invoiceInFk
FROM entry e
JOIN duaEntry de ON de.entryFk = e.id
WHERE de.duaFk = vDuaFk;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN vInvoices;
l: LOOP
SET vDone = FALSE;
FETCH vInvoices INTO vInvoiceInFk;
IF vDone THEN
LEAVE l;
END IF;
CALL invoiceInTax_getFromEntries(vInvoiceInFk);
CALL invoiceInDueDay_calculate(vInvoiceInFk);
END LOOP;
CLOSE vInvoices;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceInTax_getFromEntries` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInTax_getFromEntries`(IN vInvoiceInFk INT)
BEGIN
DECLARE vRate DOUBLE DEFAULT 1;
DECLARE vDated DATE;
DECLARE vExpenseFk VARCHAR(10);
SELECT MAX(rr.dated) INTO vDated
FROM referenceRate rr
JOIN invoiceIn ii ON ii.id = vInvoiceInFk
WHERE rr.dated <= ii.issued
AND rr.currencyFk = ii.currencyFk ;
IF vDated THEN
SELECT `value` INTO vRate
FROM referenceRate
WHERE dated = vDated;
END IF;
SELECT id INTO vExpenseFk
FROM vn.expense
WHERE `name` = 'Adquisición mercancia Extracomunitaria'
GROUP BY id
LIMIT 1;
DELETE FROM invoiceInTax
WHERE invoiceInFk = vInvoiceInFk;
INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, foreignValue, taxTypeSageFk, transactionTypeSageFk)
SELECT ii.id,
SUM(b.buyingValue * b.quantity) / IFNULL(vRate,1) taxableBase,
vExpenseFk,
IF(ii.currencyFk = 1,NULL,SUM(b.buyingValue * b.quantity )) divisa,
taxTypeSageFk,
transactionTypeSageFk
FROM invoiceIn ii
JOIN entry e ON e.invoiceInFk = ii.id
JOIN supplier s ON s.id = e.supplierFk
JOIN buy b ON b.entryFk = e.id
LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk
AND rr.dated = ii.issued
WHERE ii.id = vInvoiceInFk
HAVING taxableBase IS NOT NULL;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceInTax_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInTax_recalc`(
vInvoiceInFk INT
)
BEGIN
/**
* Recalcula y actualiza los impuestos de la factura
* usando la última tasa de cambio y detalles de compra.
*
* @param vInvoiceInFk Id de factura recibida
*/
DECLARE vRate DOUBLE DEFAULT 1;
DECLARE vExpenseFk VARCHAR(10);
SELECT `value` INTO vRate
FROM referenceRate rr
JOIN invoiceIn ii ON ii.id = vInvoiceInFk
WHERE rr.dated <= ii.issued
AND rr.currencyFk = ii.currencyFk
ORDER BY dated DESC
LIMIT 1;
DELETE FROM invoiceInTax WHERE invoiceInFk = vInvoiceInFk;
SELECT id INTO vExpenseFk
FROM expense
WHERE code = 'extraCommGoodsAcquisition';
IF vExpenseFk IS NULL THEN
CALL util.throw('Expense extraCommGoodsAcquisition not exists');
END IF;
INSERT INTO invoiceInTax(
invoiceInFk,
taxableBase,
expenseFk,
foreignValue,
taxTypeSageFk,
transactionTypeSageFk
)
SELECT ii.id,
SUM(b.buyingValue * b.quantity) / vRate bi,
vExpenseFk,
IF(c.code = 'EUR', NULL, SUM(b.buyingValue * b.quantity)),
s.taxTypeSageFk,
s.transactionTypeSageFk
FROM invoiceIn ii
JOIN currency c ON c.id = ii.currencyFk
JOIN `entry` e ON e.invoiceInFk = ii.id
JOIN supplier s ON s.id = e.supplierFk
JOIN buy b ON b.entryFk = e.id
LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk
AND rr.dated = ii.issued
WHERE ii.id = vInvoiceInFk
HAVING bi IS NOT NULL;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceIn_booking` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_booking`(vSelf INT)
BEGIN
DECLARE vBookNumber INT;
CREATE OR REPLACE TEMPORARY TABLE tInvoiceIn
ENGINE = MEMORY
SELECT ii.bookEntried,
iit.foreignValue,
ii.companyFk,
ii.expenseFkDeductible,
iit.taxableBase,
iit.transactionTypeSageFk,
ii.serial,
ii.issued,
ii.operated,
ii.supplierRef,
ii.siiTrascendencyInvoiceInFk,
ii.cplusTaxBreakFk,
ii.cplusSubjectOpFk,
ii.siiTypeInvoiceInFk,
ii.cplusRectificationTypeFk,
ii.booked,
IFNULL(a.isUeeMember, c.isUeeMember) isUeeMember,
(c.id = cc.id) isSameCountry,
s.account supplierAccount,
s.name supplierName,
s.nif,
s.IsVies,
iit.taxTypeSageFk,
tt.code taxCode,
ti.Iva,
ti.CuentaIvaSoportado,
ti.PorcentajeIva,
ti.CuentaIvaRepercutido,
ttr.ClaveOperacionDefecto,
iis.cplusTerIdNifFk,
cit.id invoicesCount,
e.code,
e.isWithheld,
e.id expenseFk,
e.name expenseName
FROM invoiceIn ii
JOIN supplier s ON s.id = ii.supplierFk
LEFT JOIN province p ON p.id = s.provinceFk
LEFT JOIN autonomy a ON a.id = p.autonomyFk
JOIN country c ON c.id = s.countryFk
JOIN supplier sc ON sc.id = ii.companyFk
JOIN country cc ON cc.id = sc.countryFk
JOIN invoiceInSerial iis ON iis.code = ii.serial
JOIN siiTypeInvoiceIn cit ON cit.id = ii.siiTypeInvoiceInFk
LEFT JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id
LEFT JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = iit.transactionTypeSageFk
LEFT JOIN expense e ON e.id = iit.expenseFk
LEFT JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk
LEFT JOIN sage.taxType tt ON tt.id = ti.CodigoIva
WHERE ii.id = vSelf;
CALL vn.ledger_next(vBookNumber);
-- Apunte del proveedor
INSERT INTO XDiario(
ASIEN,
FECHA,
SUBCTA,
EUROHABER,
CONCEPTO,
CAMBIO,
HABERME,
NFACTICK,
CLAVE,
empresa_id)
SELECT
vBookNumber ASIEN,
tii.bookEntried FECHA,
tii.supplierAccount SUBCTA,
SUM(tii.taxableBase *
IF(tii.serial= 'R' AND ((tii.taxCode IS NULL OR tii.taxCode <> 'ISP21')
AND tii.taxTypeSageFk IS NOT NULL),
1 + (tii.PorcentajeIva / 100),
1)) EUROHABER,
CONCAT('s/fra',
RIGHT(tii.supplierRef, 8),
':',
LEFT(tii.supplierName, 10)) CONCEPTO,
CAST(tii.taxableBase / tii.foreignValue AS DECIMAL (10,4)) CAMBIO,
SUM(tii.foreignValue * IF(tii.serial = 'R', 1 + (tii.PorcentajeIva / 100), 1)) HABERME,
tii.invoicesCount NFACTICK,
vSelf CLAVE,
tii.companyFk empresa_id
FROM tInvoiceIn tii;
-- Línea de Gastos
INSERT INTO XDiario(
ASIEN,
FECHA,
SUBCTA,
CONTRA,
EURODEBE,
EUROHABER,
CONCEPTO,
CAMBIO,
DEBEME,
HABERME,
NFACTICK,
empresa_id)
SELECT vBookNumber ASIEN,
tii.bookEntried FECHA,
IF(tii.isWithheld, LPAD(RIGHT(tii.supplierAccount, 5), 10, tii.expenseFk),tii.expenseFk) SUBCTA,
tii.supplierAccount CONTRA,
IF(tii.isWithheld AND tii.taxableBase < 0, NULL, ROUND(SUM(tii.taxableBase),2)) EURODEBE,
IF(tii.isWithheld AND tii.taxableBase < 0, ROUND(SUM(-tii.taxableBase), 2), NULL) EUROHABER,
CONCAT('s/fra',
RIGHT(tii.supplierRef, 8),
':',
LEFT(tii.supplierName, 10)) CONCEPTO,
CAST(tii.taxableBase / tii.foreignValue AS DECIMAL (10, 4)) CAMBIO,
IF(tii.isWithheld, NULL,ABS(ROUND(SUM(tii.foreignValue), 2))) DEBEME,
IF(tii.isWithheld, ABS(ROUND(SUM(tii.foreignValue), 2)) ,NULL) HABERME,
tii.invoicesCount NFACTICK,
tii.companyFk empresa_id
FROM tInvoiceIn tii
WHERE tii.code IS NULL OR tii.code <> 'suplido'
GROUP BY tii.expenseFk;
-- Líneas de IVA
INSERT INTO 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,
tii.bookEntried FECHA,
IF(tii.expenseFkDeductible>0, tii.expenseFkDeductible, tii.CuentaIvaSoportado) SUBCTA,
tii.supplierAccount CONTRA,
SUM(ROUND(tii.PorcentajeIva * tii.taxableBase / 100, 2)) EURODEBE,
SUM(tii.taxableBase) BASEEURO,
GROUP_CONCAT(DISTINCT tii.expenseName SEPARATOR ', ') CONCEPTO,
vSelf FACTURA,
tii.PorcentajeIva IVA,
IF(tii.isUeeMember AND eWithheld.id IS NULL, '', '*') AUXILIAR,
tii.serial SERIE,
tii.ClaveOperacionDefecto,
tii.issued FECHA_EX,
tii.operated FECHA_OP,
tii.invoicesCount NFACTICK,
tii.supplierRef FACTURAEX,
TRUE L340,
(tii.isSameCountry OR NOT tii.isUeeMember) LRECT349,
tii.siiTrascendencyInvoiceInFk TIPOCLAVE,
tii.cplusTaxBreakFk TIPOEXENCI,
tii.cplusSubjectOpFk TIPONOSUJE,
tii.siiTypeInvoiceInFk TIPOFACT,
tii.cplusRectificationTypeFk TIPORECTIF,
tii.cplusTerIdNifFk TERIDNIF,
tii.nif TERNIF,
tii.supplierName TERNOM,
tii.booked FECREGCON,
tii.companyFk
FROM tInvoiceIn tii
LEFT JOIN (
SELECT e.id
FROM tInvoiceIn tii
JOIN expense e ON e.id = tii.expenseFk
WHERE e.isWithheld
LIMIT 1
) eWithheld ON TRUE
WHERE tii.taxTypeSageFk IS NOT NULL
AND (tii.taxCode IS NULL OR tii.taxCode NOT IN ('import10', 'import21'))
GROUP BY tii.PorcentajeIva, tii.expenseFk;
-- Línea iva inversor sujeto pasivo
INSERT INTO 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,
tii.bookEntried FECHA,
tii.CuentaIvaRepercutido SUBCTA,
tii.supplierAccount CONTRA,
SUM(ROUND(tii.PorcentajeIva * tii.taxableBase / 100,2)) EUROHABER,
ROUND(SUM(tii.taxableBase),2) BASEEURO,
GROUP_CONCAT(DISTINCT tii.expenseName SEPARATOR ', ') CONCEPTO,
vSelf FACTURA,
tii.PorcentajeIva IVA,
'*' AUXILIAR,
tii.serial SERIE,
tii.ClaveOperacionDefecto,
tii.issued FECHA_EX,
tii.operated FECHA_OP,
tii.invoicesCount NFACTICK,
tii.supplierRef FACTURAEX,
FALSE L340,
(tii.isSameCountry OR NOT tii.isUeeMember) LRECT349,
1 TIPOCLAVE,
tii.cplusTaxBreakFk TIPOEXENCI,
tii.cplusSubjectOpFk TIPONOSUJE,
tii.siiTypeInvoiceInFk TIPOFACT,
tii.cplusRectificationTypeFk TIPORECTIF,
tii.cplusTerIdNifFk TERIDNIF,
tii.nif TERNIF,
tii.supplierName TERNOM,
tii.companyFk
FROM tInvoiceIn tii
JOIN sage.config c
WHERE tii.taxCode = 'ISP21' OR MID(tii.supplierAccount, 4, 1) = '1'
AND tii.taxTypeSageFk IS NOT NULL
AND NOT(tii.isVies
AND c.nontaxableTransactionTypeFk = tii.transactionTypeSageFk
AND tii.taxCode = 'nonTaxable')
GROUP BY tii.PorcentajeIva, tii.expenseFk;
-- Actualización del registro original
UPDATE invoiceIn ii
SET ii.isBooked = TRUE
WHERE ii.id = vSelf;
-- Problemas derivados de la precisión en los decimales al calcular los impuestos
UPDATE XDiario
SET EURODEBE = EURODEBE -
(SELECT IF(ABS(sub.difference) = 0.01, sub.difference, 0)
FROM(
SELECT SUM(IFNULL(ROUND(EURODEBE, 2),0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) difference
FROM XDiario
WHERE ASIEN = vBookNumber
)sub
)
WHERE ASIEN = vBookNumber
AND EURODEBE <> 0
ORDER BY id DESC
LIMIT 1;
DROP TEMPORARY TABLE tInvoiceIn;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceIn_checkBooked` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_checkBooked`(
vSelf INT
)
BEGIN
/**
* Comprueba si una factura recibida está contabilizada,
* y si lo está retorna un throw.
*
* @param vSelf Id invoiceIn
*/
DECLARE vIsBooked BOOL;
SELECT isBooked INTO vIsBooked
FROM invoiceIn
WHERE id = vSelf;
IF vIsBooked THEN
CALL util.throw('InvoiceIn is already booked');
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 tmp.ticketToInvoice;
CREATE TEMPORARY TABLE tmp.ticketToInvoice
SELECT id
FROM ticket
WHERE refFk = vInvoiceRef;
CALL invoiceExpenseMake(vInvoiceFk);
CALL invoiceTaxMake(vInvoiceFk,vTaxArea);
UPDATE invoiceOut io
JOIN (
SELECT SUM(amount) AS total
FROM invoiceOutExpense
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOutBooking`(IN vInvoice INT)
BEGIN
/* Asienta la factura emitida
*
* param vInvoice factura_id
*/
DECLARE vBookNumber INT;
DECLARE vExpenseConcept VARCHAR(50);
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,
io.issued AS FECHA_OP,
io.issued AS FECHA,
1 AS NFACTICK,
IF(ic.correctingFk,'D','') AS TIPOOPE,
io.siiTrascendencyInvoiceOutFk AS TIPOCLAVE,
io.cplusTaxBreakFk AS TIPOEXENCI,
io.cplusSubjectOpFk AS TIPONOSUJE,
io.siiTypeInvoiceOutFk AS TIPOFACT,
ic.cplusRectificationTypeFk AS TIPORECTIF,
io.companyFk,
RIGHT(io.ref, LENGTH(io.ref) - 1) AS invoiceNum,
IF(c.countryFk = vSpainCountryFk, vSpainCountryFk, IF(ct.isUeeMember,2,4)) AS TERIDNIF,
CONCAT(IF(ct.isUeeMember AND c.countryFk <> 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 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.expenseFk 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 invoiceOutExpense ioe
WHERE ioe.invoiceOutFk = vInvoice;
SELECT GROUP_CONCAT(`name` SEPARATOR ',')
INTO vExpenseConcept
FROM expense e
JOIN invoiceOutExpense ioe ON ioe.expenseFk = 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(vExpenseConcept,' : ',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.siiTrascendencyInvoiceOutFk 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 = util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutTaxAndExpense` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOutTaxAndExpense`()
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 tmp.ticketToInvoice;
CREATE TEMPORARY TABLE tmp.ticketToInvoice
SELECT id
FROM ticket
WHERE refFk = vInvoiceRef;
CALL invoiceExpenseMake(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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceOut_exportationFromClient` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_exportationFromClient`(
vMaxTicketDate DATETIME,
vClientFk INT,
vCompanyFk INT)
BEGIN
/**
* Genera tabla temporal tmp.ticketToInvoice necesaría para el proceso de facturación
* Los abonos quedan excluidos en las exportaciones
*
* @param vMaxTicketDate Fecha hasta la cual cogerá tickets para facturar
* @param vClientFk Id del cliente a facturar
* @param vCompanyFk Id de la empresa desde la que se factura
*/
DECLARE vMinTicketDate DATE;
SET vMinTicketDate = util.firstDayOfYear(vMaxTicketDate - INTERVAL 1 YEAR);
SET vMaxTicketDate = util.dayend(vMaxTicketDate);
DROP TEMPORARY TABLE IF EXISTS `tmp`.`ticketToInvoice`;
CREATE TEMPORARY TABLE `tmp`.`ticketToInvoice`
(PRIMARY KEY (`id`))
ENGINE = MEMORY
SELECT t.id
FROM ticket t
JOIN agencyMode am ON am.id = t.agencyModeFk
WHERE t.clientFk = vClientFk
AND t.refFk IS NULL
AND t.companyFk = vCompanyFk
AND t.shipped BETWEEN vMinTicketDate AND vMaxTicketDate
AND (am.`code` IS NULL OR am.`code` <> 'refund');
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_new`(
vSerial VARCHAR(255),
vInvoiceDate DATE,
vTaxArea VARCHAR(25),
OUT vNewInvoiceId INT)
BEGIN
/**
* Creación de facturas emitidas.
* requiere previamente tabla tmp.ticketToInvoice(id).
*
* @param vSerial serie a la cual se hace la factura
* @param vInvoiceDate fecha de la factura
* @param vTaxArea tipo de iva en relacion a la empresa y al cliente
* @param vNewInvoiceId id de la factura que se acaba de generar
* @return vNewInvoiceId
*/
DECLARE vIsAnySaleToInvoice BOOL;
DECLARE vIsAnyServiceToInvoice BOOL;
DECLARE vNewRef VARCHAR(255);
DECLARE vWorker INT DEFAULT account.myUser_getId();
DECLARE vCompanyFk INT;
DECLARE vInterCompanyFk INT;
DECLARE vClientFk INT;
DECLARE vCplusStandardInvoiceTypeFk INT DEFAULT 1;
DECLARE vCplusCorrectingInvoiceTypeFk INT DEFAULT 6;
DECLARE vCplusSimplifiedInvoiceTypeFk INT DEFAULT 2;
DECLARE vCorrectingSerial VARCHAR(1) DEFAULT 'R';
DECLARE vSimplifiedSerial VARCHAR(1) DEFAULT 'S';
DECLARE vNewInvoiceInFk INT;
DECLARE vIsInterCompany BOOL DEFAULT FALSE;
DECLARE vIsCEESerial BOOL DEFAULT FALSE;
DECLARE vIsCorrectInvoiceDate BOOL;
DECLARE vMaxShipped DATE;
DECLARE vDone BOOL;
DECLARE vTicketFk INT;
DECLARE vCursor CURSOR FOR
SELECT id
FROM tmp.ticketToInvoice;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SET vInvoiceDate = IFNULL(vInvoiceDate, util.VN_CURDATE());
SELECT t.clientFk,
t.companyFk,
MAX(DATE(t.shipped)),
DATE(vInvoiceDate) >= invoiceOut_getMaxIssued(
vSerial,
t.companyFk,
YEAR(vInvoiceDate))
INTO vClientFk,
vCompanyFk,
vMaxShipped,
vIsCorrectInvoiceDate
FROM tmp.ticketToInvoice tt
JOIN ticket t ON t.id = tt.id;
IF(vMaxShipped > vInvoiceDate) THEN
CALL util.throw("Invoice date can't be less than max date");
END IF;
IF NOT vIsCorrectInvoiceDate THEN
CALL util.throw('Exists an invoice with a previous date');
END IF;
-- Eliminem de tmp.ticketToInvoice els tickets que no han de ser facturats
DELETE ti.*
FROM tmp.ticketToInvoice ti
JOIN ticket t ON t.id = ti.id
LEFT JOIN address a ON a.id = t.addressFk
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
JOIN supplier su ON su.id = t.companyFk
JOIN client c ON c.id = t.clientFk
LEFT JOIN itemTaxCountry itc ON itc.itemFk = i.id
AND itc.countryFk = su.countryFk
WHERE (YEAR(t.shipped) < 2001 AND t.isDeleted)
OR c.isTaxDataChecked = FALSE
OR t.isDeleted
OR c.hasToInvoice = FALSE
OR itc.id IS NULL
OR a.id IS NULL
OR (vTaxArea = 'WORLD'
AND (a.customsAgentFk IS NULL OR a.incotermsFk IS NULL));
SELECT SUM(s.quantity * s.price * (100 - s.discount)/100) <> 0
INTO vIsAnySaleToInvoice
FROM tmp.ticketToInvoice t
JOIN sale s ON s.ticketFk = t.id;
SELECT COUNT(*) > 0 INTO vIsAnyServiceToInvoice
FROM tmp.ticketToInvoice t
JOIN ticketService ts ON ts.ticketFk = t.id;
IF (vIsAnySaleToInvoice OR vIsAnyServiceToInvoice)
AND (vCorrectingSerial = vSerial OR NOT hasAnyNegativeBase())
THEN
-- el trigger añade el siguiente Id_Factura correspondiente a la vSerial
INSERT INTO invoiceOut(
ref,
serial,
issued,
clientFk,
dued,
companyFk,
siiTypeInvoiceOutFk
)
SELECT
1,
vSerial,
vInvoiceDate,
vClientFk,
getDueDate(vInvoiceDate, dueDay),
vCompanyFk,
IF(vSerial = vCorrectingSerial,
vCplusCorrectingInvoiceTypeFk,
IF(vSerial = vSimplifiedSerial,
vCplusSimplifiedInvoiceTypeFk,
vCplusStandardInvoiceTypeFk))
FROM client
WHERE id = vClientFk;
SET vNewInvoiceId = LAST_INSERT_ID();
SELECT `ref`
INTO vNewRef
FROM invoiceOut
WHERE id = vNewInvoiceId;
OPEN vCursor;
l: LOOP
SET vDone = FALSE;
FETCH vCursor INTO vTicketFk;
IF vDone THEN
LEAVE l;
END IF;
CALL ticket_recalc(vTicketFk, vTaxArea);
END LOOP;
CLOSE vCursor;
UPDATE ticket t
JOIN tmp.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 tmp.ticketToInvoice ti
LEFT JOIN ticketState ts ON ti.id = ts.ticketFk
JOIN state s
WHERE IFNULL(ts.alertLevel, 0) < 3 and s.`code` = getAlert3State(ti.id);
INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
SELECT * FROM tmp.updateInter;
CALL invoiceExpenseMake(vNewInvoiceId);
CALL invoiceTaxMake(vNewInvoiceId, vTaxArea);
UPDATE invoiceOut io
JOIN (
SELECT SUM(amount) total
FROM invoiceOutExpense
WHERE invoiceOutFk = vNewInvoiceId
) base
JOIN (
SELECT SUM(vat) total
FROM invoiceOutTax
WHERE invoiceOutFk = vNewInvoiceId
) vat
SET io.amount = base.total + vat.total
WHERE io.id = vNewInvoiceId;
DROP TEMPORARY TABLE tmp.updateInter;
SELECT COUNT(*), id
INTO vIsInterCompany, vInterCompanyFk
FROM company
WHERE clientFk = vClientFk;
IF (vIsInterCompany) THEN
INSERT INTO invoiceIn(supplierFk, supplierRef, issued, companyFk)
SELECT vCompanyFk, vNewRef, vInvoiceDate, vInterCompanyFk;
SET vNewInvoiceInFk = LAST_INSERT_ID();
DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
CREATE TEMPORARY TABLE tmp.ticket
(KEY (ticketFk))
ENGINE = MEMORY
SELECT id ticketFk
FROM tmp.ticketToInvoice;
CALL `ticket_getTax`('NATIONAL');
SET @vTaxableBaseServices := 0.00;
SET @vTaxCodeGeneral := NULL;
INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
SELECT vNewInvoiceInFk,
@vTaxableBaseServices,
sub.expenseFk,
sub.taxTypeSageFk,
sub.transactionTypeSageFk
FROM (
SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase,
i.expenseFk,
i.taxTypeSageFk,
i.transactionTypeSageFk,
@vTaxCodeGeneral := i.taxClassCodeFk
FROM tmp.ticketServiceTax tst
JOIN invoiceOutTaxConfig i ON i.taxClassCodeFk = tst.code
WHERE i.isService
HAVING taxableBase
) sub;
INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
SELECT vNewInvoiceInFk,
SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral,
@vTaxableBaseServices, 0) taxableBase,
i.expenseFk,
i.taxTypeSageFk ,
i.transactionTypeSageFk
FROM tmp.ticketTax tt
JOIN invoiceOutTaxConfig i ON i.taxClassCodeFk = tt.code
WHERE !i.isService
GROUP BY tt.pgcFk
HAVING taxableBase
ORDER BY tt.priority;
CALL invoiceInDueDay_calculate(vNewInvoiceInFk);
SELECT COUNT(*) INTO vIsCEESerial
FROM invoiceOutSerial
WHERE code = vSerial;
IF vIsCEESerial THEN
INSERT INTO invoiceInIntrastat (
invoiceInFk,
intrastatFk,
amount,
stems,
countryFk,
net)
SELECT
vNewInvoiceInFk,
i.intrastatFk,
SUM(CAST((s.quantity * s.price * (100 - s.discount) / 100 ) AS DECIMAL(10, 2))),
SUM(CAST(IFNULL(i.stems, 1) * s.quantity AS DECIMAL(10, 2))),
su.countryFk,
CAST(SUM(IFNULL(i.stems, 1)
* s.quantity
* IF(ic.grams, ic.grams, IFNULL(i.weightByPiece, 0)) / 1000) AS DECIMAL(10, 2))
FROM sale s
JOIN ticket t ON s.ticketFk = t.id
JOIN supplier su ON su.id = t.companyFk
JOIN item i ON i.id = s.itemFk
LEFT JOIN itemCost ic ON ic.itemFk = i.id AND ic.warehouseFk = t.warehouseFk
WHERE t.refFk = vNewRef
GROUP BY i.intrastatFk;
END IF;
DROP TEMPORARY TABLE tmp.ticket;
DROP TEMPORARY TABLE tmp.ticketAmount;
DROP TEMPORARY TABLE tmp.ticketTax;
DROP TEMPORARY TABLE tmp.ticketServiceTax;
END IF;
END IF;
DROP TEMPORARY TABLE `tmp`.`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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_newFromClient`(
IN vClientFk INT,
IN vSerial CHAR(2),
IN vMaxShipped DATE,
IN vCompanyFk INT,
IN vTaxArea VARCHAR(25),
IN vRef VARCHAR(25),
OUT vInvoiceId INT)
BEGIN
/**
* Factura los tickets de un cliente hasta una fecha dada
* @param vClientFk Id del cliente a facturar
* @param vSerial Serie de factura
* @param vMaxShipped Fecha hasta la cual cogera tickets para facturar
* @param vCompanyFk Id de la empresa desde la que se factura
* @param vTaxArea Tipo de iva en relacion a la empresa y al cliente, NULL por defecto
* @param vRef Referencia de la factura en caso que se quiera forzar, NULL por defecto
* @return vInvoiceId factura
*/
DECLARE vIsRefEditable BOOLEAN;
DECLARE vIsExportation BOOLEAN;
IF vRef IS NOT NULL THEN
SELECT isRefEditable INTO vIsRefEditable
FROM invoiceOutSerial
WHERE code = vSerial;
IF NOT vIsRefEditable THEN
CALL util.throw('serial non editable');
END IF;
END IF;
SELECT COUNT(*) INTO vIsExportation
FROM vn.invoiceOutSerial
WHERE taxAreaFk = 'WORLD'
AND `code` = vSerial;
IF vIsExportation THEN
CALL invoiceOut_exportationFromClient(vMaxShipped, vClientFk, vCompanyFk);
ELSE
CALL invoiceFromClient(vMaxShipped, vClientFk, vCompanyFk);
END IF;
CALL invoiceOut_new(vSerial, util.VN_CURDATE(), vTaxArea, vInvoiceId);
UPDATE invoiceOut
SET `ref` = vRef
WHERE id = vInvoiceId
AND vRef IS NOT NULL;
IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN
CALL invoiceOutBooking(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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_newFromTicket`(IN vTicketFk int, IN vSerial char(2), IN vTaxArea varchar(25),
IN vRef 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 vIsRefEditable BOOLEAN;
CALL invoiceFromTicket(vTicketFk);
CALL invoiceOut_new(vSerial, util.VN_CURDATE(), vTaxArea, vInvoiceId);
IF vRef IS NOT NULL THEN
SELECT isRefEditable INTO vIsRefEditable
FROM invoiceOutSerial
WHERE code = vSerial;
IF NOT vIsRefEditable THEN
CALL util.throw('serial non editable');
END IF;
UPDATE invoiceOut
SET `ref` = vRef
WHERE id = vInvoiceId;
END IF;
IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN
CALL invoiceOutBooking(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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 tmp.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemBarcode_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemBarcode_update`(vItemFk INT,vCode VARCHAR(22), vDelete BOOL)
BEGIN
IF vDelete THEN
DELETE FROM vn.itemBarcode WHERE itemFk = vItemFk AND code = vCode;
ELSE
INSERT INTO vn.itemBarcode(itemFk,code) VALUES (vItemFk,vCode);
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemFuentesBalance`(vDaysInFuture INT)
BEGIN
/* Se utiliza para calcular la necesidad de mover mercancia entre el almacén de fuentes y el nuestro
*
* @param vDaysInFuture Rango de dias para calcular entradas y salidas
*
*/
DECLARE vWarehouseFk INT;
SELECT s.warehouseFk INTO vWarehouseFk
FROM vn.sector s
WHERE s.code = 'FUENTES_PICASSE';
CALL cache.stock_refresh(FALSE);
SELECT i.id itemFk,
i.longName,
i.size,
i.subName,
v.amount - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as visible,
fue.Fuentes,
alb.Albenfruit,
sale.venta,
IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra,
IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0)
- IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as saldo
FROM vn.item i
JOIN vn.itemType it ON it.id = i.typeFk
JOIN vn.itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN (
SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS Fuentes
FROM vn.itemShelving ish
JOIN vn.shelving sh ON sh.code = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
JOIN vn.sector s ON s.id = p.sectorFk
WHERE s.code = 'FUENTES_PICASSE'
GROUP BY ish.itemFk
) fue ON fue.itemFk = i.id
LEFT JOIN (
SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS Albenfruit
FROM vn.itemShelving ish
JOIN vn.shelving sh ON sh.code = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
JOIN vn.sector s ON s.id = p.sectorFk
WHERE s.code = 'ALBENFRUIT'
GROUP BY ish.itemFk
) alb ON alb.itemFk = i.id
LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk
LEFT JOIN (
SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as venta
FROM itemTicketOut
WHERE shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE()))
AND warehouseFk = vWarehouseFk
GROUP BY itemFk
) sale ON sale.item_id = i.id
LEFT JOIN (
SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as compra
FROM itemEntryIn
WHERE landed BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE()))
AND warehouseInFk = vWarehouseFk
AND isVirtualStock = FALSE
GROUP BY itemFk
) buy ON buy.item_id = i.id
LEFT JOIN (
SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as traslado
FROM itemEntryOut
WHERE shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE()))
AND warehouseOutFk = vWarehouseFk
GROUP BY itemFk
) mov ON mov.item_id = i.id
WHERE (v.amount OR fue.Fuentes OR alb.Albenfruit)
AND i.itemPackingTypeFk = 'H'
AND ic.shortLife;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemPlacementSupplyStockGetTargetList`(vItemFk INT,vSectorFk INT)
BEGIN
/**
* Devuelve la lista de ubicaciones para itemFk en ese sector. Se utiliza en la preparación previa.
* Este proc se llama a continuacion de ticketToPrePrepare
*
* @param vItemFk Identificador de vn.item
* @param vSectorFk Identificador de vn.sector
*/
SELECT ish.shelvingFk shelving,
p.code parking,
SUM(ish.visible) stockTotal,
ish.created,
p.pickingOrder
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 sc ON sc.id = p.sectorFk
JOIN vn.warehouse w ON w.id = sc.warehouseFk
WHERE sc.id = vSectorFk
AND ish.visible > 0
AND ish.itemFk = vItemFk
GROUP BY ish.id
ORDER BY sh.priority DESC,
ish.created,
p.pickingOrder;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemRefreshTags`(IN vItem INT)
BEGIN
/**
* Crea la tabla temporal necesaria para el procedimiento item_refreshTags
*
* @param vItem Articulo a modificar
* @param temporary table tmp.item(id) del articulo
**/
DROP TEMPORARY TABLE IF EXISTS tmp.item;
CREATE TEMPORARY TABLE tmp.item
SELECT vItem id;
CALL item_refreshTags();
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemSale_byWeek` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemSale_byWeek`(vWeek INT, IN vYear INT, vItemFk INT, vWarehouseFk INT)
BEGIN
DECLARE vStarted DATE;
DECLARE vEnded DATETIME;
SELECT MIN(dated), util.dayEnd(MAX(dated)) INTO vStarted, vEnded
FROM `time` t
WHERE CONCAT(vYear, LPAD(vWeek, 2, 0)) = t.period;
SELECT t.shipped,
w.name warehouse,
s.ticketFk,
t.nickname client,
am.name agencyName,
wk.code salesPerson,
s.itemFk,
IFNULL(CONCAT(ig.longName,' ',ig.`size`,' ',ig.subName), s.concept) AS concept,
s.quantity,
s.price,
s.priceFixed,
s.discount,
tls.name stateName,
sb.buyFk,
s.id saleFk,
wk.id salesPersonFk
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
JOIN warehouse w ON w.id = t.warehouseFk
JOIN address a ON a.id = t.addressFk
LEFT JOIN agencyMode am ON am.id = t.agencyModeFk
JOIN `client` c ON c.id = a.clientFk
LEFT JOIN worker wk ON wk.id = c.salesPersonFk
LEFT JOIN ticketLastState tls ON tls.ticketFk = t.id
LEFT JOIN saleBuy sb ON sb.saleFk = s.id
LEFT JOIN buy b ON b.id = sb.buyFk
LEFT JOIN item ig ON ig.id = b.itemOriginalFk
WHERE s.itemFk = vItemFk
AND t.shipped BETWEEN vStarted AND vEnded
AND IF(vWarehouseFk = 0, w.hasComission , t.warehouseFk = vWarehouseFk)
ORDER BY t.shipped, t.id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemSearchShelving` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingLog_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingLog_get`(vShelvingFk VARCHAR(10) )
BEGIN
/**
* Devuelve el log de los item en cada carro
*
* @param vShelvingFk Matrícula del carro
*
*/
SELECT isl.itemShelvingFk,
isl.created,
isl.accion,
isl.itemFk,
isl.shelvingFk,
isl.quantity,
isl.visible,
isl.available,
isl.grouping,
isl.packing,
isl.stars,
item.longName,
item.size,
item.subName,
worker.code,
isl.accion
FROM item
JOIN itemShelvingLog isl ON item.id = isl.itemFk
JOIN worker ON isl.workerFk = worker.id
WHERE shelvingFk = vShelvingFk OR isl.itemFk = vShelvingFk
ORDER BY isl.created 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingMakeFromDate`(IN `vShelvingFk` VARCHAR(8), IN `vBarcode` VARCHAR(22), IN `vQuantity` INT, IN `vPackagingFk` VARCHAR(10), IN `vGrouping` INT, IN `vPacking` INT, IN `vWarehouseFk` 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 visible = visible+vQuantity,
created = vCreated
WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
AND itemFk = vItemFk
AND packing = vPacking;
ELSE
CALL cache.last_buy_refresh(FALSE);
INSERT INTO itemShelving( itemFk,
shelvingFk,
visible,
created,
`grouping`,
packing,
packagingFk)
SELECT vItemFk,
vShelvingFk,
vQuantity,
vCreated,
IF(vGrouping = 0, IFNULL(b.packing, vPacking), vGrouping) `grouping`,
IF(vPacking = 0, b.packing, vPacking) packing,
IF(vPackagingFk = '', b.packagingFk, vPackagingFk) packaging
FROM vn.item i
LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk
LEFT JOIN vn.buy b ON b.id = lb.buy_id
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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, st.saleFk
FROM ticket t
JOIN ticketState tst ON tst.ticketFk = t.id
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
JOIN cache.visible v ON s.itemFk = v.item_id AND v.calc_id = vVisibleCache
LEFT JOIN saleTracking st ON st.saleFk = s.id AND st.stateFk = 26
JOIN itemShelvingStock iss ON iss.itemFk = v.item_id
LEFT JOIN
(SELECT itemFk, sum(saldo) as transit
FROM 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 util.VN_CURDATE() AND MIDNIGHT(util.VN_CURDATE())
AND tst.isPreviousPreparable = TRUE
AND t.warehouseFk = vWarehouseFk
AND iss.sectorFk = vSectorFk
AND st.saleFk 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingRadar`(
vSectorFk INT
)
proc:BEGIN
/**
* Calcula la información detallada respecto un sector.
*
* @param vSectorFk Id de sector
*/
DECLARE vCalcVisibleFk INT;
DECLARE vCalcAvailableFk INT;
DECLARE hasFatherSector BOOLEAN;
DECLARE vBuyerFk INT DEFAULT 0;
DECLARE vWarehouseFk INT DEFAULT 0;
DECLARE vSonSectorFk INT;
DECLARE vWorkerFk INT;
SELECT s.workerFk
INTO vWorkerFk
FROM vn.sector s
WHERE s.id = vSectorFk;
SELECT w.id, s.warehouseFk INTO vBuyerFk, vWarehouseFk
FROM vn.worker w
JOIN vn.sector s ON s.code = w.code
WHERE s.id = vSectorFk;
SELECT s.id INTO vSectorFk
FROM vn.sector s
WHERE s.warehouseFk = vWarehouseFk
AND s.isMain;
SELECT COUNT(*) INTO hasFatherSector
FROM vn.sector
WHERE sonFk = vSectorFk;
SELECT warehouseFk, sonFk INTO vWarehouseFk, vSonSectorFk
FROM vn.sector
WHERE id = vSectorFk;
CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk);
CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE());
DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar;
IF hasFatherSector THEN
CREATE TEMPORARY TABLE tmp.itemShelvingRadar
(PRIMARY KEY (itemFk))
ENGINE = MEMORY
SELECT *
FROM (
SELECT iss.itemFk,
i.longName,
i.size,
i.subName producer,
IFNULL(a.available,0) available,
SUM(IF(s.sonFk = vSectorFk, IFNULL(iss.visible,0), 0)) upstairs,
SUM(IF(iss.sectorFk = vSectorFk, IFNULL(iss.visible,0), 0)) downstairs,
IF(it.isPackaging, NULL, IFNULL(v.visible,0)) as visible,
vSectorFk sectorFk
FROM vn.itemShelvingStock iss
JOIN vn.sector s ON s.id = iss.sectorFk
JOIN vn.item i on i.id = iss.itemFk
JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk)
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
WHERE vSectorFk IN (iss.sectorFk, s.sonFk)
GROUP BY iss.itemFk
UNION ALL
SELECT v.item_id,
i.longName,
i.size,
i.subName producer,
IFNULL(a.available,0) as available,
0 upstairs,
0 downstairs,
IF(it.isPackaging, NULL, v.visible) visible,
vSectorFk as sectorFk
FROM cache.visible v
JOIN vn.item i on i.id = v.item_id
JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk)
LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id AND iss.warehouseFk = vWarehouseFk
LEFT JOIN cache.available a ON a.item_id = v.item_id AND a.calc_id = vCalcAvailableFk
WHERE v.calc_id = vCalcVisibleFk
AND iss.itemFk IS NULL
AND it.isInventory
) sub GROUP BY itemFk;
SELECT ishr.*,
CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) AS nicho,
CAST(downstairs - IFNULL(notPickedYed,0) AS DECIMAL(10,0)) as pendiente
FROM tmp.itemShelvingRadar ishr
JOIN vn.item i ON i.id = ishr.itemFk
LEFT JOIN (SELECT s.itemFk, sum(s.quantity) as notPickedYed
FROM vn.ticket t
JOIN vn.ticketStateToday tst ON tst.ticketFk = t.id
JOIN vn.sale s ON s.ticketFk = t.id
WHERE t.warehouseFk = vWarehouseFk
AND tst.alertLevel = 0
GROUP BY s.itemFk
) sub ON sub.itemFk = ishr.itemFk
ORDER BY i.typeFk, i.longName;
ELSE
CREATE TEMPORARY TABLE tmp.itemShelvingRadar
(PRIMARY KEY (itemFk))
ENGINE = MEMORY
SELECT iss.itemFk,
0 `hour`,
0 `minute`,
'--' itemPlacementCode,
i.longName,
i.size,
i.subName producer,
i.upToDown,
IFNULL(a.available,0) available,
IFNULL(v.visible - iss.visible,0) dayEndVisible,
IFNULL(v.visible - iss.visible,0) firstNegative,
IFNULL(v.visible - iss.visible,0) itemPlacementVisible,
IFNULL(i.minimum * b.packing,0) 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 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)
OR iss.sectorFk = vSectorFk;
DROP TEMPORARY TABLE IF EXISTS tmp.itemOutTime;
CREATE TEMPORARY TABLE tmp.itemOutTime
SELECT *,SUM(amount) quantity
FROM
(SELECT io.itemFk,
io.quantity 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 itemTicketOut io
JOIN tmp.itemShelvingRadar isr ON isr.itemFk = io.itemFk
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 > util.VN_CURDATE()
AND st.isChecked
) stPrevious ON `stPrevious`.`saleFk` = io.saleFk
WHERE t.warehouseFk = vWarehouseFk
AND s.isPicked = 0
AND NOT io.reserved
AND stPrevious.saleFk IS NULL
AND io.shipped >= util.VN_CURDATE()
AND io.shipped < util.VN_CURDATE() + INTERVAL 1 DAY
) 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);
UPDATE tmp.itemShelvingRadar isr
JOIN (SELECT s.itemFk, sum(s.quantity) amount
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
JOIN ticketLastState tls ON tls.ticketFk = t.id
WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
AND tls.name = 'Prep Camara'
GROUP BY s.itemFk) sub ON sub.itemFk = isr.itemFk
SET isr.dayEndVisible = dayEndVisible + sub.amount,
firstNegative = firstNegative + sub.amount;
SELECT * FROM tmp.itemShelvingRadar;
END IF;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingRadar_Entry`(vEntryFk INT)
BEGIN
DECLARE vWarehouseFk INT DEFAULT 1;
DECLARE vCalcVisibleFk INT;
DECLARE vCalcAvailableFk INT;
DECLARE vTodayDayEnd DATETIME DEFAULT util.dayEnd(util.VN_CURDATE());
CALL cache.visible_refresh(vCalcVisibleFk, FALSE, 1);
CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_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 util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingRadar_Entry_State_beta` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingRadar_Entry_State_beta`(vEntryFk INT)
BEGIN
DECLARE vWarehouseFk INT DEFAULT 1;
DECLARE vCalcVisibleFk INT;
DECLARE vCalcAvailableFk INT;
DECLARE vTodayDayEnd DATETIME DEFAULT util.dayEnd(util.VN_CURDATE());
CALL cache.visible_refresh(vCalcVisibleFk, FALSE, 1);
CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_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,
CAST(IFNULL(iss.visible,0) - IFNULL(v.visible,0) AS DECIMAL(10,0)) as outShelving
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 vn.itemShelvingStock iss ON iss.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_Add`(vItemShelvingFk INT, vSaleFk INT, vQuantity INT)
BEGIN
/**
* Añade línea a itemShelvingSale y regulariza el carro
*
* @param vItemShelvingFk Id itemShelving
* @param vSaleFk Id de sale
* @param vQuantity cantidad a regularizar
*/
INSERT INTO itemShelvingSale(itemShelvingFk,
saleFk,
quantity,
userFk)
VALUES (vItemShelvingFk,
vSaleFk,
vQuantity,
getUser());
UPDATE itemShelving
SET visible = visible - vQuantity
WHERE id = vItemShelvingFk;
UPDATE vn.saleTracking
SET isChecked = 1
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reserve` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reserve`()
BEGIN
/**
* Reserva cantidades con ubicaciones para un conjunto de sales del mismo
* almacen.
*
* @table tmp.sale(saleFk, userFk)
*/
DECLARE vCalcFk INT;
DECLARE vWarehouseFk INT;
DECLARE vCurrentYear INT DEFAULT YEAR(util.VN_NOW());
DECLARE vLastPickingOrder INT;
SELECT t.warehouseFk, MAX(p.pickingOrder)
INTO vWarehouseFk, vLastPickingOrder
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN tmp.sale ts ON ts.saleFk = s.id
LEFT JOIN itemShelvingSale iss ON iss.saleFk = ts.saleFk
LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
LEFT JOIN shelving sh ON sh.code = ish.shelvingFk
LEFT JOIN parking p ON p.id = sh.parkingFk
WHERE t.warehouseFk IS NOT NULL;
IF vWarehouseFk IS NULL THEN
CALL util.throw('Warehouse not set');
END IF;
CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk);
SET @outstanding = 0;
SET @oldsaleFk = 0;
CREATE OR REPLACE TEMPORARY TABLE tSalePlacementQuantity
(INDEX(saleFk))
ENGINE = MEMORY
SELECT saleFk, userFk, quantityToReserve, itemShelvingFk
FROM( SELECT saleFk,
sub.userFk,
itemShelvingFk ,
IF(saleFk <> @oldsaleFk, @outstanding := quantity, @outstanding),
@qtr := LEAST(@outstanding, available) quantityToReserve,
@outStanding := @outStanding - @qtr,
@oldsaleFk := saleFk
FROM(
SELECT ts.saleFk,
ts.userFk,
s.quantity,
ish.id itemShelvingFk,
ish.visible - IFNULL(ishr.reservedQuantity, 0) available
FROM tmp.sale ts
JOIN sale s ON s.id = ts.saleFk
JOIN itemShelving ish ON ish.itemFk = s.itemFk
LEFT JOIN (
SELECT itemShelvingFk, SUM(quantity) reservedQuantity
FROM itemShelvingSale
WHERE NOT isPicked
GROUP BY itemShelvingFk) ishr ON ishr.itemShelvingFk = ish.id
JOIN shelving sh ON sh.code = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector sc ON sc.id = p.sectorFk
JOIN warehouse w ON w.id = sc.warehouseFk
JOIN productionConfig pc
WHERE w.id = vWarehouseFk
AND NOT sc.isHideForPickers
ORDER BY
s.id,
p.pickingOrder >= vLastPickingOrder,
sh.priority DESC,
ish.visible >= s.quantity DESC,
s.quantity MOD ish.grouping = 0 DESC,
ish.grouping DESC,
IF(pc.orderMode = 'Location', p.pickingOrder, ish.created)
)sub
)sub2
WHERE quantityToReserve > 0;
INSERT INTO itemShelvingSale(
itemShelvingFk,
saleFk,
quantity,
userFk)
SELECT itemShelvingFk,
saleFk,
quantityToReserve,
IFNULL(userFk, getUser())
FROM tSalePlacementQuantity spl;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reserveByCollection` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reserveByCollection`(
vCollectionFk INT(11)
)
BEGIN
/**
* Reserva cantidades con ubicaciones para el contenido de una colección
*
* @param vCollectionFk Identificador de collection
*/
CREATE OR REPLACE TEMPORARY TABLE tmp.sale
(INDEX(saleFk))
ENGINE = MEMORY
SELECT s.id saleFk, NULL userFk
FROM ticketCollection tc
JOIN sale s ON s.ticketFk = tc.ticketFk
LEFT JOIN (
SELECT DISTINCT saleFk
FROM saleTracking st
JOIN state s ON s.id = st.stateFk
WHERE st.isChecked
AND s.semaphore = 1)st ON st.saleFk = s.id
WHERE tc.collectionFk = vCollectionFk
AND st.saleFk IS NULL
AND NOT s.isPicked;
CALL itemShelvingSale_reserve();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reserveBySale` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reserveBySale`(
vSelf INT ,
vQuantity INT,
vUserFk INT
)
BEGIN
/**
* Reserva cantida y ubicación para una saleFk
*
* @param vSelf Identificador de la venta
* @param vQuantity Cantidad a reservar
* @param vUserFk Id de usuario que realiza la reserva
*/
CREATE OR REPLACE TEMPORARY TABLE tmp.sale
ENGINE = MEMORY
SELECT vSelf saleFk, vUserFk userFk;
CALL itemShelvingSale_reserve();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_setQuantity` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_setQuantity`(
vItemShelvingSaleFk INT(10),
vQuantity DECIMAL(10,0),
vIsItemShelvingSaleEmpty BOOLEAN
)
BEGIN
/**
* Gestiona la reserva de un itemShelvingFk, actualizando isPicked y quantity
* en vn.itemShelvingSale y vn.sale.isPicked en caso necesario.
* Si la reserva de la ubicación es fallida, se regulariza la situación
*
* @param vItemShelvingSaleFk Id itemShelvingSaleFK
* @param vQuantity Cantidad real que se ha cogido de la ubicación
* @param vIsItemShelvingSaleEmpty determina si ka ubicación itemShelvingSale se ha
* quedado vacio tras el movimiento
*/
DECLARE vSaleFk INT;
DECLARE vCursorSaleFk INT;
DECLARE vItemShelvingFk INT;
DECLARE vReservedQuantity INT;
DECLARE vRemainingQuantity INT;
DECLARE vItemFk INT;
DECLARE vUserFk INT;
DECLARE vDone BOOLEAN DEFAULT FALSE;
DECLARE vSales CURSOR FOR
SELECT iss.saleFk, iss.userFk
FROM itemShelvingSale iss
JOIN sale s ON s.id = iss.saleFk
WHERE iss.id = vItemShelvingSaleFk
AND s.itemFk = vItemFk
AND NOT iss.isPicked;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
IF (SELECT isPicked FROM itemShelvingSale WHERE id = vItemShelvingSaleFk) THEN
CALL util.throw('Booking completed');
END IF;
SELECT s.itemFk, iss.saleFk, iss.itemShelvingFk
INTO vItemFk, vSaleFk, vItemShelvingFk
FROM itemShelvingSale iss
JOIN sale s ON s.id = iss.saleFk
WHERE iss.id = vItemShelvingSaleFk
AND NOT iss.isPicked;
UPDATE itemShelvingSale
SET isPicked = TRUE,
quantity = vQuantity
WHERE id = vItemShelvingSaleFk;
UPDATE itemShelving
SET visible = IF(vIsItemShelvingSaleEmpty, 0, GREATEST(0,visible - vQuantity))
WHERE id = vItemShelvingFk;
IF vIsItemShelvingSaleEmpty THEN
OPEN vSales;
l: LOOP
SET vDone = FALSE;
FETCH vSales INTO vCursorSaleFk, vUserFk;
IF vDone THEN
LEAVE l;
END IF;
CREATE OR REPLACE TEMPORARY TABLE tmp.sale
(INDEX(saleFk, userFk))
ENGINE = MEMORY
SELECT vCursorSaleFk, vUserFk;
CALL itemShelvingSale_reserveWhitUser();
DROP TEMPORARY TABLE tmp.sale;
END LOOP;
CLOSE vSales;
DELETE iss
FROM itemShelvingSale iss
JOIN sale s ON s.id = iss.saleFk
WHERE iss.id = vItemShelvingSaleFk
AND s.itemFk = vItemFk
AND NOT iss.isPicked;
END IF;
SELECT SUM(quantity) INTO vRemainingQuantity
FROM itemShelvingSale
WHERE saleFk = vSaleFk
AND NOT isPicked;
IF vRemainingQuantity THEN
CALL itemShelvingSale_reserveBySale (vSaleFk, vRemainingQuantity, NULL);
SELECT SUM(quantity) INTO vRemainingQuantity
FROM itemShelvingSale
WHERE saleFk = vSaleFk
AND NOT isPicked;
IF NOT vRemainingQuantity <=> 0 THEN
SELECT SUM(iss.quantity)
INTO vReservedQuantity
FROM itemShelvingSale iss
WHERE iss.saleFk = vSaleFk;
CALL saleTracking_new(
vSaleFk,
TRUE,
vReservedQuantity,
`account`.`myUser_getId`(),
NULL,
'PREPARED',
TRUE);
UPDATE sale s
SET s.quantity = vReservedQuantity
WHERE s.id = vSaleFk ;
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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingTransfer`(vItemShelvingFk INT, vShelvingFk VARCHAR(3))
BEGIN
/**
* Transfiere producto de una ubicación a otra, fusionando si coincide el
* packing y la fecha.
*
* @param vItemShelvingFk Identificador de itemShelving
* @param vShelvingFk Identificador de shelving
*/
DECLARE vNewItemShelvingFk INT DEFAULT 0;
SELECT MAX(ish.id)
INTO vNewItemShelvingFk
FROM itemShelving ish
JOIN (
SELECT
itemFk,
packing,
created
FROM itemShelving
WHERE id = vItemShelvingFk
) ish2
ON ish2.itemFk = ish.itemFk
AND ish2.packing = ish.packing
AND date(ish2.created) = date(ish.created)
WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci;
IF vNewItemShelvingFk THEN
UPDATE itemShelving ish
JOIN itemShelving ish2 ON ish2.id = vItemShelvingFk
SET ish.visible = ish.visible + ish2.visible
WHERE ish.id = vNewItemShelvingFk;
DELETE FROM itemShelving
WHERE id = vItemShelvingFk;
ELSE
UPDATE itemShelving
SET shelvingFk = vShelvingFk
WHERE id = vItemShelvingFk;
END IF;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT)
BEGIN
/**
* Añade registro o lo actualiza si ya existe.
*
* @param vShelvingFk matrícula del carro
* @param vBarcode el id del registro
* @param vQuantity indica la cantidad del producto
* @param vPackagingFk el packaging del producto en itemShelving, NULL para coger el de la ultima compra
* @param vGrouping el grouping del producto en itemShelving, NULL para coger el de la ultima compra
* @param vPacking el packing del producto, NULL para coger el de la ultima compra
* @param vWarehouseFk indica el sector
*
**/
DECLARE vItemFk INT;
SELECT barcodeToItem(vBarcode) INTO vItemFk;
IF vPacking IS NULL
THEN
SET vPacking = itemPacking(vBarcode, vWarehouseFk);
SET vQuantity = vQuantity * vPacking;
END IF;
IF (SELECT COUNT(*) FROM itemShelving
WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
AND itemFk = vItemFk
AND packing = vPacking) = 1 THEN
UPDATE itemShelving
SET visible = visible+vQuantity
WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking;
ELSE
CALL cache.last_buy_refresh(FALSE);
INSERT INTO itemShelving( itemFk,
shelvingFk,
visible,
grouping,
packing,
packagingFk)
SELECT vItemFk,
vShelvingFk,
vQuantity,
IFNULL(vGrouping, b.grouping),
IFNULL(vPacking, b.packing),
IFNULL(vPackagingFk, b.packagingFk)
FROM item i
LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk
LEFT JOIN buy b ON b.id = lb.buy_id
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_addByClaim` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_addByClaim`(vClaimFk INT, vShelvingFk VARCHAR(3))
BEGIN
/**
* Insert items of claim into itemShelving.
*
* @param vClaimFk The claim
* @param vShelvingFk The shelving
* @table tmp.buyUltimate
*/
DECLARE vWarehouseFk INT;
SELECT t.warehouseFk INTO vWarehouseFk
FROM claim c
JOIN ticket t ON t.id = c.ticketFk
WHERE c.id = vClaimFk;
CALL buyUltimate (vWarehouseFk, util.VN_CURDATE());
INSERT INTO itemShelving (itemFk, shelvingFk, packing, `grouping`, visible)
SELECT s.itemFk, vShelvingFk, b.packing, b.`grouping`, cb.quantity AS visible
FROM claim c
JOIN claimBeginning cb ON c.id = cb.claimFk
JOIN sale s ON s.id = cb.saleFk
JOIN ticket t ON t.id = s.ticketFk
JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk AND bu.warehouseFk = t.warehouseFk
JOIN buy b ON b.id = bu.buyFk
WHERE c.id = vClaimFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_addList` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_addList`(vShelvingFk VARCHAR(3), vList TEXT, vIsChecking BOOL, vWarehouseFk INT)
BEGIN
/* Recorre cada elemento en la colección vList.
* Si el parámetro isChecking = FALSE, llama a itemShelving_add.
*
* Cuando es TRUE sólo inserta los elementos de la colección que no están ya en
* ese shelving, actualizando los valores del campo vn.itemShelving.isChecked
*
* param vShelvingFk Identificador de vn.shelving
* param vList JSON array con esta estructura: '[value1, value2, ...]'
* param vIsChecking Define si hay que añadir o comprobar los items
* param vWarehouseFk Identificador de vn.warehouse
*/
DECLARE vListLength INT DEFAULT JSON_LENGTH(vList);
DECLARE vCounter INT DEFAULT 0;
DECLARE vBarcode VARCHAR(22);
DECLARE vPath VARCHAR(6);
DECLARE vItemFk INT;
DECLARE vIsChecked BOOL;
WHILE vCounter < vListLength DO
SET vPath = CONCAT('$[',vCounter,']');
SET vBarcode = JSON_EXTRACT(vList,vPath);
SET vIsChecked = NULL;
IF vIsChecking THEN
SELECT barcodeToItem(vBarcode) INTO vItemFk;
SELECT COUNT(*) INTO vIsChecked
FROM vn.itemShelving
WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
AND itemFk = vItemFk;
END IF;
IF NOT (vIsChecking AND vIsChecked) THEN
CALL vn.itemShelving_add(vShelvingFk, vBarcode, 1, NULL, NULL, NULL, vWarehouseFk);
END IF;
UPDATE vn.itemShelving
SET isChecked = vIsChecked
WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk
AND itemFk = vItemFk AND isChecked IS NULL;
SET vCounter = vCounter + 1;
END WHILE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_filterBuyer` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_filterBuyer`(vBuyerFk INT, vWarehouseFk INT)
proc:BEGIN
/**
* Lista de articulos filtrados por comprador
*
* @param vBuyerFk Comprador a filtrar
* @param vWarehouseFk Warehouse
* @return Lista de articulos
*/
DECLARE vCalcVisibleFk INT;
CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk);
SELECT * FROM
(SELECT sub.itemFk,
sub.longName,
CONCAT('Hoy saldrán ', CAST(sub2.pendiente AS DECIMAL(10,0)), ' unidades.') `size`,
CONCAT(IF(sub2.itemFk, IF(sub2.pendiente > (sub.upstairs + sub.downstairs),'(1) ','(2) '),'(3) ' ),sub.producer) producer,
sub.upstairs,
sub.downstairs,
sub.visible,
CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) nicho,
sub.name itemColour
FROM (SELECT iss.itemFk,
CONCAT(i.longName, ' ', IFNULL(i.size, ''),' ', IFNULL(i.subName, '') ) longName,
'' size,
CONCAT(iss.parkingCode, ' ', iss.shelvingFk) producer,
0 upstairs,
SUM(IFNULL(iss.visible,0)) downstairs,
IF(it.isPackaging, null, IFNULL(v.visible, 0)) visible,
ik.name
FROM itemShelvingStock iss
JOIN sector s ON s.id = iss.sectorFk
JOIN item i on i.id = iss.itemFk
LEFT JOIN ink ik ON ik.id = i.inkFk
JOIN itemType it ON it.id = i.typeFk
LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk
WHERE s.warehouseFk = vWarehouseFk
AND it.workerFk = vBuyerFk
GROUP BY itemFk
) sub LEFT JOIN (SELECT s.itemFk, SUM(s.quantity) pendiente
FROM sale s
LEFT JOIN saleTracking st ON st.saleFk = s.id
JOIN ticket t ON t.id = s.ticketFk
JOIN client c on c.id = t.clientFk
WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
AND st.saleFk IS NULL
AND c.typeFk IN ('normal', 'trust')
GROUP BY s.itemFk
) sub2 ON sub2.itemFk = sub.itemFk
UNION ALL
SELECT v.item_id,
i.longName,
CONCAT('Hoy saldrán ', CAST(sub5.pendiente AS DECIMAL(10,0)), ' unidades.') `size`,
CONCAT(IF(sub5.pendiente,'(0) ','(3) ')) producer,
0,
0,
v.visible,
v.visible nicho,
ik.name itemColour
FROM cache.visible v
JOIN item i ON i.id = v.item_id
LEFT JOIN ink ik ON ik.id = i.inkFk
JOIN itemType it ON it.id = i.typeFk
LEFT JOIN itemShelvingStock iss ON iss.itemFk = v.item_id AND iss.warehouseFk = vWarehouseFk
LEFT JOIN (SELECT s.itemFk, SUM(s.quantity) pendiente
FROM sale s
LEFT JOIN saleTracking st ON st.saleFk = s.id
JOIN ticket t ON t.id = s.ticketFk
JOIN client c on c.id = t.clientFk
WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
AND st.saleFk IS NULL
AND c.typeFk IN ('normal', 'trust')
GROUP BY s.itemFk
) sub5 ON sub5.itemFk = v.item_id
WHERE v.calc_id = vCalcVisibleFk
AND iss.itemFk IS NULL
AND it.workerFk = vBuyerFk
) sub3
WHERE nicho
ORDER BY producer;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_get`(IN vSelf VARCHAR(8))
BEGIN
/**
* Lista artículos de itemshelving
*
* @param vSelf matrícula del carro
**/
SELECT ish.itemFk item,
IFNULL(i.longName, CONCAT(i.name, ' ', i.size)) description,
ish.visible,
CEIL(ish.visible/ish.packing) stickers,
ish.packing,
ish.grouping,
p.code,
ish.id,
s.priority,
ish.isChecked,
ic.url
FROM itemShelving ish
JOIN item i ON i.id = ish.itemFk
JOIN shelving s ON vSelf = s.code COLLATE utf8_unicode_ci
LEFT JOIN parking p ON s.parkingFk = p.id
JOIN hedera.imageConfig ic
WHERE ish.shelvingFk COLLATE utf8_unicode_ci = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_getAlternatives` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_getAlternatives`(vShelvingFk VARCHAR(10))
BEGIN
/**
* Devuelve un listado de posibles ubicaciones alternativas a ubicar los item de la matricula
* del carro que se le ha pasado.
*
* @param vShelvingFk matricula del carro
*/
SELECT is2.id,is2.shelvingFk , p.code, is2.itemFk , is2.visible, p.pickingOrder
FROM itemShelving is2
JOIN shelving sh ON sh.code = is2.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector s ON s.id = p.sectorFk
LEFT JOIN operator o ON o.sectorFk = s.id AND o.workerFk = account.myUser_getId()
JOIN warehouse wh ON wh.id = s.warehouseFk
JOIN itemShelving is3 ON is3.itemFk = is2.itemFk AND is3.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci
WHERE is2.shelvingFk <> vShelvingFk COLLATE utf8_unicode_ci
GROUP BY is2.id
ORDER BY p.pickingOrder 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_getInfo` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_getInfo`(vItemFk VARCHAR(22))
BEGIN
/**
* Muestra información realtiva a la ubicación de un item
*
* @param vItemFk Id del item
*/
SELECT vn.barcodeToItem(vItemFk)
INTO vItemFk;
SELECT pk.code Parking,
sh.code Matricula,
ish.visible visible,
ish.created created,
ish.itemFk itemFk,
sh.priority
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
ORDER BY sh.priority DESC, created 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_getSaleDate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_getSaleDate`(vShelvingFk VARCHAR(3))
BEGIN
/* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula.
*
* @param vShelvingFk Matrícula del carro o pallet
*/
DECLARE vWarehouseFk INT;
DECLARE vStockScopeDays INT;
SELECT s.warehouseFk, stockScopeDays
INTO vWarehouseFk, vStockScopeDays
FROM sector s
JOIN operator o ON s.id = o.sectorFk
JOIN productionConfig pc
WHERE o.workerFk = account.myUser_getId();
IF vWarehouseFk IS NULL
THEN CALL util.throw('WarehouseFk not setted');
END IF;
IF vStockScopeDays IS NULL
THEN CALL util.throw('StockScopeDays not setted');
END IF;
CREATE OR REPLACE TEMPORARY TABLE tmp.tItems
(PRIMARY KEY (itemFk))
ENGINE = MEMORY
SELECT itemFk, SUM(visible) visible
FROM itemShelving
WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci
GROUP BY itemFk;
CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay
(INDEX (itemFk, dated))
ENGINE = MEMORY
SELECT dated,
SUM(t3.amount) OVER (PARTITION BY t3.itemFk ORDER BY dated) stock,
t3.itemFk
FROM (
SELECT t.itemFk, dated, SUM(amount) amount
FROM (
SELECT t2.itemFk, t2.amount, t2.dated
FROM (
SELECT item_id itemFk, amount, util.VN_CURDATE() dated
FROM cache.stock s
JOIN tmp.tItems i ON i.itemFk = s.item_id
WHERE s.warehouse_id = vWarehouseFk
UNION ALL
SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE()
FROM itemShelving ish
JOIN tmp.tItems i ON i.itemFk = ish.itemFk
JOIN shelving sh ON sh.code = ish.shelvingFk
JOIN parking p ON sh.parkingFk = p.id
JOIN sector s ON s.id = p.sectorFk
WHERE s.isReserve
GROUP BY ish.itemFk
UNION ALL
SELECT iei.itemFk, SUM(quantity), landed
FROM itemEntryIn iei
JOIN tmp.tItems i ON i.itemFk = iei.itemFk
WHERE iei.landed BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY
AND iei.warehouseInFk = vWarehouseFk
AND NOT isVirtualStock
GROUP BY iei.itemFk, iei.landed
UNION ALL
SELECT ieo.itemFk, SUM(quantity), shipped
FROM itemEntryOut ieo
JOIN tmp.tItems i ON i.itemFk = ieo.itemFk
WHERE ieo.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY
AND ieo.warehouseOutFk = vWarehouseFk
GROUP BY ieo.itemFk, ieo.shipped
UNION ALL
SELECT i.itemFk, SUM(ito.quantity), DATE(ito.shipped)
FROM itemTicketOut ito
JOIN tmp.tItems i ON i.itemFk = ito.itemFk
WHERE ito.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY
AND ito.warehouseFk = vWarehouseFk
GROUP BY ito.itemFk, ito.shipped
) t2
JOIN tmp.tItems i ON i.itemFk = t2.itemFk)t
GROUP BY t.itemFk, dated
) t3;
-- Se restan las entradas de hoy
UPDATE tmp.tStockByDay sbd
JOIN (SELECT iei.itemFk, SUM(quantity) todayEntry
FROM itemEntryIn iei
JOIN tmp.tItems i ON i.itemFk = iei.itemFk
WHERE iei.landed = util.VN_CURDATE()
AND iei.warehouseInFk = vWarehouseFk
AND NOT iei.isVirtualStock) sub ON sub.itemFk = sbd.itemFk
SET sbd.stock = sbd.stock - sub.todayEntry
WHERE sbd.dated = util.VN_CURDATE();
-- Se añaden las lineas de venta servidas
UPDATE tmp.tStockByDay sbd
JOIN (SELECT s.itemFK, SUM(quantity) amount
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
WHERE t.warehouseFk = vWarehouseFk
AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight()
AND s.isPicked
GROUP BY s.itemFk) sub ON sub.itemFk = sbd.itemFk
SET sbd.stock = sbd.stock + sub.amount;
-- Se añaden los items ubicados hoy
UPDATE tmp.tStockByDay sbd
JOIN (SELECT ish.itemFK, SUM(ish.visible) amount
FROM itemShelving ish
JOIN shelving sh ON sh.code = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector s ON s.id = p.sectorFk
WHERE s.warehouseFk = vWarehouseFk
AND NOT s.isReserve
AND ish.created BETWEEN util.VN_CURDATE() AND util.midnight()
GROUP BY ish.itemFk) sub ON sub.itemFk = sbd.itemFk
SET sbd.stock = sbd.stock + sub.amount;
SELECT ts.itemFk,
i.longName,
IF(ts.stock<=0, ts.dated, NULL) dated,
ts.stock,
sub4.visible,
sub4.shelvingFk
FROM(
SELECT IFNULL(sub2.minDated, sub.minDated) dated,
IFNULL(sub2.itemFk, sub.itemFk) itemFk
FROM(SELECT sbd.itemFk,
MIN(dated) minDated,
sbd.stock
FROM tmp.tItems ti
LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk
GROUP BY itemFk)sub
LEFT JOIN (
SELECT sbd.itemFk,
MIN(dated) minDated,
sbd.stock
FROM tmp.tItems ti
LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk
WHERE sbd.stock <= 0
GROUP BY itemFk)sub2 ON sub2.itemFk =sub.itemFk
WHERE sub2.itemFk IS NOT NULL
OR (sub2.itemFk IS NULL AND sub.itemFk IS NOT NULL)) sub3
LEFT JOIN tmp.tStockByDay ts ON ts.itemFk = sub3.itemFk AND ts.dated = sub3.dated
JOIN (SELECT ish.itemFk,
ish.visible,
p.sectorFk,
ish.shelvingFk
FROM itemShelving ish
JOIN vn.shelving sh ON sh.code = ish.shelvingFk
LEFT JOIN parking p ON p.id = parkingFk
LEFT JOIN vn.sector s ON s.id = p.sectorFk
WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci
) sub4 ON sub4.itemFk = ts.itemFk
LEFT JOIN sector s ON s.id = sub4.sectorFk
LEFT JOIN item i ON i.id = ts.itemFk
WHERE NOT s.isReserve;
DROP TEMPORARY TABLE tmp.tStockByDay, tmp.tItems;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_inventory` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_inventory`(vParkingFromFk VARCHAR(8), vParkingToFk VARCHAR(8))
BEGIN
/**
* Devuelve un listado de ubicaciones a revisar
*
* @param vParkingFromFk Parking de partida, identificador de parking
* @param vParkingToFk Parking de llegada, identificador de parking
*/
DECLARE vSectorFk INT;
DECLARE vPickingOrderFrom INT;
DECLARE vPickingOrderTo INT;
SELECT p.sectorFk, p.pickingOrder INTO vSectorFk, vPickingOrderFrom
FROM parking p
WHERE p.code = vParkingFromFk COLLATE 'utf8mb3_general_ci';
SELECT p.pickingOrder INTO vPickingOrderTo
FROM parking p
WHERE p.code = vParkingToFk COLLATE 'utf8mb3_general_ci';
CALL visible_getMisfit(vSectorFk);
SELECT ish.id,
p.pickingOrder,
p.code parking,
ish.shelvingFk,
ish.itemFk,
i.longName,
ish.visible,
p.sectorFk,
it.workerFk buyer,
ic.url,
i.image,
ish.isChecked,
CASE
WHEN IFNULL (s.notPrepared, 0) > sm.parked THEN 0
WHEN sm.visible > sm.parked THEN 1
ELSE 2
END priority
FROM itemShelving ish
JOIN item i ON i.id = ish.itemFk
JOIN itemType it ON it.id = i.typeFk
JOIN tmp.stockMisfit sm ON sm.itemFk = ish.itemFk
JOIN shelving sh ON sh.code = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
LEFT JOIN (
SELECT s.itemFk, sum(s.quantity) notPrepared
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
JOIN warehouse w ON w.id = t.warehouseFk
JOIN config c ON c.mainWarehouseFk = w.id
WHERE t.shipped BETWEEN util.VN_CURDATE()
AND util.dayEnd(util.VN_CURDATE())
AND s.isPicked = FALSE
GROUP BY s.itemFk
) s ON s.itemFk = i.id
JOIN hedera.imageConfig ic
WHERE p.pickingOrder BETWEEN vPickingOrderFrom AND vPickingOrderTo
AND p.sectorFk = vSectorFk
ORDER BY p.pickingOrder;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_selfConsumption` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_selfConsumption`(
vShelvingFk VARCHAR(10) COLLATE utf8_general_ci,
vItemFk INT,
vQuantity INT
)
BEGIN
/**
* Leave the indicated amount on the shelf
* and create a ticket with the difference.
*
* @param vShelvingFk id of the shelf where the item is located.
* @param vItemFk article of which the self-consumption ticket is to be created.
* @param vQuantity amount that will stay on the shelf
*/
DECLARE vVisible INT;
DECLARE vClientFk INT;
DECLARE vTicketFk INT;
DECLARE vWarehouseFk INT;
DECLARE vCompanyFk INT;
DECLARE vAgencyModeFk INT;
DECLARE vItemShelvingFk INT;
DECLARE vAddressFk INT;
SELECT c.id,
pc.clientSelfConsumptionFk,
s.warehouseFk,
pc.addressSelfConsumptionFk
INTO vCompanyFk,
vClientFk,
vWarehouseFk,
vAddressFk
FROM company c
JOIN address a ON a.clientFk = c.clientFk
JOIN warehouse w ON w.addressFk = a.id
JOIN sector s ON s.warehouseFk = w.id
JOIN parking p ON p.sectorFk = s.id
JOIN shelving s2 ON s2.parkingFk = p.id
JOIN productionConfig pc
WHERE s2.code = vShelvingFk;
IF vClientFk IS NULL THEN
CALL util.throw('The company does not have a customer assigned');
END IF;
IF vQuantity IS NULL OR vQuantity < 0 THEN
CALL util.throw('The shelf cannot have NULL or negative quantities');
END IF;
IF vShelvingFk IS NULL THEN
CALL util.throw('The shelf is necessary');
END IF;
IF vItemFk IS NULL THEN
CALL util.throw('The article is required to create the ticket.');
END IF;
SELECT SUM(visible), id INTO vVisible, vItemShelvingFk
FROM itemShelving
WHERE shelvingFk = vShelvingFk
AND itemFk = vItemFk;
IF vVisible IS NULL THEN
CALL util.throw('The item is not on the shelf.');
END IF;
CALL ticket_getWithParameters(
vClientFk,
vWarehouseFk,
CURDATE(),
vAddressFk,
vCompanyFk,
NULL,
vTicketFk
);
INSERT INTO sale (itemFk, ticketFk, quantity, concept)
SELECT vItemFk, vTicketFk, (vVisible - vQuantity), longName
FROM item
WHERE id = vItemFk;
UPDATE itemShelving
SET visible = IF(id = vItemShelvingFk, vQuantity, 0)
WHERE shelvingFk = vShelvingFk
AND itemFk = vItemFk;
CALL vn.ticket_setState(vTicketFk, 'DELIVERED');
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_update`(vVisible INT, vPacking INT, vShelf INT ,vGrouping INT )
BEGIN
/**
* Actualiza itemShelving.
*
* @param vVisible la cantidad visible del registro a actualizar
* @param vShelf el id del registro a actualizar
* @param vPacking el packing del del producto en itemShelving
* @param vGrouping el grouping del producto en itemShelving
*/
UPDATE itemShelving
SET visible = vVisible,
packing = vPacking,
grouping = vGrouping
WHERE id = vShelf;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTagReorder`(itemTypeFk INT)
BEGIN
SET @isTriggerDisabled = TRUE;
-- No se puede usar temporary porque da error Error Code: 1137. No puedo reabrir tabla: 'i
DROP TABLE IF EXISTS tmp.item;
CREATE TABLE tmp.item
SELECT DISTINCT i.id
FROM vn.item i
WHERE i.typeFk = itemTypeFk;
UPDATE itemTag it
JOIN tmp.item i ON i.id = it.itemFk
JOIN vn.item ON item.id = i.id
JOIN itemTypeTag itt ON itt.itemTypeFk = item.typeFk AND itt.tagFk = it.tagFk
SET it.priority = itt.priority
WHERE itt.itemTypeFk = itemTypeFk;
CALL item_refreshTags();
SET @isTriggerDisabled = FALSE;
DROP 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTagReorderByName`(vName VARCHAR(255))
BEGIN
SET @isTriggerDisabled = TRUE;
-- No se puede usar temporary porque da error Error Code: 1137. No puedo reabrir tabla: 'i
DROP TABLE IF EXISTS tmp.item;
CREATE TABLE tmp.item
SELECT DISTINCT i.id
FROM vn.item i
WHERE i.`name` LIKE CONCAT(vName,'%');
UPDATE itemTag it
JOIN tmp.item i ON i.id = it.itemFk
JOIN vn.item ON item.id = i.id
JOIN itemTypeTag itt ON itt.itemTypeFk = item.typeFk AND itt.tagFk = it.tagFk
SET it.priority = itt.priority
WHERE itt.itemTypeFk = itemTypeFk;
CALL item_refreshTags();
SET @isTriggerDisabled = FALSE;
DROP 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemTag_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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTag_replace`(vItemFromFk INT, vItemToFk INT, vPicture VARCHAR(100))
BEGIN
/* Reemplaza los tags de un artículo por los de otro, así como su imagen
*
* @param vItemFromFk id de vn.item con el artículo del que se toman los tags
* @param vItemToFk id de vn.item con el artículo del que se toman los tags
* @param vPicture imagen del artículo. Opcional. Si no se especifica, hereada la del vItemFromFk
*/
DELETE FROM vn.itemTag
WHERE itemFk = vItemToFk;
INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT vItemToFk, tagFk, value, priority
FROM vn.itemTag
WHERE itemFk = vItemFromFk;
IF ISNULL(vPicture) THEN
SELECT image INTO vPicture
FROM vn.item
WHERE id = vItemFromFk;
END IF;
UPDATE vn.item i
SET i.image = vPicture
WHERE i.id = vItemToFk;
CALL vn.itemRefreshTags(vItemToFk);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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, util.VN_CURDATE()) AND util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `itemTrash` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTrash`(
vItemFk INT,
vWarehouseFk INT,
vQuantity INT,
vIsTrash BOOLEAN)
BEGIN
DECLARE vTicketFk INT;
DECLARE vClientFk INT;
DECLARE vCompanyVnlFk INT DEFAULT 442;
DECLARE vCalc INT;
SELECT barcodeToItem(vItemFk) INTO vItemFk;
SELECT IF(vIsTrash, 200, 400) INTO vClientFk;
SELECT t.id INTO vTicketFk
FROM ticket t
JOIN address a ON a.id=t.addressFk
WHERE t.warehouseFk = vWarehouseFk
AND t.clientFk = vClientFk
AND DATE(t.shipped) = util.VN_CURDATE()
AND a.isDefaultAddress
LIMIT 1;
CALL cache.visible_refresh(vCalc, TRUE, vWarehouseFk);
IF vTicketFk IS NULL THEN
CALL ticket_add(
vClientFk,
util.VN_CURDATE(),
vWarehouseFk,
vCompanyVnlFk,
NULL,
NULL,
NULL,
util.VN_CURDATE(),
account.myUser_getId(),
FALSE,
vTicketFk);
END IF;
INSERT INTO sale(ticketFk, itemFk, concept, quantity)
SELECT vTicketFk,
vItemFk,
CONCAT(longName,' ',worker_getCode(), ' ', LEFT(CAST(util.VN_NOW() AS TIME),5)),
vQuantity
FROM item
WHERE id = vItemFk;
UPDATE cache.visible
SET visible = visible - vQuantity
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_cleanFloramondo` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_cleanFloramondo`()
BEGIN
/**
* Elimina todos los items repetidos de floramondo
* y los sustituye por el que tiene menor id
*/
DECLARE vItemFrom INT;
DECLARE vItemEnd INT;
DECLARE vItemOld INT;
DECLARE vItemNew INT;
DECLARE vCurrentItem INT;
DECLARE vQuantity INT;
DECLARE vCounter INT DEFAULT 0;
DECLARE vIsStop BOOL DEFAULT FALSE;
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE curItemClean CURSOR FOR
SELECT GREATEST(i.id, i2.id) idOld,
LEAST(i.id, i2.id) idNew
FROM item i
JOIN (
SELECT i.id,
i.name,
i.subname,
i.value5,
i.value6,
i.value7,
i.value8,
i.value9,
i.value10,
i.NumberOfItemsPerCask,
i.EmbalageCode,
i.quality
FROM item i
LEFT JOIN (
SELECT i.id,
sr.NumberOfUnits,
MAX(di.LatestOrderDateTime) lodt
FROM item i
JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk
JOIN edi.deliveryInformation di ON di.supplyResponseID = i.supplyResponseFk
GROUP BY i.id
)sub ON sub.id = i.id
WHERE i.isFloramondo
AND (i.supplyResponseFk IS NULL
OR sub.NumberOfUnits = 0
OR sub.lodt < util.VN_NOW())
GROUP BY i.name,
i.subname,
i.value5,
i.value6,
i.value7,
i.value8,
i.value9,
i.value10,
i.NumberOfItemsPerCask,
i.EmbalageCode,
i.quality
) i2 ON i2.name <=> i.name
AND i2.subname <=> i.subname
AND i2.value5 <=> i.value5
AND i2.value6 <=> i.value6
AND i2.value7 <=> i.value7
AND i2.value8 <=> i.value8
AND i2.value9 <=> i.value9
AND i2.value10 <=> i.value10
AND i2.NumberOfItemsPerCask <=> i.NumberOfItemsPerCask
AND i2.EmbalageCode <=> i.EmbalageCode
AND i2.quality <=> i.quality
JOIN (
SELECT DISTINCT b.itemFk
FROM buy b
JOIN item i ON i.id = b.itemFk
WHERE i.isFloramondo
AND NOT b.printedStickers
)sub2 ON sub2.itemFk = GREATEST(i.id, i2.id)
WHERE i.isFloramondo
AND i.id <> i2.id;
DECLARE EXIT HANDLER FOR SQLEXCEPTION SET vDone = TRUE;
BEGIN
SET vDone = TRUE;
ROLLBACK;
RESIGNAL;
END;
SET @isModeInventory:= TRUE;
OPEN curItemClean;
curItemClean: LOOP
FETCH curItemClean INTO vItemOld, vItemNew;
START TRANSACTION;
# Deletes
UPDATE IGNORE itemCost
SET itemFk = vItemNew
WHERE itemFk = vItemOld;
DELETE FROM itemCost
WHERE itemFk = vItemOld;
DELETE FROM bs.waste
WHERE itemFk = vItemOld;
DELETE FROM priceFixed
WHERE itemFk = vItemOld;
DELETE FROM itemMatchProperties
WHERE itemFk = vItemOld;
DELETE FROM itemBotanical
WHERE itemFk = vItemOld;
DELETE FROM itemProposal
WHERE itemFk = vItemOld;
SET @isTriggerDisabled := TRUE;
DELETE FROM itemTag
WHERE itemFk = vItemOld;
SET @isTriggerDisabled := FALSE;
DELETE FROM itemBarcode
WHERE itemFk = vItemOld;
DELETE FROM itemTaxCountry
WHERE itemFk = vItemOld;
# Updates
UPDATE buy
SET itemFk = vItemNew
WHERE itemFk = vItemOld;
UPDATE sale
SET itemFk = vItemNew
WHERE itemFk = vItemOld;
UPDATE specialPrice
SET itemFk = vItemNew
WHERE itemFk = vItemOld;
UPDATE packaging
SET itemFk = vItemNew
WHERE itemFk = vItemOld;
UPDATE packaging
SET freightItemFk = vItemNew
WHERE freightItemFk = vItemOld;
UPDATE hedera.orderRow
SET itemFk = vItemNew
WHERE itemFk = vItemOld;
UPDATE itemLog
SET originFk = vItemNew
WHERE originFk = vItemOld;
UPDATE itemShelving
SET itemFk = vItemNew
WHERE itemFk = vItemOld;
UPDATE ticketPackagingStartingStock
SET itemFk = vItemNew
WHERE itemFk = vItemOld;
UPDATE inventoryFailure
SET itemFk = vItemNew
WHERE itemFk = vItemOld;
UPDATE genericAllocation
SET itemFk = vItemNew
WHERE itemFk = vItemOld;
UPDATE itemPlacementSupply
SET itemFk = vItemNew
WHERE itemFk = vItemOld;
# Mantenemos la imagen si el nuevo no tiene
UPDATE vn.item itemNew
LEFT JOIN item itemOld ON itemOld.id = vItemOld
AND itemOld.image IS NOT NULL
SET itemNew.image = itemOld.image
WHERE itemNew.id = vItemNew
AND itemNew.image IS NULL;
# Eliminamos el item sustituido
DELETE FROM item
WHERE id = vItemOld;
COMMIT;
SET vCounter = vCounter + 1;
END LOOP;
CLOSE curItemClean;
SET @isModeInventory:= 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_comparative` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_comparative`(
vDate DATETIME,
vDayRange TINYINT,
vWarehouseFk TINYINT,
vAvailableSince DATE,
vBuyerFk INT,
vIsFloramondo BOOL,
vCountryFk INT
)
proc: BEGIN
/**
* Genera una tabla de comparativa de artículos por itemType/comprador/fecha.
* Los datos se calculan en función de los parámetros proporcionados.
*
* @param vDate La fecha para la cual se generará la comparativa.
* @param vDayRange El rango de días a considerar para la comparativa.
* @param vWarehouseFk El identificador del almacén para filtrar los artículos.
* @param vAvailableSince La fecha de disponibilidad desde la cual se consideran los artículos disponibles.
* @param vBuyerFk El identificador del comprador para filtrar los artículos.
* @param vIsFloramondo Indica si se deben incluir solo los artículos de Floramondo (opcional).
* @param vCountryFk El identificador del país.
* @param tmp.comparativeFilterType(filterFk INT ,itemTypeFk INT)
* @return tmp.comparative
*/
DECLARE vDayRangeStart DATE;
DECLARE vDayRangeEnd DATE;
DECLARE w1, w2, w3, w4, w5, w6, w7 INT;
DECLARE y1, y2, y3, y4, y5, y6, y7 INT;
DECLARE z1, z2, z3, z4, z5, z6, z7 INT;
DECLARE vPeriod INT;
DECLARE i INT DEFAULT 0;
DECLARE vHasTypeFilter BOOL;
DECLARE vWeekRange INT;
DECLARE vWeekCount TINYINT;
DECLARE vMaxDayRange INT;
DECLARE vMinDayRange INT;
DECLARE vDefaultDayRange INT;
IF NOT(SELECT COUNT(*) FROM comparativeConfig)THEN
LEAVE proc;
END IF;
SELECT weekRange,
weekRange * 2 + 1,
maxDayRange,
minDayRange,
defaultDayRange
INTO vWeekRange,
vWeekCount,
vMaxDayRange,
vMinDayRange,
vDefaultDayRange
FROM comparativeConfig;
IF vDayRange < vMinDayRange OR vDayRange > vMaxDayRange THEN
SET vDayRange = vDefaultDayRange;
END IF;
SELECT MIN(dated) INTO vDayRangeStart
FROM vn.time
WHERE dated <= vDate
GROUP BY period
ORDER BY dated desc
LIMIT 1 OFFSET vWeekRange;
SELECT MAX(dated) INTO vDayRangeEnd
FROM vn.time
WHERE dated >= vDate
GROUP BY period
ORDER BY dated ASC
LIMIT 1 OFFSET vWeekRange;
SELECT COUNT(itemTypeFk) > 0 INTO vHasTypeFilter
FROM tmp.comparativeFilterType;
CREATE OR REPLACE TEMPORARY TABLE tmp.itemInventory
(PRIMARY KEY (id))
ENGINE = MEMORY
SELECT i.id
FROM item i
JOIN itemType t ON t.id = i.typeFk
JOIN itemCategory c ON c.id = t.categoryFk
LEFT JOIN worker w ON w.id = t.workerFk
WHERE (NOT vHasTypeFilter
OR t.id IN (SELECT itemTypeFk FROM tmp.comparativeFilterType))
AND (vBuyerFk IS NULL
OR t.workerFk = vBuyerFk)
AND (vIsFloramondo IS NULL
OR i.isFloramondo = vIsFloramondo);
IF vDate < util.VN_CURDATE() THEN
ALTER TABLE tmp.itemInventory
ADD `buy_id` INT NOT NULL DEFAULT 0,
ADD `buy_date` DATE DEFAULT '2000-01-01',
ADD `life` INT DEFAULT 0,
ADD `sd` INT DEFAULT 0,
ADD `avalaible` INT DEFAULT 0,
ADD `visible` INT DEFAULT 0;
ELSE
CALL multipleInventory(vAvailableSince, vWarehouseFk, vDayRange);
CALL item_multipleBuy(vDate, vWarehouseFk);
CALL item_multipleBuyByDate(vDate, vWarehouseFk);
END IF;
CREATE OR REPLACE TEMPORARY TABLE tTable (
cy INT(6) PRIMARY KEY,
ly INT(6),
zy INT(6),
INDEX (ly)
);
REPEAT
SET i = i + 1;
SELECT t.period INTO vPeriod
FROM vn.`time` t
WHERE t.dated = vDayRangeStart + INTERVAL (vWeekCount * (i - 1)) DAY;
INSERT IGNORE INTO tTable(cy, ly, zy) VALUES(vPeriod, vPeriod - 100, vPeriod - 200);
UNTIL i = vWeekCount END REPEAT;
SELECT cy, ly, zy INTO w1, y1, z1 FROM tTable LIMIT 1;
SELECT cy, ly, zy INTO w2, y2, z2 FROM tTable WHERE cy > w1 LIMIT 1;
SELECT cy, ly, zy INTO w3, y3, z3 FROM tTable WHERE cy > w2 LIMIT 1;
SELECT cy, ly, zy INTO w4, y4, z4 FROM tTable WHERE cy > w3 LIMIT 1;
SELECT cy, ly, zy INTO w5, y5, z5 FROM tTable WHERE cy > w4 LIMIT 1;
SELECT cy, ly, zy INTO w6, y6, z6 FROM tTable WHERE cy > w5 LIMIT 1;
SELECT cy, ly, zy INTO w7, y7, z7 FROM tTable WHERE cy > w6 LIMIT 1;
-- Genera una tabla con los datos del año pasado.
CREATE OR REPLACE TEMPORARY TABLE tLastYear
(KEY (lItemFk))
ENGINE = MEMORY
SELECT c.itemFk lItemFk,
SUM(IF(c.timePeriod = y1, c.quantity, 0)) lweek1,
SUM(IF(c.timePeriod = y2, c.quantity, 0)) lweek2,
SUM(IF(c.timePeriod = y3, c.quantity, 0)) lweek3,
SUM(IF(c.timePeriod = y4, c.quantity, 0)) lweek4,
SUM(IF(c.timePeriod = y5, c.quantity, 0)) lweek5,
SUM(IF(c.timePeriod = y6, c.quantity, 0)) lweek6,
SUM(IF(c.timePeriod = y7, c.quantity, 0)) lweek7,
SUM(IF(c.timePeriod = y1, c.price, 0)) lprice1,
SUM(IF(c.timePeriod = y2, c.price, 0)) lprice2,
SUM(IF(c.timePeriod = y3, c.price, 0)) lprice3,
SUM(IF(c.timePeriod = y4, c.price, 0)) lprice4,
SUM(IF(c.timePeriod = y5, c.price, 0)) lprice5,
SUM(IF(c.timePeriod = y6, c.price, 0)) lprice6,
SUM(IF(c.timePeriod = y7, c.price, 0)) lprice7
FROM tmp.itemInventory ai
JOIN comparative c ON c.itemFk = ai.id
JOIN warehouse w on w.id = c.warehouseFk
JOIN tTable wt ON c.timePeriod = wt.ly
WHERE IFNULL(vWarehouseFk, c.warehouseFk) = c.warehouseFk
AND w.isComparative
AND (vCountryFk IS NULL OR c.countryFk = vCountryFk)
GROUP BY ai.id;
-- Genera una tabla con los datos de hace DOS años.
CREATE OR REPLACE TEMPORARY TABLE tTwoYearsAgo
(KEY (tItemFk))
ENGINE = MEMORY
SELECT c.itemFk tItemFk,
SUM(IF(c.timePeriod = z1, c.quantity, 0)) vlweek1,
SUM(IF(c.timePeriod = z2, c.quantity, 0)) vlweek2,
SUM(IF(c.timePeriod = z3, c.quantity, 0)) vlweek3,
SUM(IF(c.timePeriod = z4, c.quantity, 0)) vlweek4,
SUM(IF(c.timePeriod = z5, c.quantity, 0)) vlweek5,
SUM(IF(c.timePeriod = z6, c.quantity, 0)) vlweek6,
SUM(IF(c.timePeriod = z7, c.quantity, 0)) vlweek7,
SUM(IF(c.timePeriod = z1, c.price, 0)) vlprice1,
SUM(IF(c.timePeriod = z2, c.price, 0)) vlprice2,
SUM(IF(c.timePeriod = z3, c.price, 0)) vlprice3,
SUM(IF(c.timePeriod = z4, c.price, 0)) vlprice4,
SUM(IF(c.timePeriod = z5, c.price, 0)) vlprice5,
SUM(IF(c.timePeriod = z6, c.price, 0)) vlprice6,
SUM(IF(c.timePeriod = z7, c.price, 0)) vlprice7
FROM tmp.itemInventory ai
JOIN comparative c ON c.itemFk = ai.id
JOIN warehouse w on w.id = c.warehouseFk
JOIN tTable wt ON c.timePeriod = wt.zy
WHERE IFNULL(vWarehouseFk, c.warehouseFk) = c.warehouseFk
AND w.isComparative
AND (vCountryFk IS NULL OR c.countryFk = vCountryFk)
GROUP BY ai.id;
-- Genera una tabla con los datos de este año.ss
CREATE OR REPLACE TEMPORARY TABLE tCurrentYear
(KEY (cItemFk))
ENGINE = MEMORY
SELECT t.itemFk cItemFk,
SUM(IF(week = w1, total, 0)) cweek1,
SUM(IF(week = w2, total, 0)) cweek2,
SUM(IF(week = w3, total, 0)) cweek3,
SUM(IF(week = w4, total, 0)) cweek4,
SUM(IF(week = w5, total, 0)) cweek5,
SUM(IF(week = w6, total, 0)) cweek6,
SUM(IF(week = w7, total, 0)) cweek7,
SUM(IF(week = w1, price, 0)) cprice1,
SUM(IF(week = w2, price, 0)) cprice2,
SUM(IF(week = w3, price, 0)) cprice3,
SUM(IF(week = w4, price, 0)) cprice4,
SUM(IF(week = w5, price, 0)) cprice5,
SUM(IF(week = w6, price, 0)) cprice6,
SUM(IF(week = w7, price, 0)) cprice7
FROM (
SELECT s.itemFk,
ti.period `week`,
SUM(s.quantity) total,
TRUNCATE(SUM(s.quantity * s.priceFixed),0) price
FROM ticket t
JOIN sale s ON t.id = s.ticketFk
JOIN tmp.itemInventory it ON it.id = s.itemFk
JOIN time ti ON ti.dated = DATE(t.shipped)
JOIN item i ON i.id = s.itemFk
JOIN itemType tp ON tp.id = i.typeFk
JOIN itemCategory ic ON ic.id = tp.categoryFk
JOIN warehouse w ON w.id = t.warehouseFk
STRAIGHT_JOIN address ad ON ad.id = t.addressFk
JOIN province p ON p.id = ad.provinceFk
JOIN `client` c ON c.id = ad.clientFk
WHERE t.shipped BETWEEN vDayRangeStart AND util.dayEnd(vDayRangeEnd)
AND c.typeFk IN ('Normal','handMaking')
AND w.id = COALESCE(vWarehouseFk, w.id)
AND w.isComparative
AND (vCountryFk IS NULL OR p.countryFk = vCountryFk)
GROUP BY i.id, week
) t
GROUP BY t.itemFk;
-- Genera la tabla con la comparativa.
CREATE OR REPLACE TEMPORARY TABLE tmp.comparative
ENGINE = MEMORY
SELECT it.subName productor,
b.packing,
b.buyingValue costefijo,
b.groupingMode caja,
it.image ArticleImage,
IFNULL(it.inkFk,"?") color,
tp.code tipo,
it.typeFk tipo_id,
o.code origen,
it.category categoria,
it.stems tallos,
it.size medida,
it.name article,
w.code codigoTrabajador,
tp.categoryFk reino_id,
ly.*,
cy.*,
zy.*,
it.*,
it.id Id_Article,
i.buy_id,
tp.life,
IFNULL(i.sd,0) sd,
i.avalaible,
i.visible,
i.buy_date,
e.id provider_id,
it.comment comments,
it.description itemDescription,
IF(cy.cItemFk IS NULL AND i.visible = 0 AND i.avalaible = 0
AND IFNULL(i.sd, 0) = 0, FALSE, TRUE) filtret,
IF(it.hasMinPrice, FORMAT(it.minPrice, 2), "") pvp,
s.company_name
FROM tmp.itemInventory i
JOIN item it ON it.id = i.id
LEFT JOIN itemType tp ON tp.id = it.typeFk
LEFT JOIN worker w ON w.id = tp.workerFk
LEFT JOIN buy b ON b.id = i.buy_id
LEFT JOIN entry e ON e.id = b.entryFk
LEFT JOIN origin o ON o.id = it.originFk
LEFT JOIN tLastYear ly ON ly.lItemFk = it.id
LEFT JOIN tCurrentYear cy ON cy.cItemFk = it.id
LEFT JOIN tTwoYearsAgo zy ON zy.tItemFk = it.id
LEFT JOIN edi.ekt e2 ON e2.id = b.ektFk
LEFT JOIN edi.supplier s ON s.supplier_id = e2.pro
WHERE i.avalaible
OR i.visible
OR i.sd
OR cy.cweek1 OR cy.cweek2 OR cy.cweek3 OR cy.cweek4 OR cy.cweek5 OR cy.cweek6 OR cy.cweek7
OR ly.lweek1 OR ly.lweek2 OR ly.lweek3 OR ly.lweek4 OR ly.lweek5 OR ly.lweek6 OR ly.lweek7
OR zy.vlweek1 OR zy.vlweek2 OR zy.vlweek3 OR zy.vlweek4 OR zy.vlweek5 OR zy.vlweek6 OR zy.vlweek7;
-- Elimina las tablas temporales creadas...
DROP TEMPORARY TABLE IF EXISTS tmp.itemInventory,
tTwoYearsAgo,
tLastYear,
tCurrentYear,
tTable;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_deactivateUnused` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_deactivateUnused`()
BEGIN
/**
* Cambia a false el campo isActive de la tabla vn.item para todos aquellos
* items que no se han comprado en los últimos meses configurados en
* @vn.itemConfig.monthToDeactivate
*/
DECLARE vMonthToDeactivate INT;
SELECT monthToDeactivate INTO vMonthToDeactivate
FROM vn.itemConfig;
DROP TEMPORARY TABLE IF EXISTS tmp.buyMaxCreated;
CREATE TEMPORARY TABLE tmp.buyMaxCreated
ENGINE = MEMORY
SELECT b.itemFk,
MAX(b.created) created
FROM vn.buy b
JOIN vn.item i ON i.id = b.itemFk
WHERE i.isActive
GROUP BY itemFk;
UPDATE vn.item i
JOIN tmp.buyMaxCreated bmc ON bmc.itemFk = i.id
SET i.isActive = FALSE
WHERE bmc.created < util.VN_CURDATE() - INTERVAL vMonthToDeactivate MONTH;
DROP TEMPORARY TABLE IF EXISTS tmp.buyMaxCreated;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_getAtp` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getAtp`(vDated DATE)
BEGIN
/**
* Calcula el valor mínimo acumulado para cada artículo ordenado por fecha y
* almacén.
*
* @param vDated Si no hay movimientos en la fecha indicada, debe devolver 0
* @table tmp.itemCalc(itemFk, wareHouseFk, dated, quantity)
* @return tmp.itemAtp(itemFk, warehouseFk, quantity)
*/
CREATE OR REPLACE TEMPORARY TABLE tItemOrdered
(UNIQUE(itemFk, warehouseFk, dated))
ENGINE = MEMORY
SELECT itemFk, warehouseFk, dated, SUM(quantity) quantity
FROM (
SELECT itemFk, warehouseFk, dated, quantity
FROM tmp.itemCalc
UNION ALL
SELECT itemFk, warehouseFk, vDated, 0
FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2
) t1
GROUP BY itemFk, warehouseFk, dated
ORDER BY itemFk, warehouseFk, dated;
SET @lastItemFk := 0;
SET @lastWareHouseFk := 0;
SET @lastQuantity := 0;
CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp
(INDEX (itemFk, wareHouseFk))
SELECT itemFk, wareHouseFk, MIN(quantityAccumulated) quantity
FROM (
SELECT
itemFk,
IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk,
@lastQuantity := quantity,
@lastQuantity := @lastQuantity + quantity) quantityAccumulated,
wareHouseFk,
@lastItemFk := itemFk,
@lastWareHouseFk := wareHouseFk
FROM tItemOrdered
)sub
GROUP BY itemFk, wareHouseFk;
DROP TEMPORARY TABLE tItemOrdered;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_getBalance` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getBalance`(
vItemFk INT,
vWarehouseFk INT,
vDate DATETIME
)
BEGIN
/**
* @vItemFk item a buscar
* @vWarehouseFk almacen donde buscar
* @vDate Si la fecha es null, muestra el histórico desde el inventario.
* Si la fecha no es null, muestra histórico desde la fecha pasada.
*/
DECLARE vDateInventory DATETIME;
IF vDate IS NULL THEN
SELECT inventoried INTO vDateInventory
FROM config;
ELSE
SELECT mockUtcTime INTO vDateInventory
FROM util.config;
END IF;
CREATE OR REPLACE TEMPORARY TABLE tItemDiary(
shipped DATE,
`in` INT(11),
`out` INT(11),
alertLevel INT(11),
stateName VARCHAR(20),
`name` VARCHAR(50),
reference VARCHAR(50),
origin INT(11),
clientFk INT(11),
isPicked INT(11),
isTicket TINYINT(1),
lineFk INT(11),
`order` TINYINT(3) UNSIGNED,
clientType VARCHAR(20),
claimFk INT(10) UNSIGNED,
inventorySupplierFk INT(10)
);
INSERT INTO tItemDiary
SELECT tr.landed shipped,
b.quantity `in`,
NULL `out`,
st.alertLevel ,
st.name stateName,
s.name `name`,
e.invoiceNumber reference,
e.id origin,
s.id clientFk,
IF(st.`code` = 'DELIVERED', TRUE, FALSE) isPicked,
FALSE isTicket,
b.id lineFk,
NULL `order`,
NULL clientType,
NULL claimFk,
ec.inventorySupplierFk
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 state st ON st.`code` = IF( tr.landed < util.VN_CURDATE()
OR (util.VN_CURDATE() AND tr.isReceived),
'DELIVERED',
'FREE')
JOIN entryConfig ec
WHERE tr.landed >= vDateInventory
AND vWarehouseFk = tr.warehouseInFk
AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL)
AND b.itemFk = vItemFk
AND e.isExcludedFromAvailable = FALSE
AND e.isRaid = FALSE
UNION ALL
SELECT tr.shipped,
NULL,
b.quantity,
st.alertLevel,
st.name,
s.name,
e.invoiceNumber,
e.id,
s.id,
IF(st.`code` = 'DELIVERED' , TRUE, FALSE),
FALSE,
b.id,
NULL,
NULL,
NULL,
ec.inventorySupplierFk
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 state st ON st.`code` = IF(tr.shipped < util.VN_CURDATE()
OR (tr.shipped = util.VN_CURDATE() AND tr.isReceived),
'DELIVERED',
'FREE')
JOIN entryConfig ec
WHERE tr.shipped >= vDateInventory
AND vWarehouseFk = tr.warehouseOutFk
AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL)
AND b.itemFk = vItemFk
AND e.isExcludedFromAvailable = FALSE
AND w.isFeedStock = FALSE
AND e.isRaid = FALSE
UNION ALL
SELECT DATE(t.shipped),
NULL,
s.quantity,
st2.alertLevel,
st2.name,
t.nickname,
t.refFk,
t.id,
t.clientFk,
stk.id,
TRUE,
s.id,
st.`order`,
c.typeFk,
cb.claimFk,
NULL
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
LEFT JOIN ticketState ts ON ts.ticketFk = t.id
LEFT JOIN state st ON st.`code` = ts.`code`
JOIN client c ON c.id = t.clientFk
JOIN state st2 ON st2.`code` = IF(t.shipped < util.VN_CURDATE(),
'DELIVERED',
IF (t.shipped > util.dayEnd(util.VN_CURDATE()),
'FREE',
IFNULL(ts.code, 'FREE')))
LEFT JOIN state stPrep ON stPrep.`code` = 'PREPARED'
LEFT JOIN saleTracking stk ON stk.saleFk = s.id
AND stk.stateFk = stPrep.id
LEFT JOIN claimBeginning cb ON s.id = cb.saleFk
WHERE t.shipped >= vDateInventory
AND s.itemFk = vItemFk
AND vWarehouseFk =t.warehouseFk
ORDER BY shipped,
(inventorySupplierFk = clientFk) DESC,
alertLevel DESC,
isTicket,
`order` DESC,
isPicked DESC,
`in` DESC,
`out` DESC;
IF vDate IS NULL THEN
SET @a := 0;
SET @currentLineFk := 0;
SET @shipped := '';
SELECT DATE(@shipped:= t.shipped) shipped,
t.alertLevel,
t.stateName,
t.origin,
t.reference,
t.clientFk,
t.name,
t.`in` invalue,
t.`out`,
@a := @a + IFNULL(t.`in`, 0) - IFNULL(t.`out`, 0) balance,
@currentLineFk := IF (@shipped < util.VN_CURDATE()
OR (@shipped = util.VN_CURDATE() AND (t.isPicked OR a.`code` >= 'ON_PREPARATION')),
t.lineFk,
@currentLineFk) lastPreparedLineFk,
t.isTicket,
t.lineFk,
t.isPicked,
t.clientType,
t.claimFk,
t.`order`
FROM tItemDiary t
LEFT JOIN alertLevel a ON a.id = t.alertLevel;
ELSE
SELECT IFNULL(SUM(IFNULL(`in`, 0)) - SUM(IFNULL(`out`, 0)), 0) INTO @a
FROM tItemDiary
WHERE shipped < vDate;
SELECT vDate shipped,
0 alertLevel,
0 stateName,
0 origin,
'' reference,
0 clientFk,
'Inventario calculado',
@a invalue,
NULL `out`,
@a balance,
0 lastPreparedLineFk,
0 isTicket,
0 lineFk,
0 isPicked,
0 clientType,
0 claimFk,
NULL `order`
UNION ALL
SELECT shipped,
alertlevel,
stateName,
origin,
reference,
clientFk,
name, `in`,
`out`,
@a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0),
0,
isTicket,
lineFk,
isPicked,
clientType,
claimFk,
`order`
FROM tItemDiary
WHERE shipped >= vDate;
END IF;
DROP TEMPORARY TABLE tItemDiary;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_getInfo` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getInfo`(IN `vBarcode` VARCHAR(22), IN `vWarehouseFk` INT)
BEGIN
/**
* Devuelve información relativa al item correspondiente del vBarcode pasado
*
* @param vBarcode código relativo al ítem
* @param vWarehouseFk código del almacén
*/
DECLARE vCacheVisibleFk INT;
DECLARE vCacheAvailableFk INT;
DECLARE vVisibleItemShelving INT;
DECLARE vItemFk INT;
CALL cache.visible_refresh(vCacheVisibleFk, FALSE, vWarehouseFk);
CALL cache.available_refresh(vCacheAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE());
CALL buyUltimate(vWarehouseFk, util.VN_CURDATE());
SELECT barcodeToItem(vBarcode) INTO vItemFk;
SELECT SUM(visible) INTO vVisibleItemShelving
FROM itemShelvingStock
WHERE itemFk = vItemFk
AND warehouseFk = vWarehouseFk;
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 `min`,
p.name producer,
o.code origin,
v.visible - IFNULL(vVisibleItemShelving, 0) unlocated,
a.available,
vVisibleItemShelving,
v.visible,
b.`grouping`,
b.packing,
CONCAT('http:', ic.url, '/catalog/200x200/', i.image) urlImage200,
CONCAT('http:', ic.url, '/catalog/1600x900/', i.image) urlImage,
i.itemPackingTypeFk,
i.comment reference,
u.name buyer,
IFNULL(b.buyingValue, 0) +
IFNULL(b.freightValue, 0) +
IFNULL(b.comissionValue, 0) +
IFNULL(b.packageValue, 0) itemCost
FROM item i
LEFT JOIN producer p ON p.id = i.producerFk
LEFT JOIN origin o ON o.id = i.originFk
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 tmp.buyUltimate bu ON bu.itemFk = i.id
LEFT JOIN buy b ON b.id = bu.buyFk
AND bu.warehouseFk = vWarehouseFk
JOIN itemType it ON it.id = i.typeFk
JOIN account.user u ON u.id = it.workerFk
JOIN hedera.imageConfig ic
WHERE i.id = vItemFk;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_getLack` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getLack`(IN vForce BOOLEAN, IN vDays INT)
BEGIN
/**
* Calcula una tabla con el máximo negativo visible para cada producto y almacen
*
* @param vForce Fuerza el recalculo del stock
* @param vDays Numero de dias a considerar
**/
CALL `cache`.stock_refresh(vForce);
CALL item_getMinacum(NULL, util.VN_CURDATE(), vDays, NULL);
CALL item_getMinETD();
CALL item_zoneClosure();
SELECT i.id itemFk,
i.longName,
w.id warehouseFk,
p.`name` producer,
i.`size`,
i.category,
w.name warehouse,
SUM(IFNULL(sub.amount,0)) lack,
i.inkFk,
IFNULL(im.timed, util.midnight()) timed,
IFNULL(izc.timed, util.midnight()) minTimed,
o.name originFk
FROM (SELECT item_id,
warehouse_id,
amount
FROM cache.stock
WHERE amount > 0
UNION ALL
SELECT itemFk,
warehouseFk,
amount
FROM tmp.itemMinacum
) sub
JOIN warehouse w ON w.id = sub.warehouse_id
JOIN item i ON i.id = sub.item_id
LEFT JOIN producer p ON p.id = i.producerFk
JOIN itemType it ON it.id = i.typeFk
JOIN itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN tmp.itemMinETD im ON im.itemFk = i.id
LEFT JOIN tmp.itemZoneClosure izc ON izc.itemFk = i.id
JOIN origin o ON o.id = i.originFk
WHERE w.isForTicket
AND ic.display
AND it.code != 'GEN'
GROUP BY i.id, w.id
HAVING lack < 0;
DROP TEMPORARY TABLE tmp.itemMinacum;
DROP TEMPORARY TABLE tmp.itemMinETD;
DROP TEMPORARY TABLE tmp.itemZoneClosure;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_getMinacum` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getMinacum`(IN vWarehouseFk TINYINT, IN vDatedFrom DATETIME, IN vRange INT, IN vItemFk INT)
BEGIN
/**
* Cálculo del mínimo acumulado, para un item/almacén especificado, en caso de
* NULL para todo.
*
* @param vWarehouseFk -> warehouseFk
* @param vDatedFrom -> fecha inicio
* @param vRange -> número de días a considerar
* @param vItemFk -> Identificador de item
* @return tmp.itemMinacum
*/
DECLARE vDatedTo DATETIME;
SET vDatedFrom = TIMESTAMP(DATE(vDatedFrom), '00:00:00');
SET vDatedTo = TIMESTAMP(TIMESTAMPADD(DAY, vRange, vDatedFrom), '23:59:59');
DROP TEMPORARY TABLE IF EXISTS tmp.itemCalc;
CREATE TEMPORARY TABLE tmp.itemCalc
(INDEX (itemFk, warehouseFk))
SELECT sub.itemFk,
sub.dated,
CAST(SUM(sub.quantity) AS SIGNED) quantity,
sub.warehouseFk
FROM (SELECT s.itemFk,
DATE(t.shipped) dated,
-s.quantity quantity,
t.warehouseFk
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
AND s.quantity != 0
AND (vItemFk IS NULL OR s.itemFk = vItemFk)
AND (vWarehouseFk IS NULL OR t.warehouseFk = vWarehouseFk)
UNION ALL
SELECT b.itemFk,
t.landed,
b.quantity,
t.warehouseInFk
FROM buy b
JOIN entry e ON e.id = b.entryFk
LEFT JOIN travel t ON t.id = e.travelFk
WHERE t.landed BETWEEN vDatedFrom AND vDatedTo
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND !e.isExcludedFromAvailable
AND b.quantity != 0
AND (vItemFk IS NULL OR b.itemFk = vItemFk)
UNION ALL
SELECT b.itemFk,
t.shipped,
-b.quantity,
t.warehouseOutFk
FROM buy b
JOIN entry e ON e.id = b.entryFk
LEFT JOIN travel t ON t.id = e.travelFk
WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
AND (vWarehouseFk IS NULL OR t.warehouseOutFk = vWarehouseFk)
AND !e.isExcludedFromAvailable
AND b.quantity != 0
AND (vItemFk IS NULL OR b.itemFk = vItemFk)
AND !e.isRaid
) sub
GROUP BY sub.itemFk, sub.warehouseFk, sub.dated;
CALL item_getAtp(vDatedFrom);
DROP TEMPORARY TABLE tmp.itemCalc;
DROP TEMPORARY TABLE IF EXISTS tmp.itemMinacum;
CREATE TEMPORARY TABLE tmp.itemMinacum
(INDEX(itemFk))
ENGINE = MEMORY
SELECT i.itemFk,
i.warehouseFk,
i.quantity amount
FROM tmp.itemAtp i
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_getMinETD` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getMinETD`()
BEGIN
/* Devuelve una tabla temporal con la primera ETD, para todos los artículos con salida hoy.
*
* @return tmp.itemMinETD(itemFk, timed)
*/
DECLARE vMidnight DATETIME DEFAULT util.midnight();
DROP TEMPORARY TABLE IF EXISTS tmp.itemMinETD;
CREATE TEMPORARY TABLE tmp.itemMinETD
(INDEX (itemFk))
ENGINE = MEMORY
SELECT s.itemFk, MIN(TIME(IFNULL(z.`hour`,vMidnight))) timed
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
LEFT JOIN `zone` z ON z.id = t.zoneFk
WHERE t.shipped BETWEEN util.VN_CURDATE() AND vMidnight
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_getSimilar` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getSimilar`(
vSelf INT,
vWarehouseFk INT,
vDated DATE,
vShowType BOOL
)
BEGIN
/**
* Propone articulos disponibles ordenados, con la cantidad
* de veces usado y segun sus caracteristicas.
*
* @param vSelf Id de artículo
* @param vWarehouseFk Id de almacen
* @param vDated Fecha
* @param vShowType Mostrar tipos
*/
DECLARE vCalcFk INT;
DECLARE vTypeFk INT;
DECLARE vPriority INT DEFAULT 1;
CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDated);
WITH itemTags AS (
SELECT i.id,
typeFk,
tag5,
value5,
tag6,
value6,
tag7,
value7,
tag8,
value8,
t.name,
it.value
FROM vn.item i
LEFT JOIN vn.itemTag it ON it.itemFk = i.id
AND it.priority = vPriority
LEFT JOIN vn.tag t ON t.id = it.tagFk
WHERE i.id = vSelf
)
SELECT i.id itemFk,
i.longName,
i.subName,
i.tag5,
i.value5,
(i.value5 <=> its.value5) match5,
i.tag6,
i.value6,
(i.value6 <=> its.value6) match6,
i.tag7,
i.value7,
(i.value7 <=> its.value7) match7,
i.tag8,
i.value8,
(i.value8 <=> its.value8) match8,
a.available,
IFNULL(ip.counter, 0) `counter`,
CASE
WHEN b.groupingMode = 'grouping' THEN b.grouping
WHEN b.groupingMode = 'packing' THEN b.packing
ELSE 1
END AS minQuantity,
iss.visible located,
b.price2
FROM vn.item i
JOIN cache.available a ON a.item_id = i.id
AND a.calc_id = vCalcFk
LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id
AND ip.itemFk = vSelf
LEFT JOIN vn.itemTag it ON it.itemFk = i.id
AND it.priority = vPriority
LEFT JOIN vn.tag t ON t.id = it.tagFk
LEFT JOIN cache.last_buy lb ON lb.item_id = i.id
AND lb.warehouse_id = vWarehouseFk
LEFT JOIN vn.buy b ON b.id = lb.buy_id
LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = i.id
AND iss.warehouseFk = vWarehouseFk
JOIN itemTags its
WHERE a.available > 0
AND (i.typeFk = its.typeFk OR NOT vShowType)
AND i.id <> vSelf
ORDER BY `counter` DESC,
(t.name = its.name) DESC,
(it.value = its.value) DESC,
(i.tag5 = its.tag5) DESC,
match5 DESC,
(i.tag6 = its.tag6) DESC,
match6 DESC,
(i.tag7 = its.tag7) DESC,
match7 DESC,
(i.tag8 = its.tag8) DESC,
match8 DESC
LIMIT 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_getStock` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getStock`(
vWarehouseFk SMALLINT,
vDated DATE,
vItemFk INT
)
BEGIN
/**
* Calcula el stock de un artículo de un vWarehouseFk,
* desde la fecha del inventario hasta vDated
*
* @param vWarehouse Warehouse id
* @param vDated Max date to filter
* @param vItemFk Item id
*
* @return tmp.itemList(itemFk, stock, visible, available)
*/
DECLARE vIsLogifloraDay BOOL DEFAULT vn.isLogifloraDay(vDated, vWarehouseFk);
SET vDated = TIMESTAMP(vDated, '00:00:00');
CREATE OR REPLACE 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 >= util.VN_CURDATE()
AND shipped < vDated
AND warehouseFk = vWarehouseFk
AND (vItemFk IS NULL OR itemFk = vItemFk)
UNION ALL
SELECT iei.itemFk, iei.quantity
FROM itemEntryIn iei
LEFT JOIN edi.warehouseFloramondo wf ON wf.entryFk = iei.entryFk
JOIN item i ON i.id = iei.itemFk
WHERE iei.landed >= util.VN_CURDATE()
AND iei.landed < vDated
AND iei.warehouseInFk = vWarehouseFk
AND (vItemFk IS NULL OR iei.itemFk = vItemFk)
AND (wf.entryFk IS NULL OR vIsLogifloraDay)
AND NOT (iei.landed > util.VN_CURDATE() AND i.isFloramondo)
UNION ALL
SELECT ieo.itemFk, ieo.quantity
FROM itemEntryOut ieo
JOIN item i ON i.id = ieo.itemFk
WHERE ieo.shipped >= util.VN_CURDATE()
AND ieo.shipped < vDated
AND ieo.warehouseOutFk = vWarehouseFk
AND (vItemFk IS NULL OR ieo.itemFk = vItemFk)
AND NOT (ieo.shipped > util.VN_CURDATE() AND i.isFloramondo)
) sub
GROUP BY itemFk
HAVING stock;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_GetVisible` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_GetVisible`(vWarehouse SMALLINT, vItem INT)
BEGIN
DECLARE vTomorrow DATETIME DEFAULT TIMESTAMPADD(DAY, 1, util.VN_CURDATE());
INSERT INTO tmp.itemVisible (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 > util.VN_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 >= util.VN_CURDATE() AND i.shipped < vTomorrow
UNION ALL
SELECT iei.itemFk, quantity
FROM itemEntryIn iei
WHERE (iei.isReceived != FALSE /*OR ip.modificationDate > util.VN_CURDATE()*/)
AND iei.landed >= util.VN_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 >= util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_multipleBuy` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_multipleBuy`(
vDate DATETIME,
vWarehouseFk INT
)
BEGIN
/**
* Updates the tmp.itemInventory table, adding the buy id.
*
* @param tmp.itemInventory(buy_id)
* @param vDate -> Date of the purchase operation.
* @param vWarehouseFk -> Identifier of the warehouse (warehouseId).
*/
ALTER TABLE tmp.itemInventory ADD IF NOT EXISTS buy_id INT;
CALL buyUltimate(vWarehouseFk, vDate);
CREATE OR REPLACE TEMPORARY TABLE tmp
(KEY (itemFk))
ENGINE = MEMORY
SELECT *
FROM (
SELECT itemFk, buyFk
FROM tmp.buyUltimate
ORDER BY (vWarehouseFk = warehouseFk) DESC, landing DESC
LIMIT 10000000000000000000
) t
GROUP BY itemFk;
UPDATE tmp.itemInventory ai
JOIN tmp t ON ai.id = t.itemFk
SET ai.buy_id = t.buyFk;
DROP TEMPORARY TABLE tmp, 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_multipleBuyByDate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_multipleBuyByDate`(
vDated DATETIME,
vWarehouseFk TINYINT(3)
)
BEGIN
/**
* Updates the tmp.itemInventory table, adding the purchase date.
*
* @param tmp.itemInventory(buy_date)
* @param vDated -> end date
* @param vWarehouseFk -> warehouse id
*/
DECLARE vLastBuyScope INT;
SELECT comparativeLastBuyScope INTO vLastBuyScope
FROM config;
ALTER TABLE tmp.itemInventory
ADD `buy_date` datetime NOT NULL;
CREATE OR REPLACE TEMPORARY TABLE lastBuyScope
SELECT i.id, MAX(t.landed) lastLanded
FROM item i
JOIN buy b ON b.itemFk = i.id
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
JOIN supplier s ON s.id = e.supplierFk
JOIN warehouse w ON w.id = t.warehouseInFk
WHERE t.landed BETWEEN (vDated + INTERVAL - vLastBuyScope DAY) AND vDated
AND NOT s.name = 'INVENTARIO'
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND w.isComparative
AND NOT e.isRaid
GROUP BY i.id;
UPDATE tmp.itemInventory y
JOIN lastBuyScope lbs ON lbs.id = y.id
SET y.buy_date = lbs.lastLanded;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_refreshFromTags` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_refreshFromTags`(vSelf INT)
BEGIN
/**
* Updates item attributes with its corresponding tags.
*
* @param vSelf The item id
*/
DECLARE vTags JSON;
DECLARE vValues JSON;
DECLARE vAbbrs JSON;
DECLARE vOverwrites JSON;
SELECT JSON_OBJECTAGG(`priority`, t.`name`),
JSON_OBJECTAGG(`priority`, it.`value`),
JSON_OBJECTAGG(`priority`, IFNULL(a.abbreviation, it.`value`)),
JSON_OBJECTAGG(`overwrite`, it.`value`)
INTO vTags, vValues, vAbbrs, vOverwrites
FROM itemTag it
JOIN tag t ON t.id = it.tagFk
LEFT JOIN tagAbbreviation a ON a.`value` = it.`value`
AND (a.tagFk IS NULL OR a.tagFk = t.id)
WHERE it.itemFk = vSelf;
UPDATE item i
LEFT JOIN ink k ON k.name = JSON_VALUE(vOverwrites, '$.inkFk')
LEFT JOIN origin o ON o.name = JSON_VALUE(vOverwrites, '$.originFk')
LEFT JOIN producer p ON p.name = JSON_VALUE(vOverwrites, '$.producerFk')
SET i.`name` = CONCAT_WS(' ',
JSON_VALUE(vAbbrs, '$.1'),
JSON_VALUE(vAbbrs, '$.2'),
IF(i.isFloramondo, NULL, JSON_VALUE(vAbbrs, '$.3'))
),
i.longName = CONCAT_WS(' ',
JSON_VALUE(vValues, '$.1'),
JSON_VALUE(vValues, '$.2'),
JSON_VALUE(vValues, '$.3')
),
i.subname = JSON_VALUE(vValues, '$.4'),
i.size = JSON_VALUE(vOverwrites, '$.size'),
i.stems = IFNULL(JSON_VALUE(vOverwrites, '$.stems'),i.stems),
i.category = JSON_VALUE(vOverwrites, '$.category'),
i.tag5 = JSON_VALUE(vTags, '$.5'),
i.tag6 = JSON_VALUE(vTags, '$.6'),
i.tag7 = JSON_VALUE(vTags, '$.7'),
i.tag8 = JSON_VALUE(vTags, '$.8'),
i.tag9 = JSON_VALUE(vTags, '$.9'),
i.tag10 = JSON_VALUE(vTags, '$.10'),
i.value5 = JSON_VALUE(vValues, '$.5'),
i.value6 = JSON_VALUE(vValues, '$.6'),
i.value7 = JSON_VALUE(vValues, '$.7'),
i.value8 = JSON_VALUE(vValues, '$.8'),
i.value9 = JSON_VALUE(vValues, '$.9'),
i.value10 = JSON_VALUE(vValues, '$.10'),
i.producerFk = p.id,
i.inkFk = k.id,
i.originFk = IFNULL(o.id, i.originFk)
WHERE i.id = vSelf;
CALL item_setGeneric(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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_refreshTags` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_refreshTags`()
BEGIN
/**
* Update item table, tag "cache" fields
*
* @param temporary table tmp.item(id) of the article
*/
DECLARE vDone BOOL;
DECLARE vItemFk INT;
DECLARE vCur CURSOR FOR SELECT id FROM tmp.item;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN vCur;
l: LOOP
SET vDone = FALSE;
FETCH vCur INTO vItemFk;
IF vDone THEN
LEAVE l;
END IF;
CALL item_refreshFromTags(vItemFk);
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_saveReference` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_saveReference`(vBarcode VARCHAR(22), vReference VARCHAR(150))
BEGIN
/**
* Actualiza la referencia del item
*
* @param vBarcode del item
* @param vReference referencia a actualizar
*/
DECLARE vItemFk INT;
SELECT barcodeToItem(vBarcode) INTO vItemFk;
UPDATE item SET comment = vReference 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_setGeneric` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_setGeneric`(vSelf INT)
BEGIN
/**
* Asigna el código genérico a un item, salvo que sea un código de item genérico.
*
* @param vSelf identificador de vn.item
*/
DECLARE vGenericFk INT;
SELECT itemFk INTO vGenericFk
FROM (
SELECT itemFk, SUM(matches) = maxMatches `match`
FROM (
SELECT ga.id gaid, ga.itemFk,
CASE
WHEN t.code = 'nflowers' THEN
it.value <=> ga.numFlores
WHEN t.code = 'origin' THEN
it.value <=> ga.origin
WHEN t.code = 'quality' THEN
it.value <=> ga.quality
WHEN t.code = 'color' THEN
it.value <=> ga.color
WHEN t.code = 'category' THEN
it.value <=> ga.category
WHEN t.code = 'producer' THEN
it.value <=> ga.productor
ELSE
0
END matches,
(NOT ISNULL(ga.origin))
+ (NOT ISNULL(ga.color))
+ (NOT ISNULL(ga.quality))
+ (NOT ISNULL(ga.numFlores))
+ (NOT ISNULL(ga.category))
+ (NOT ISNULL(ga.productor)) maxMatches
FROM vn.item i
JOIN vn.itemTag it ON it.itemFk = i.id
JOIN vn.tag t ON t.id = it.tagFk
JOIN vn.genericAllocation ga
ON (i.typeFk = ga.typeFk OR ga.typeFk IS NULL)
AND (i.longName = ga.longName OR ga.longName IS NULL)
AND (i.`size` = ga.`size` OR ga.`size` IS NULL)
AND i.id != ga.itemFk
WHERE i.id = vSelf
AND NOT i.isFloramondo) sub
GROUP BY gaid
HAVING `match`) sub2
LIMIT 1;
UPDATE vn.item
SET genericFk = vGenericFk
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_setVisibleDiscard` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_setVisibleDiscard`(
vItemFk INT,
vWarehouseFk INT,
vQuantity INT,
vAddressFk INT)
BEGIN
/**
* Procedimiento para dar dar de baja/alta un item, si vAddressFk es NULL se entiende que se da de alta y se toma el addressFk de la configuración
*
* @param vItemFk Identificador del ítem
* @param vWarehouseFk id del warehouse
* @param vQuantity a dar de alta/baja
* @param vAddressFk id address
*/
DECLARE vTicketFk INT;
DECLARE vClientFk INT;
DECLARE vDefaultCompanyFk INT;
DECLARE vCalc INT;
DECLARE vAddressShortage INT;
SELECT barcodeToItem(vItemFk) INTO vItemFk;
SELECT DEFAULT(companyFk) INTO vDefaultCompanyFk
FROM vn.ticket LIMIT 1;
IF vAddressFk IS NULL THEN
SELECT pc.shortageAddressFk INTO vAddressShortage
FROM productionConfig pc ;
ELSE
SET vAddressShortage = vAddressFk;
END IF;
SELECT a.clientFk INTO vClientFk
FROM address a
WHERE a.id = vAddressShortage;
SELECT t.id INTO vTicketFk
FROM ticket t
JOIN address a ON a.id = t.addressFk
JOIN ticketState ts ON ts.ticketFk = t.id
WHERE t.warehouseFk = vWarehouseFk
AND a.id = vAddressShortage
AND DATE(t.shipped) = util.VN_CURDATE()
AND ts.code = 'DELIVERED'
LIMIT 1;
CALL cache.visible_refresh(vCalc, TRUE, vWarehouseFk);
IF vTicketFk IS NULL THEN
CALL ticket_add(
vClientFk,
util.VN_CURDATE(),
vWarehouseFk,
vDefaultCompanyFk,
vAddressFk,
NULL,
NULL,
util.VN_CURDATE(),
account.myUser_getId(),
FALSE,
vTicketFk);
END IF;
INSERT INTO sale(ticketFk, itemFk, concept, quantity)
SELECT vTicketFk,
vItemFk,
name,
vQuantity
FROM item
WHERE id = vItemFk;
UPDATE cache.visible
SET visible = visible - vQuantity
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_updatePackingType` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_updatePackingType`(vItem INT, vItemPackingTypeFk VARCHAR(1))
BEGIN
/**
* Update the packing type of an item
*
* @param vItem id del item a actualizar
* @param vItemPackingTypeFk packing type
*/
UPDATE item SET itemPackingTypeFk = vItemPackingTypeFk WHERE id = vItem;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_ValuateInventory`(vDated DATE, vIsDetailed BOOLEAN)
BEGIN
DECLARE vInventoried DATE;
DECLARE vHasNotInventory BOOLEAN DEFAULT FALSE;
DECLARE vInventoryClone DATE;
DECLARE vDateDayEnd DATETIME;
DECLARE vInventorySupplierFk INT;
SELECT inventorySupplierFk INTO vInventorySupplierFk
FROM entryConfig;
SET vDateDayEnd = util.dayEnd(vDated);
SELECT tr.landed INTO vInventoried
FROM travel tr
JOIN `entry` e ON e.travelFk = tr.id
JOIN entryConfig ec
WHERE landed <= vDateDayEnd
AND e.supplierFk = vInventorySupplierFk
ORDER BY tr.landed DESC
LIMIT 1;
SET vHasNotInventory = (vInventoried IS NULL);
IF vHasNotInventory THEN
SELECT landed INTO vInventoryClone
FROM travel tr
JOIN `entry` e ON e.travelFk = tr.id
JOIN entryConfig ec
WHERE landed >= vDated
AND e.supplierFk = vInventorySupplierFk
ORDER BY landed ASC
LIMIT 1;
SET vInventoried = vDated + INTERVAL 1 DAY;
SET vDateDayEnd = vInventoryClone;
END IF;
CREATE OR REPLACE TEMPORARY TABLE tInventory(
warehouseFk SMALLINT,
itemFk BIGINT,
quantity INT,
cost DOUBLE DEFAULT 0,
total DOUBLE DEFAULT 0,
warehouseInventory VARCHAR(20),
PRIMARY KEY (warehouseInventory, itemFk) USING HASH
)
ENGINE = MEMORY;
-- Inventario inicial
IF vHasNotInventory THEN
INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
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
JOIN entryConfig ec
WHERE landed = vDateDayEnd
AND e.supplierFk = vInventorySupplierFk
AND w.valuatedInventory
AND t.isInventory
GROUP BY tr.warehouseInFk, b.itemFk;
ELSE
INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
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
JOIN entryConfig ec
WHERE landed = vInventoried
AND e.supplierFk = vInventorySupplierFk
AND w.valuatedInventory
AND t.isInventory
GROUP BY tr.warehouseInFk, b.itemFk;
END IF;
-- Añadimos las entradas
INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
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
JOIN entryConfig ec
WHERE tr.landed BETWEEN vInventoried AND vDateDayEnd
AND IF(tr.landed = util.VN_CURDATE(), tr.isReceived, TRUE)
AND NOT e.isRaid
AND w.valuatedInventory
AND t.isInventory
AND e.supplierFk <> vInventorySupplierFk
ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity * IF(vHasNotInventory, -1, 1));
-- Descontamos las salidas
INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
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 tInventory.quantity = tInventory.quantity + (b.quantity * IF(vHasNotInventory,1,-1));
-- Descontamos las lineas de venta
INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
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 tInventory.quantity = tInventory.quantity + s.quantity * IF(vHasNotInventory, 1, -1);
-- Volver a poner lo que esta aun en las estanterias
IF vDated = util.VN_CURDATE() THEN
INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
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 NOT (s.isPicked OR t.isLabeled)
AND w.valuatedInventory
AND it.isInventory
ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + s.quantity * IF(vHasNotInventory, 0, 1);
END IF;
-- Mercancia en transito
INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory)
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 tInventory.quantity = tInventory.quantity + (b.quantity);
CALL vn.buyUltimate(NULL, vDateDayEnd);
UPDATE tInventory i
JOIN tmp.buyUltimate bu ON i.warehouseFk = bu.warehouseFk AND i.itemFk = bu.itemFk
JOIN buy b ON b.id = bu.buyFk
SET total = i.quantity * (IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0)),
cost = IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0)
WHERE i.quantity;
DELETE FROM tInventory
WHERE quantity IS NULL OR NOT quantity;
IF vIsDetailed THEN
SELECT ti.warehouseFk,
i.id itemFk,
i.longName,
i.size,
ti.quantity,
tp.name Tipo,
ic.name Reino,
ti.cost,
CAST(ti.total AS DECIMAL(10, 2)) total,
ti.warehouseInventory almacen
FROM tInventory ti
JOIN warehouse w ON w.id = warehouseFk
JOIN item i ON i.id = ti.itemFk
JOIN itemType tp ON tp.id = i.typeFk
JOIN itemCategory ic ON ic.id = tp.categoryFk
WHERE w.valuatedInventory
AND ti.total > 0
ORDER BY ti.total DESC;
ELSE
SELECT i.warehouseInventory Almacen,
ic.name Reino,
CAST(i.total AS DECIMAL(10, 2)) Euros,
w.code Comprador,
it.id
FROM tInventory i
JOIN warehouse wh ON wh.id = warehouseFk
JOIN item it ON it.id = i.itemFk
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,
tInventory;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_zoneClosure` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `item_zoneClosure`()
BEGIN
/* Devuelve una tabla temporal con la hora minima de un ticket sino tiene el de la zoneClosure y
* si tampoco hay el de la zona , para todos los artículos con salida hoy.
*
* @return tmp.itemZoneClosure(itemFk, timed)
*/
CREATE OR REPLACE TEMPORARY TABLE tmp.itemZoneClosure
(INDEX (itemFk))
ENGINE = MEMORY
SELECT s.itemFk,
MIN(DATE_FORMAT(IF(HOUR(t.shipped),t.shipped,
IFNULL(zc.hour, z.HOUR)), '%H:%i')
)timed
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
LEFT JOIN `zone` z ON z.id = t.zoneFk
LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk
WHERE t.shipped BETWEEN util.VN_CURDATE() AND CONCAT(util.VN_CURDATE(), ' 23:59:59')
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ledger_doCompensation` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ledger_doCompensation`(vDated DATE, vCompensationAccount VARCHAR(10) , vBankFk VARCHAR(10), vConcept VARCHAR(255), vAmount DECIMAL(10,2), vCompanyFk INT, vOriginalAccount VARCHAR(10))
BEGIN
/**
* Compensa un pago o un recibo insertando en contabilidad
*
* @param vDated fecha en la cual se anota
* @param vCompensationAccount cuenta contable contra la que se compensa
* @param vBankFk banco de la compensacion
* @param vConcept descripcion
* @param vAmount cantidad que se compensa
* @param vCompany empresa
* @param vOriginalAccount cuenta contable desde la cual se compensa
*
*/
DECLARE vNewBookEntry INT;
DECLARE vIsClientCompensation INT;
DECLARE vClientFk INT;
DECLARE vSupplierFk INT;
DECLARE vIsOriginalAClient BOOL;
DECLARE vPayMethodCompensation INT;
CALL ledger_next(vNewBookEntry);
SELECT COUNT(id) INTO vIsOriginalAClient FROM client WHERE accountingAccount LIKE vOriginalAccount COLLATE utf8_general_ci;
SELECT id, COUNT(id) INTO vClientFk, vIsClientCompensation
FROM client
WHERE accountingAccount LIKE vCompensationAccount COLLATE utf8_general_ci;
SET @vAmount1:= 0.0;
SET @vAmount2:= 0.0;
INSERT INTO XDiario (ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EUROHABER, empresa_id)
VALUES ( vNewBookEntry,
vDated,
vOriginalAccount,
vCompensationAccount,
vConcept,
@vAmount1:= IF(
(vIsOriginalAClient AND vAmount > 0) OR
(NOT vIsOriginalAClient AND vAmount < 0),
0,
ABS(vAmount)
),
@vAmount2:= IF(@vAmount1,
0,
ABS(vAmount)
),
vCompanyFk
),
( vNewBookEntry,
vDated,
vCompensationAccount,
vOriginalAccount,
vConcept,
@vAmount2,
@vAmount1,
vCompanyFk);
IF vIsClientCompensation THEN
IF vIsOriginalAClient THEN
SET vAmount = -vAmount;
END IF;
INSERT INTO receipt(invoiceFk, amountPaid, payed, bankFk, companyFk, clientFk, isConciliate)
VALUES (vConcept, vAmount, vDated, vBankFk, vCompanyFk, vClientFk, TRUE);
ELSE
IF NOT vIsOriginalAClient THEN
SET vAmount = -vAmount;
END IF;
SELECT id INTO vSupplierFk FROM supplier WHERE `account` LIKE vCompensationAccount COLLATE utf8_general_ci;
SELECT id INTO vPayMethodCompensation FROM payMethod WHERE `code` = 'compensation';
INSERT INTO payment (received, dueDated, supplierFk, amount, bankFk, payMethodFk, concept, companyFk, isConciliated)
VALUES(vDated, vDated, vSupplierFk, vAmount, vBankFk, vPayMethodCompensation, vConcept, vCompanyFk, 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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `lungSize_generator` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `lungSize_generator`(vDate DATE)
BEGIN
SET @buildingOrder := 0;
SET @route := 0;
set @cajas := 0;
UPDATE tmp.sorter
SET buildingOrder = @buildingOrder := IF(@route = @route := routeFk, @buildingOrder, 0) + 1
where date(created) = vDate
order by routeFk, created, weight DESC;
update tmp.sorter
SET palletOrder = buildingOrder mod 14, lungGrow = buildingOrder mod 14
WHERE date(created) = vDate;
UPDATE tmp.sorter
JOIN (
SELECT routeFk, max(id) maxid
FROM tmp.sorter
where date(created) = vDate
GROUP BY routeFk) sub ON sub.maxid = id
SET lungGrow = 1 - palletOrder ;
UPDATE tmp.sorter
SET lungGrow = IF(palletOrder = 0, -13, lungGrow);
DELETE FROM tmp.lungSize WHERE dia = vDate;
INSERT INTO tmp.lungSize(dia, hora,size)
select vDate,hora, @cajas := @cajas + cajas as size
from
(
select IF(lungGrow BETWEEN -12 AND -1, ETD,time_format(created,"%H:%i")) as hora, sum(if(lungGrow <= 0, lungGrow, 1)) as cajas, @cajas := 0
from tmp.sorter
where date(created) = vDate
group by hora
) sub;
SELECT * FROM tmp.lungSize
WHERE dia = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `machineWorker_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `machineWorker_add`(vPlate VARCHAR(10), vWorkerFk INT)
BEGIN
/**
* Inserta registro si el vWorkerFk no ha registrado nada en las últimas 12 horas
* @param vPlate número de matrícula
* @param vWorkerFk id del worker
*
*/
UPDATE vn.machineWorker mw
JOIN vn.machine m ON m.id = mw.machineFk
SET mw.outTimed = util.VN_NOW()
WHERE (mw.workerFk = vWorkerFk OR m.plate = vPlate)
AND ISNULL(mw.outTimed);
INSERT INTO machineWorker (machineFk, workerFk)
SELECT m.id, vWorkerFk
FROM machine m
WHERE m.plate= vPlate;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `machineWorker_getHistorical` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `machineWorker_getHistorical`(vPlate VARCHAR(20), vWorkerFk INT)
BEGIN
/**
* Obtiene historial de la matrícula vPlate que el trabajador vWorkerFk escanea,
* si es jefe de producción muestra el historial completo.
*
* @param vPlate número de matrícula
* @param vWorkerFk id del trabajador
*
*/
DECLARE vWorkerName VARCHAR(255) DEFAULT account.user_getNameFromId(vWorkerFk);
SELECT mw.inTimed,account.user_getNameFromId(mw.workerFk) as workerName, mw.outTimed
FROM machineWorker mw
JOIN machine m ON m.plate = vPlate
WHERE mw.machineFk = m.id
AND mw.workerFk = IF(account.user_hasRole(vWorkerName, 'coolerAssist'), mw.workerFk, vWorkerFk)
ORDER BY mw.inTimed 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `machineWorker_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `machineWorker_update`(vPlate VARCHAR(10), vWorkerFk INT)
BEGIN
/**
* Actualiza el registro correspondiente si el vWorkerFk se ha registrado en las últimas horas (campo maxHours de machineWorkerConfig) con vPlate,
*
* @param vPlate número de matrícula
* @param vWorkerFk id del trabajador
*
*/
DECLARE vMachineFk INT(10);
DECLARE vMaxHours INT(10);
SELECT m.id INTO vMachineFk
FROM machine m
WHERE m.plate = vPlate;
SELECT maxHours INTO vMaxHours
FROM machineWorkerConfig;
IF (SELECT COUNT(*)
FROM machineWorker m
WHERE m.workerFk = vWorkerFk
AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) AND ISNULL(m.outTimed)) THEN
UPDATE machineWorker m
SET m.outTimed = CURRENT_TIMESTAMP()
WHERE m.workerFk = vWorkerFk
AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW())
AND ISNULL(m.outTimed)
AND m.machineFk = vMachineFk;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `machine_getWorkerPlate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `machine_getWorkerPlate`(vWorkerFk INT)
BEGIN
/**
* Selecciona la matrícula del vehículo del workerfk
*
* @param vWorkerFk el id del trabajador
*/
SELECT m.plate
FROM machine m
JOIN machineWorker mw ON mw.machineFk = m.id
WHERE mw.inTimed >= TIMESTAMPADD(HOUR , -12,util.VN_NOW())
AND ISNULL(mw.outTimed)
AND mw.workerFk = vWorkerFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `mail_insert`(
vReceiver VARCHAR(255),
vReplyTo VARCHAR(50),
vSubject VARCHAR(100),
vBody TEXT)
BEGIN
/**
* Inserta en la tabla vn.mail
*
* @param vReceiver Receptor del correo
* @param vReplyTo A quién contestar el correo
* @param vSubject Título del correo
* @param vBody Cuerpo del correo
*/
DECLARE vIsRepeated BOOLEAN;
SELECT COUNT(*) INTO vIsRepeated
FROM vn.mail
WHERE creationDate >= util.VN_CURDATE()
AND `receiver` = vReceiver
AND `replyTo` = vReplyTo
AND `subject` = vSubject
AND !sent;
IF NOT vIsRepeated THEN
INSERT INTO vn.mail SET
`receiver` = vReceiver,
`replyTo` = vReplyTo,
`subject` = vSubject,
`body` = IFNULL(vBody,vSubject);
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `makePCSGraf` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `makePCSGraf`(vDated DATE)
BEGIN
DECLARE vHour INT DEFAULT 0;
DECLARE vMinute INT DEFAULT 0;
DECLARE vBoxes INT;
DROP TEMPORARY TABLE IF EXISTS vn.pcsDay;
CREATE TEMPORARY TABLE vn.pcsDay
SELECT 0 as hh, 0 as mm, 0 as boxes;
-- Creamos una tabla soporte para acumular las cajas a lo largo del dia
WHILE vHour < 24 DO
WHILE vMinute < 59 DO
SET vMinute = vMinute + 1;
INSERT INTO vn.pcsDay(hh,mm) VALUES(vHour, vMinute);
END WHILE;
SET vMinute = -1;
SET vHour = vHour + 1;
END WHILE;
-- Acumulamos
UPDATE vn.pcsDay pd
LEFT JOIN (SELECT * FROM vn.pcs_graf WHERE dia = vDated) pg USING(hh,mm)
SET pd.boxes = pd.boxes + pg.box;
SELECT * FROM vn.pcsDay;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `manaSpellersRequery`(vWorkerFk INTEGER)
`whole_proc`:
BEGIN
/**
* Guarda en workerMana el mana consumido por un trabajador
*
* @param vWorkerFk Id Trabajador
*/
DECLARE vWorkerIsExcluded BOOLEAN;
SELECT COUNT(*) INTO vWorkerIsExcluded
FROM workerManaExcluded
WHERE workerFk = vWorkerFk;
IF vWorkerIsExcluded THEN
LEAVE whole_proc;
END IF;
CREATE OR REPLACE TEMPORARY TABLE tmp.client
SELECT id
FROM client
WHERE salesPersonFk = vWorkerFk;
CALL client_getMana();
INSERT INTO workerMana (workerFk, amount)
SELECT vWorkerFk, sum(mana)
FROM tmp.clientMana
ON DUPLICATE KEY UPDATE amount = VALUES(amount);
DROP TEMPORARY TABLE
tmp.client,
tmp.clientMana;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `multipleInventory` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `multipleInventory`(
vDate DATE,
vWarehouseFk TINYINT,
vMaxDays TINYINT
)
proc: BEGIN
DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY;
DECLARE vDateFrom DATE DEFAULT vDate;
DECLARE vDateTo DATETIME;
DECLARE vDateToTomorrow DATETIME;
DECLARE vDefaultDayRange INT;
IF vDate < util.VN_CURDATE() THEN
LEAVE proc;
END IF;
IF vDate = util.VN_CURDATE() THEN
SELECT inventoried INTO vDateFrom
FROM config;
END IF;
SELECT defaultDayRange INTO vDefaultDayRange
FROM comparativeConfig;
SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY;
SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY;
ALTER TABLE tmp.itemInventory
ADD `avalaible` INT NOT NULL,
ADD `sd` INT NOT NULL,
ADD `rest` INT NOT NULL,
ADD `expected` INT NOT NULL,
ADD `inventory` INT NOT NULL,
ADD `visible` INT NOT NULL,
ADD `life` TINYINT NOT NULL DEFAULT '0';
-- Calculo del inventario
UPDATE tmp.itemInventory ai
JOIN (
SELECT itemFk Id_Article, SUM(quantity) Subtotal
FROM (
SELECT s.itemFk, - s.quantity quantity
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
JOIN warehouse w ON w.id = t.warehouseFk
WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate)
AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk
AND w.isComparative
UNION ALL
SELECT b.itemFk, b.quantity
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
JOIN warehouse w ON w.id = t.warehouseInFk
WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate)
AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk
AND w.isComparative
AND NOT e.isExcludedFromAvailable
AND NOT e.isRaid
UNION ALL
SELECT b.itemFk, - b.quantity
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
JOIN warehouse w ON w.id = t.warehouseOutFk
WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate)
AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk
AND w.isComparative
AND NOT e.isExcludedFromAvailable
AND NOT e.isRaid
) sub2
GROUP BY itemFk
) sub ON ai.id = sub.Id_Article
SET ai.inventory = sub.Subtotal,
ai.visible = sub.Subtotal,
ai.avalaible = sub.Subtotal,
ai.sd = sub.Subtotal;
-- Cálculo del visible
UPDATE tmp.itemInventory ai
JOIN (
SELECT itemFk Id_Article, SUM(quantity) Subtotal
FROM (
SELECT s.itemFk, s.quantity
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
JOIN warehouse w ON w.id = t.warehouseFk
WHERE t.shipped >= vDate
AND t.shipped < vDateTomorrow
AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL)
AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk
AND w.isComparative
UNION ALL
SELECT b.itemFk, - b.quantity
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
JOIN warehouse w ON w.id = t.warehouseInFk
WHERE t.landed = vDate
AND NOT t.isReceived
AND NOT e.isExcludedFromAvailable
AND NOT e.isRaid
AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk
AND w.isComparative
UNION ALL
SELECT b.itemFk, b.quantity
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
JOIN warehouse w ON w.id = t.warehouseOutFk
WHERE t.shipped = vDate
AND NOT t.isReceived
AND NOT e.isExcludedFromAvailable
AND NOT e.isRaid
AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk
AND w.isComparative
) sub2
GROUP BY itemFk
) sub ON ai.id = sub.Id_Article
SET ai.visible = ai.visible + sub.Subtotal;
-- Calculo del disponible
CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc
(INDEX (itemFk, warehouseFk))
ENGINE = MEMORY
SELECT sub.itemFk,
vWarehouseFk warehouseFk,
sub.dated,
SUM(sub.quantity) quantity
FROM (
SELECT s.itemFk,
DATE(t.shipped) dated,
- s.quantity quantity
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
JOIN warehouse w ON w.id = t.warehouseFk
WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo
AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk
AND w.isComparative
UNION ALL
SELECT b.itemFk, t.landed, b.quantity
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
JOIN warehouse w ON w.id = t.warehouseInFk
WHERE t.landed BETWEEN vDateTomorrow AND vDateTo
AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk
AND w.isComparative
AND NOT e.isExcludedFromAvailable
AND NOT e.isRaid
UNION ALL
SELECT b.itemFk, t.shipped, - b.quantity
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
JOIN warehouse w ON w.id = t.warehouseOutFk
WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo
AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk
AND w.isComparative
AND NOT e.isExcludedFromAvailable
AND NOT e.isRaid
) sub
GROUP BY sub.itemFk, sub.dated;
CALL item_getAtp(vDate);
CALL travel_upcomingArrivals(vWarehouseFk, vDate);
UPDATE tmp.itemInventory ai
JOIN (
SELECT it.itemFk,
SUM(it.quantity) quantity,
im.quantity minQuantity
FROM tmp.itemCalc it
JOIN tmp.itemAtp im ON im.itemFk = it.itemFk
JOIN item i ON i.id = it.itemFk
LEFT JOIN origin o ON o.id = i.originFk
LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk
WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL,
t.landing,
vDateToTomorrow)
GROUP BY it.itemFk
) sub ON sub.itemFk = ai.id
SET ai.avalaible = IF(sub.minQuantity > 0,
ai.avalaible,
ai.avalaible + sub.minQuantity),
ai.sd = ai.inventory + sub.quantity;
DROP TEMPORARY TABLE
tmp.itemTravel,
tmp.itemCalc,
tmp.itemAtp;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `multipleInventoryHistory` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `multipleInventoryHistory`(
vItemFk INT)
BEGIN
DECLARE vDateInventory DATETIME;
SELECT inventoried INTO vDateInventory FROM config;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `mysqlConnectionsSorter_kill` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `mysqlConnectionsSorter_kill`()
BEGIN
/**
* Elimina conexiones del usuario sorter con tiempo >= 30seg. Asociado al evento con el mismo nombre
*/
DECLARE vDone INT DEFAULT 0;
DECLARE vProcesId INT;
DECLARE vCursor CURSOR FOR
SELECT p.id
FROM information_schema.processlist p
WHERE USER = 'sorter'
AND TIME >= 30;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN vCursor;
l: LOOP
FETCH vCursor INTO vProcesId;
IF vDone THEN
LEAVE l;
END IF;
KILL vProcesId;
END LOOP;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `mysqlPreparedCount_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `mysqlPreparedCount_check`()
BEGIN
DECLARE vPreparedCount INTEGER;
SELECT VARIABLE_VALUE INTO vPreparedCount
FROM INFORMATION_SCHEMA.GLOBAL_STATUS
WHERE VARIABLE_NAME LIKE '%prepared_stmt_count%';
IF(vPreparedCount >= 40000) THEN
CALL `vn`.`mail_insert`('cau@verdnatura.es',
NULL,
'Problemas BBDD prepared_stmt_count',
CONCAT('Existen problemas con el servicio de Logiflora, prepared_stmt_count con valor: ',
vPreparedCount,
', está próximo a exceder su límite. \r\n Hay que reiniciar el servicio LF.VMP.Service del servidor a3.')
);
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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.myUser_getId(), ', "', vDescription, '")'
);
PREPARE stmt FROM @qryLog;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `orderDelete` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `orderListVolume`(IN vOrderId INT)
BEGIN
SELECT
o.id,
o.itemFk,
i.description,
o.amount,
round(ic.cm3delivery * o.amount / 1000000,3) as volume
FROM hedera.orderRow o
JOIN item i ON i.id = o.itemFk
JOIN itemCost ic ON ic.itemFk = o.itemFk AND ic.warehouseFk = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 vComponentCost INT DEFAULT 28;
DECLARE vGraceDate DATE;
DECLARE vDateEnd DATE;
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 */
SET vDateEnd = DATE_ADD(vDate, INTERVAL 1 DAY);
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 vDateEnd
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 COUNT(*)
INTO vIsInvoiceable
FROM tmp.packageToInvoicePositives;
IF vIsInvoiceable THEN
CALL ticket_add(vClient,
vDateEnd,
vWarehouse,
vCompany,
NULL,
NULL,
NULL,
vDateEnd,
account.myUser_getId(),
TRUE,
vNewTicket);
INSERT INTO ticketPackaging(
ticketFk,
packagingFk,
quantity,
pvp)
SELECT vNewTicket,
pti.packagingFk,
- SUM(pti.quantity) AS totalQuantity,
pti.price
FROM tmp.packageToInvoice pti
LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk
WHERE ptip.itemFK IS NOT NULL
OR vIsAllInvoiceable
GROUP BY packagingFk
HAVING totalQuantity;
INSERT INTO sale(
ticketFk,
itemFk,
concept,
quantity,
price
)
SELECT vNewTicket,
pti.itemFk,
i.name as concept,
sum(pti.quantity) as totalQuantity,
pti.price
FROM tmp.packageToInvoice pti
JOIN item i ON i.id = pti.itemFk
LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk
WHERE ptip.itemFK IS NOT NULL
OR vIsAllInvoiceable
GROUP BY pti.itemFk
HAVING totalQuantity;
INSERT INTO saleComponent(saleFk, componentFk, value)
SELECT id, vComponentCost, price
FROM sale
WHERE ticketFk = vNewTicket;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `packingListSwitch`(saleFk INT)
BEGIN
DECLARE valueFk INT;
DECLARE encajando INT DEFAULT 9;
SELECT isChecked INTO valueFk
FROM saleTracking
WHERE saleFk = saleFk
AND stateFk = encajando;
SET valueFk = (IFNULL(valueFk,0) + 1) MOD 3;
REPLACE saleTracking(saleFk, isChecked, workerFk, stateFk)
VALUES(saleFk,valueFk,account.myUser_getId(),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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `packingSite_startCollection` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `packingSite_startCollection`(vSelf INT, vTicketFk INT)
proc: BEGIN
/**
* @param vSelf packingSite id
* @param vTicketFk A ticket id from the collection to start
*/
DECLARE vExists BOOL;
DECLARE vIsAdvanced BOOL;
DECLARE vNewCollectionFk INT;
DECLARE vOldCollectionFk INT;
DECLARE vIsPackingByOther BOOL;
SELECT id, collectionFk
INTO vExists, vOldCollectionFk
FROM packingSite
WHERE id = vSelf;
IF NOT vExists THEN
CALL util.throw('packingSiteNotExists');
END IF;
SELECT COUNT(*) > 0
INTO vIsAdvanced
FROM packingSiteAdvanced
WHERE ticketFk = vTicketFk;
IF vIsAdvanced THEN
LEAVE proc;
END IF;
SELECT collectionFk INTO vNewCollectionFk
FROM ticketCollection WHERE ticketFk = vTicketFk;
IF vOldCollectionFk IS NOT NULL
AND vOldCollectionFk <> vNewCollectionFk THEN
SELECT COUNT(*) > 0
INTO vIsPackingByOther
FROM packingSite
WHERE id <> vSelf
AND collectionFk = vOldCollectionFk;
IF NOT vIsPackingByOther AND NOT collection_isPacked(vOldCollectionFk) THEN
CALL util.throw('cannotChangeCollection');
END IF;
END IF;
UPDATE packingSite SET collectionFk = vNewCollectionFk
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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), 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 * 100 + vRow )
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), 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `parking_algemesi` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `parking_algemesi`(vFromRow INT, vToRow INT, vSectorFk INT, vLetter VARCHAR(1), vPickingOrder INT, vTrolleysByLine INT)
BEGIN
DECLARE vRow INT;
DECLARE vCode VARCHAR(8);
DECLARE i INT;
IF vToRow < vFromRow THEN
SET vRow = vFromRow;
WHILE vRow >= vToRow DO
SET i = 1;
WHILE i <= vTrolleysByLine DO
SET vCode = CONCAT(vLetter,'-', LPAD(vRow,2,'0'),'-', i);
INSERT IGNORE INTO vn.parking( sectorFk, `code`, pickingOrder)
VALUES (vSectorFk, vCode, vPickingOrder + (i * 10))
ON DUPLICATE KEY UPDATE `code` = vCode;
SET i = i + 1;
END WHILE;
SET vRow = vRow - 1;
END WHILE;
ELSE
SET vRow = vFromRow;
WHILE vRow <= vToRow DO
SET i = 1;
WHILE i <= vTrolleysByLine DO
SET vCode = CONCAT(vLetter,'-', LPAD(vRow,2,'0'),'-', i);
INSERT IGNORE INTO vn.parking( sectorFk, `code`, pickingOrder)
VALUES (vSectorFk, vCode, vPickingOrder + (i * 10) )
ON DUPLICATE KEY UPDATE `code` = vCode;
SET i = i + 1;
END WHILE;
SET vRow = vRow + 1;
END WHILE;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `parking_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `parking_new`(vStart INT, vEnd INT, vSectorFk INT)
BEGIN
DECLARE vRow INT;
DECLARE vColumn INT;
DECLARE vLetters VARCHAR(200);
DECLARE vLettersLength INT;
SET vColumn = vStart;
SET vRow = 1;
SET vLetters = 'ABCDEF';
SET vLettersLength = LENGTH(vLetters);
WHILE vColumn <= vEnd DO
REPLACE vn.parking(`column`, `row`, `code`, sectorFk)
VALUES(vColumn, vRow, CONCAT(vColumn,MID(vLetters,vRow,1)), vSectorFk);
SET vRow = vRow + 1;
IF vRow > vLettersLength THEN
SET vRow = 1;
SET vColumn = vColumn + 1;
END IF;
END WHILE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `parking_setOrder` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `parking_setOrder`(vWarehouseFk INT)
BEGIN
/*
* Ordena el orden de preparacion de los parking de acuerdo con la tabla vn.corridor
*/
UPDATE vn.parking p
JOIN (
SELECT code,
@orden := @orden + 10 AS po
FROM (
SELECT c.prepOrder,
p.code,
@orden := 0,
IF(c.isAscendent, 1,-1) * CAST(SUBSTRING(p.code,3,2) AS DECIMAL(2,0)) subCorridor ,
CAST(IF(LENGTH(p.code) > 5, SUBSTRING(p.code,6,2), 0) AS DECIMAL(2,0)) ubication
FROM vn.parking p
JOIN vn.sector s ON s.id = p.sectorFk
JOIN vn.corridor c ON c.code = LEFT(p.code,1) COLLATE utf8_general_ci
WHERE s.warehouseFk = vWarehouseFk) sub
ORDER BY sub.prepOrder, subCorridor, ubication) sub2 ON sub2.code = p.code
SET p.pickingOrder = sub2.po;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `payment_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `payment_add`(
vDated DATE,
vSupplierFk INT,
vAmount DOUBLE,
vCurrencyFk INT,
vForeignValue DOUBLE,
vBankFk INT,
vPayMethodFk INT,
vExpenseFk DOUBLE,
vConcept VARCHAR(40),
vCompanyFk INT)
BEGIN
/**
* Registra un pago realizado a un proveedor y
* su correspondiente registro en caja.
*
* @param vDated Fecha del pago
* @param vSupplierFk Id del proveedor
* @param vAmount Cantidad a pagar
* @param vCurrencyFk Id de la moneda
* @param vForeignValue Tipo de cambio utilizado
* @param vBankFk Id del banco
* @param vPayMethodFk Id del método de pago
* @param vExpenseFk Id de gasto
* @param vConcept Concepto del pago
* @param vCompanyFk Id de la empresa
* @return paymentFk Id de pago insertado
*/
INSERT INTO till(
concept,
serie,
`number`,
`out`,
dated,
isAccountable,
bankFk,
workerFk,
companyFk,
isConciliate
)
SELECT CONCAT('n/pago a ', `name`),
'R',
vSupplierFk,
vAmount,
vDated,
1,
vBankFk,
account.myUser_getId(),
vCompanyFk,
1
FROM supplier
WHERE id = vSupplierFk;
INSERT INTO payment(
received,
dueDated,
supplierFk,
amount,
currencyFk,
divisa,
bankFk,
payMethodFk,
bankingFees,
concept,
companyFk
)
VALUES(
vDated,
vDated,
vSupplierFk,
vAmount,
vCurrencyFk,
IF(NOT vForeignValue, NULL, vForeignValue),
vBankFk,
vPayMethodFk,
vExpenseFk,
vConcept,
vCompanyFk
);
SELECT LAST_INSERT_ID() paymentFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `prepareClientList` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prepareClientList`()
BEGIN
/*
* Require la tabla tmp.ticket(id,clientFk)
*/
DROP TEMPORARY TABLE IF EXISTS tmp.client;
CREATE TEMPORARY TABLE tmp.client
(PRIMARY KEY (id))
ENGINE = MEMORY
SELECT DISTINCT clientFk id
FROM 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `prepareTicketList` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `prepareTicketList`(vStartingDate DATETIME, vEndingDate DATETIME)
BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.productionTicket;
CREATE TEMPORARY TABLE tmp.productionTicket
(PRIMARY KEY (ticketFk))
ENGINE = MEMORY
SELECT t.id ticketFk, t.clientFk
FROM vn.ticket t
LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id
JOIN vn.client c ON c.id = t.clientFk
WHERE c.typeFk IN ('normal','handMaking','internalUse')
AND (
t.shipped BETWEEN util.VN_CURDATE() AND vEndingDate
OR (
ts.alertLevel < 3
AND t.shipped >= vStartingDate
AND t.shipped < util.VN_CURDATE()
)
);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `previousSticker_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `previousSticker_get`(vSaleGroupFk INT)
BEGIN
/**
* Devuelve los campos a imprimir en una etiqueta de preparación previa.
* Actualiza el valor de vn.saleGroup.parkingFk en el caso de que exista un
* saleGroup del mismo ticket con parking, del mismo sector, para que todos se
* pongan juntos.
*
* @param vSaleGroupFk Identificador de vn.saleGroup
*/
DECLARE vTicketFk INT;
DECLARE vParkingFk INT;
DECLARE vSectorFk INT;
SELECT s.ticketFk
INTO vTicketFk
FROM vn.saleGroupDetail sgd
JOIN vn.sale s ON s.id = sgd.saleFk
WHERE sgd.saleGroupFk = vSaleGroupFk
LIMIT 1;
SELECT sg.parkingFk, sc.sectorFk
INTO vParkingFk, vSectorFk
FROM vn.saleGroup sg
JOIN vn.sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sg.id
JOIN vn.sectorCollection sc ON sc.id = scsg.sectorCollectionFk
JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = sg.id
JOIN vn.sale s ON s.id = sgd.saleFk
WHERE s.ticketFk = vTicketFk
AND sg.parkingFk IS NOT NULL
LIMIT 1;
UPDATE vn.saleGroup sg
SET sg.parkingFk = vParkingFk
WHERE sg.id = vSaleGroupFk
AND sg.sectorFk = vSectorFk;
SELECT sgd.saleGroupFk,
t.id ticketFk,
p.code as location,
t.observations,
IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) shippingHour,
IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) shippingMinute ,
IFNULL(MAX(i.itemPackingTypeFk),'H') itemPackingTypeFk ,
count(*) items,
sc.description sector
FROM vn.sale s
JOIN vn.item i ON i.id = s.itemFk
JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk
JOIN vn.sector sc ON sc.id = sg.sectorFk
JOIN vn.ticket t ON t.id = s.ticketFk
LEFT JOIN vn.parking p ON p.id = sg.parkingFk
LEFT JOIN vn.`zone` z ON z.id = t.zoneFk
WHERE sgd.saleGroupFk = vSaleGroupFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `printer_checkSector` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `printer_checkSector`(vLabelerFk tinyint(3) unsigned, vSector INT(11))
BEGIN
/**
* Comprueba si la impresora pertenece al sector
*
* @param vLabelerFk id de la impresora
* @param vSector sector a comprobar
*/
DECLARE isPrinterInNewSector BOOL;
IF vLabelerFk IS NOT NULL THEN
SELECT COUNT(sectorFK) INTO isPrinterInNewSector
FROM vn.printer p
WHERE id = vLabelerFk AND sectorFk = vSector;
IF !isPrinterInNewSector THEN
CALL util.throw("PrinterNotInSameSector");
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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `productionControl` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `productionControl`(
vWarehouseFk INT,
vScopeDays INT
)
proc: BEGIN
/**
* Devuelve un listado de tickets con parámetros relativos a la producción de los días en rango.
*
* @param vWarehouseFk Identificador de warehouse
* @param vScopeDays Número de días desde hoy en adelante que entran en el cálculo.
*
* @return Table tmp.productionBuffer
*/
DECLARE vEndingDate DATETIME;
DECLARE vIsTodayRelative BOOLEAN;
SELECT util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, maxProductionScopeDays) DAY
INTO vEndingDate
FROM productionConfig;
SELECT isTodayRelative INTO vIsTodayRelative
FROM worker
WHERE id = getUser(); -- Cambiar por account.myUser_getId(), falta dar permisos
CALL prepareTicketList(util.yesterday(), vEndingDate);
CREATE OR REPLACE TEMPORARY TABLE tmp.ticket
SELECT * FROM tmp.productionTicket;
CALL prepareClientList();
CREATE OR REPLACE TEMPORARY TABLE tmp.sale_getProblems
(INDEX (ticketFk)) ENGINE = MEMORY
SELECT tt.ticketFk, tt.clientFk, t.warehouseFk, t.shipped
FROM tmp.productionTicket tt
JOIN ticket t ON t.id = tt.ticketFk;
CALL ticket_getProblems(vIsTodayRelative);
CREATE OR REPLACE TEMPORARY TABLE tmp.productionBuffer
(PRIMARY KEY(ticketFk), previaParking VARCHAR(255))
ENGINE = MEMORY
SELECT tt.ticketFk,
tt.clientFk,
t.warehouseFk,
t.nickname,
t.packages,
IF(HOUR(t.shipped), HOUR(t.shipped), COALESCE(HOUR(zc.hour),HOUR(z.hour))) HH,
COALESCE(HOUR(zc.hour), HOUR(z.hour)) Departure,
COALESCE(MINUTE(t.shipped), MINUTE(zc.hour), MINUTE(z.hour)) mm,
t.routeFk,
IF(dm.code = 'DELIVERY', z.`id`, 0) zona,
t.nickname addressNickname,
a.postalCode,
a.city,
p.name province,
CONCAT(z.`name`,' ',IFNULL(RIGHT(t.routeFk,3),'')) agency,
am.id agencyModeFk,
0 `lines`,
CAST( 0 AS DECIMAL(5,2)) m3,
CAST( 0 AS DECIMAL(5,2)) preparationRate,
"" problem,
IFNULL(tls.state,2) state,
w.code workerCode,
DATE(t.shipped) shipped,
wk.code salesPersonCode,
p.id provinceFk,
tls.productionOrder,
IFNULL(tls.alertLevel, 0) alertLevel,
t.isBoxed palletized,
IF(rm.isPickingAllowed, rm.bufferFk, NULL) ubicacion,
tlu.lastUpdated,
IFNULL(st.graphCategory, 0) graphCategory,
pk.code parking,
0 H,
0 V,
0 N,
st.isOk,
ag.isOwn,
rm.bufferFk
FROM tmp.productionTicket tt
JOIN ticket t ON tt.ticketFk = t.id
LEFT JOIN ticketStateToday tst ON tst.ticketFk = t.id
LEFT JOIN `state` st ON st.id = tst.state
LEFT JOIN client c ON c.id = t.clientFk
LEFT JOIN worker wk ON wk.id = c.salesPersonFk
JOIN address a ON a.id = t.addressFk
LEFT JOIN province p ON p.id = a.provinceFk
JOIN agencyMode am ON am.id = t.agencyModeFk
JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
JOIN agency ag ON ag.id = am.agencyFk
LEFT JOIN ticketState tls ON tls.ticketFk = tt.ticketFk
LEFT JOIN ticketLastUpdated tlu ON tlu.ticketFk = tt.ticketFk
LEFT JOIN worker w ON w.id = tls.userFk
LEFT JOIN routesMonitor rm ON rm.routeFk = t.routeFk
LEFT JOIN `zone` z ON z.id = t.zoneFk
LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk
AND DATE(t.shipped) = zc.dated
LEFT JOIN ticketParking tp ON tp.ticketFk = t.id
LEFT JOIN parking pk ON pk.id = tp.parkingFk
WHERE t.warehouseFk = vWarehouseFk
AND dm.code IN ('AGENCY', 'DELIVERY', 'PICKUP');
UPDATE tmp.productionBuffer pb
JOIN (
SELECT pb.ticketFk, GROUP_CONCAT(p.code) previaParking
FROM tmp.productionBuffer pb
JOIN sale s ON s.ticketFk = pb.ticketFk
JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
JOIN saleGroup sg ON sg.id = sgd.saleGroupFk
JOIN parking p ON p.id = sg.parkingFk
GROUP BY pb.ticketFk
) t ON t.ticketFk = pb.ticketFk
SET pb.previaParking = t.previaParking;
-- Problemas por ticket
ALTER TABLE tmp.productionBuffer
CHANGE COLUMN `problem` `problem` VARCHAR(255),
ADD COLUMN `collectionH` INT,
ADD COLUMN `collectionV` INT,
ADD COLUMN `collectionN` INT;
UPDATE tmp.productionBuffer pb
JOIN tmp.ticket_problems tp ON tp.ticketFk = pb.ticketFk
SET pb.problem = TRIM(CAST(CONCAT( IFNULL(tp.itemShortage, ''),
IFNULL(tp.itemDelay, ''),
IFNULL(tp.itemLost, ''),
IF(tp.isFreezed, ' CONGELADO',''),
IF(tp.hasHighRisk, ' RIESGO',''),
IF(tp.hasTicketRequest, ' COD 100',''),
IF(tp.isTaxDataChecked, '',' FICHA INCOMPLETA'),
IF(tp.hasComponentLack, ' COMPONENTES', ''),
IF(HOUR(util.VN_NOW()) < pb.HH AND tp.isTooLittle, ' PEQUEÑO', '')
) AS char(255)));
-- Clientes Nuevos o Recuperados
UPDATE tmp.productionBuffer pb
LEFT JOIN bs.clientNewBorn cnb ON cnb.clientFk = pb.clientFk
JOIN productionConfig pc
SET pb.problem = TRIM(CAST(CONCAT('NUEVO ', pb.problem) AS CHAR(255)))
WHERE (cnb.clientFk IS NULL OR cnb.isRookie)
AND pc.rookieDays;
-- Líneas y volumen por ticket
UPDATE tmp.productionBuffer pb
JOIN (
SELECT tt.ticketFk,
COUNT(*) `lines`,
SUM(sv.volume) m3,
IFNULL(SUM(IF(sv.isPicked, sv.volume, 0)) / SUM(sv.volume), 0) rate
FROM tmp.productionTicket tt
JOIN saleVolume sv ON sv.ticketFk = tt.ticketFk
GROUP BY tt.ticketFk
) m ON m.ticketFk = pb.ticketFk
SET pb.`lines` = m.`lines`,
pb.m3 = m.m3,
pb.preparationRate = m.rate;
DELETE FROM tmp.productionBuffer
WHERE NOT `lines`;
-- Lineas por linea de encajado
UPDATE tmp.productionBuffer pb
JOIN (
SELECT ticketFk,
SUM(sub.H) H,
SUM(sub.V) V,
SUM(sub.N) N
FROM (
SELECT t.ticketFk,
SUM(i.itemPackingTypeFk = 'H') H,
SUM(i.itemPackingTypeFk = 'V') V,
SUM(i.itemPackingTypeFk IS NULL) N
FROM tmp.productionTicket t
JOIN sale s ON s.ticketFk = t.ticketFk
JOIN item i ON i.id = s.itemFk
GROUP BY t.ticketFk, i.itemPackingTypeFk
) sub
GROUP BY ticketFk
) sub2 ON sub2.ticketFk = pb.ticketFk
SET pb.H = sub2.H,
pb.V = sub2.V,
pb.N = sub2.N;
-- Colecciones segun tipo de encajado
UPDATE tmp.productionBuffer pb
JOIN ticketCollection tc ON pb.ticketFk = tc.ticketFk
SET pb.collectionH = IF(pb.H, tc.collectionFk, NULL),
pb.collectionV = IF(pb.V, tc.collectionFk, NULL),
pb.collectionN = IF(pb.N, tc.collectionFk, NULL);
-- Previa pendiente
ALTER TABLE tmp.productionBuffer
ADD previousWithoutParking BOOL DEFAULT FALSE;
CREATE OR REPLACE TEMPORARY TABLE tmp.ticketWithPrevia
(ticketFk INT PRIMARY KEY,
salesCount INT DEFAULT 0,
salesInParkingCount INT DEFAULT 0)
ENGINE = MEMORY;
-- Insertamos todos los tickets que tienen productos parkineados
-- en sectores de previa, segun el sector
CREATE OR REPLACE TEMPORARY TABLE tItemShelvingStock
(PRIMARY KEY(itemFk, sectorFk))
ENGINE = MEMORY
SELECT ish.itemFk,
p.sectorFk,
st.code = 'previousPrepared' isPreviousPrepared,
sc.itemPackingTypeFk
FROM itemShelving ish
JOIN shelving sh ON sh.code = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN sector sc ON sc.id = p.sectorFk
JOIN sectorType st ON st.id = sc.typeFk
WHERE p.sectorFk
AND ish.visible
GROUP BY ish.itemFk, p.sectorFk;
INSERT INTO tmp.ticketWithPrevia(ticketFk, salesCount)
SELECT pb.ticketFk, COUNT(DISTINCT s.id)
FROM tmp.productionBuffer pb
JOIN sale s ON s.ticketFk = pb.ticketFk
JOIN tItemShelvingStock iss ON iss.itemFk = s.itemFk
JOIN sector sc ON sc.id = iss.sectorFk
JOIN item i ON i.id = iss.itemFk
WHERE iss.isPreviousPrepared
AND (sc.itemPackingTypeFk IS NULL
OR (i.itemPackingTypeFk IS NULL AND NOT pb.V)
OR sc.itemPackingTypeFk = i.itemPackingTypeFk)
AND s.quantity > 0
GROUP BY pb.ticketFk;
-- Se calcula la cantidad de productos que estan ya preparados porque su saleGroup está aparcado
UPDATE tmp.ticketWithPrevia twp
JOIN (
SELECT pb.ticketFk, COUNT(DISTINCT s.id) salesInParkingCount
FROM tmp.productionBuffer pb
JOIN sale s ON s.ticketFk = pb.ticketFk
JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
JOIN saleGroup sg ON sg.id = sgd.saleGroupFk
WHERE sg.parkingFk IS NOT NULL
AND s.quantity > 0
GROUP BY pb.ticketFk
) sub ON twp.ticketFk = sub.ticketFk
SET twp.salesInParkingCount = sub.salesInParkingCount;
-- Marcamos como pendientes aquellos que no coinciden las cantidades
UPDATE tmp.productionBuffer pb
JOIN tmp.ticketWithPrevia twp ON twp.ticketFk = pb.ticketFk
SET pb.previousWithoutParking = TRUE
WHERE twp.salesCount > twp.salesInParkingCount;
DROP TEMPORARY TABLE
tmp.productionTicket,
tmp.ticket,
tmp.risk,
tmp.ticket_problems,
tmp.ticketWithPrevia,
tItemShelvingStock;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `productionError_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `productionError_add`()
BEGIN
DECLARE vDatedFrom DATETIME;
DECLARE vDatedTo DATETIME;
/**
* Rellena la tabla vn.productionError con estadisticas de encajadores, revisores y sacadores. Se ejecuta en el nightTask
*/
SELECT util.VN_CURDATE() - INTERVAL 1 DAY, util.dayend(util.VN_CURDATE() - INTERVAL 1 DAY) INTO vDatedFrom, vDatedTo;
CALL timeControl_calculateAll(vDatedFrom, vDatedTo);
-- Rellena la tabla tmp.errorsByClaim con encajadores, revisores y sacadores
CREATE OR REPLACE TEMPORARY TABLE tmp.errorsByClaim
ENGINE = MEMORY
SELECT COUNT(c.ticketFk) errors,
cd.workerFk
FROM claimDevelopment cd
JOIN claim c ON cd.claimFk = c.id
JOIN ticket t ON c.ticketFk = t.id
JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id
WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
AND cr.code IN ('pic', 'chk', 'pck')
GROUP BY cd.workerFk;
-- Genera la tabla tmp.volume con encajadores, sacadores y revisores
CREATE OR REPLACE TEMPORARY TABLE tmp.volume
ENGINE = MEMORY
SELECT SUM(w.volume) volume,
w.workerFk
FROM bs.workerProductivity w
WHERE w.dated BETWEEN vDatedFrom AND vDatedTo
GROUP BY w.workerFk;
-- Rellena la tabla tmp.errorsByChecker con fallos de revisores
CREATE OR REPLACE TEMPORARY TABLE tmp.errorsByChecker
ENGINE = MEMORY
WITH rankedWorkers AS (
SELECT sm.id,
st.workerFk,
ROW_NUMBER() OVER(PARTITION BY sm.id ORDER BY s2.`order`) rnk
FROM vn.saleMistake sm
JOIN vn.saleTracking st ON sm.saleFk = st.saleFk
JOIN vn.`state` s2 ON s2.id = st.stateFk
JOIN vn.sale s ON s.id = sm.saleFk
JOIN vn.ticket t ON t.id = s.ticketFk
WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
AND s2.code IN ('OK', 'PREVIOUS_PREPARATION', 'PREPARED', 'CHECKED')
)
SELECT workerFk, COUNT(*) errors
FROM rankedWorkers
WHERE rnk = 1
GROUP BY workerFk;
-- Rellena la tabla tmp.expeditionErrors con fallos de expediciones
CREATE OR REPLACE TEMPORARY TABLE tmp.expeditionErrors
ENGINE = MEMORY
SELECT COUNT(t.id) errors,
e.workerFk
FROM vn.expeditionMistake pm
JOIN vn.expedition e ON e.id = pm.expeditionFk
JOIN vn.ticket t ON t.id = e.ticketFk
WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
GROUP BY e.workerFk;
-- Genera la tabla tmp.total para sacadores y revisores
CREATE OR REPLACE TEMPORARY TABLE tmp.total
ENGINE = MEMORY
SELECT st.workerFk,
COUNT(DISTINCT t.id) ticketCount,
COUNT(s.id) lineCount
FROM saleTracking st
JOIN `state` s2 ON s2.id = st.stateFk
JOIN sale s ON s.id = st.saleFk
JOIN ticket t ON s.ticketFk = t.id
WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo)
AND s2.code IN ('OK','PREVIOUS_PREPARATION','PREPARED','CHECKED')
GROUP BY st.workerFk;
-- Rellena la tabla vn.productionError con sacadores
INSERT INTO productionError(userFk,
firstname,
lastname,
rol,
ticketNumber,
lineNumber,
error,
volume,
hourStart,
hourEnd,
hourWorked,
dated)
SELECT w.id,
w.firstName,
w.lastName,
"Sacadores",
t.ticketCount totalTickets,
t.lineCount,
IFNULL(ec.errors,0) + IFNULL(ec2.errors,0) errors,
v.volume volume,
SUBSTRING(tc.tableTimed, 1, 5) hourStart,
SUBSTRING(tc.tableTimed, LENGTH(tc.tableTimed)-4, 5) hourEnd,
IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) hourWorked,
vDatedFrom dated
FROM tmp.total t
LEFT JOIN worker w ON w.id = t.workerFk
LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = t.workerFk
LEFT JOIN tmp.errorsByClaim ec ON ec.workerFk = t.workerFk
LEFT JOIN tmp.volume v ON v.workerFk = t.workerFk
LEFT JOIN tmp.errorsByChecker ec2 ON ec2.workerFk = t.workerFk
JOIN (SELECT DISTINCT w.id -- Verificamos que son sacadores
FROM vn.collection c
JOIN vn.state s ON s.id = c.stateFk
JOIN vn.train tn ON tn.id = c.trainFk
JOIN vn.worker w ON w.id = c.workerFk
WHERE c.created BETWEEN vDatedFrom AND vDatedTo) sub ON sub.id = w.id
GROUP BY w.id;
CREATE OR REPLACE TEMPORARY TABLE itemPickerErrors -- Errores de los sacadores, derivadores de los revisadores
ENGINE = MEMORY
SELECT COUNT(c.ticketFk) errors,
tt.userFk
FROM claimDevelopment cd
JOIN claim c ON cd.claimFk = c.id
JOIN ticket t ON c.ticketFk = t.id
JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id
JOIN ticketTracking tt ON tt.ticketFk = t.id
JOIN `state` s ON s.id = tt.stateFk
WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
AND cr.code = 'chk'
AND s.code = 'ON_PREPARATION'
GROUP BY tt.userFk;
UPDATE productionError ep
JOIN itemPickerErrors ipe ON ipe.userFk = ep.userFk
SET ep.error = ep.error + ipe.errors
WHERE vDatedFrom = ep.dated AND ep.rol = 'Sacadores';
DROP TEMPORARY TABLE itemPickerErrors;
-- Rellena la tabla vn.productionError con revisores
CALL productionError_addCheckerPackager(vDatedFrom, vDatedTo, "Revisadores");
-- Genera la tabla tmp.total para encajadores
CREATE OR REPLACE TEMPORARY TABLE tmp.total
ENGINE = MEMORY
SELECT e.workerFk,
COUNT(DISTINCT t.id) ticketCount,
COUNT(s.id) lineCount
FROM expedition e
JOIN ticket t ON e.ticketFk = t.id
JOIN sale s ON s.ticketFk = t.id
WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo
GROUP BY e.workerFk;
-- Rellena la tabla vn.productionError con encajadores
CALL productionError_addCheckerPackager(vDatedFrom, vDatedTo, "Encajadores");
DROP TEMPORARY TABLE tmp.errorsByClaim,
tmp.volume,
tmp.errorsByChecker,
tmp.expeditionErrors,
tmp.total;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `productionError_addCheckerPackager` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `productionError_addCheckerPackager`(
vDatedFrom DATETIME,
vDatedTo DATETIME,
vRol VARCHAR(50))
BEGIN
/**
* Rellena la tabla vn.productionError con rol
*
* @param vDatedFrom Fecha desde
* @param vDatedTo Fecha hasta
* @param vRol rol a insertar
*/
INSERT INTO productionError(userFk,
firstname,
lastname,
rol,
ticketNumber,
lineNumber,
error,
volume,
hourStart,
hourEnd,
hourWorked,
dated)
SELECT w.id,
w.firstName,
w.lastName,
vRol,
t.ticketCount totalTickets,
t.lineCount,
IFNULL(ec.errors,0) + IFNULL(ec2.errors,0) + IFNULL(pe.errors,0) errors,
NULL volume,
SUBSTRING(tc.tableTimed, 1, 5) hourStart,
SUBSTRING(tc.tableTimed, LENGTH(tc.tableTimed)-4, 5) hourEnd,
IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) hourWorked,
vDatedFrom dated
FROM tmp.total t
LEFT JOIN worker w ON w.id = t.workerFk
LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = t.workerFk
LEFT JOIN tmp.errorsByClaim ec ON ec.workerFk = t.workerFk
LEFT JOIN tmp.volume v ON v.workerFk = t.workerFk
LEFT JOIN tmp.errorsByChecker ec2 ON ec2.workerFk = t.workerFk
LEFT JOIN tmp.expeditionErrors pe ON pe.workerFk = t.workerFk
GROUP BY w.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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `productionSectorList`(vSectorFk INT)
BEGIN
/**
* Devuelve el listado de sale que se puede preparar en previa para ese sector
*
* @param vSectorFk Identificador de sector
*/
DECLARE vWarehouseFk INT;
SELECT warehouseFk INTO vWarehouseFk
FROM sector
WHERE id = vSectorFk;
DROP TEMPORARY TABLE IF EXISTS tmp.whiteTicket;
CREATE TEMPORARY TABLE tmp.whiteTicket
(ticketFk INT PRIMARY KEY)
SELECT s.ticketFk , count(*) AS saleNum, sum(ISNULL(i.itemPackingTypeFk)) iptNull
FROM sale s
JOIN item i ON i.id = s.itemFk
JOIN ticket t ON t.id = s.ticketFk
WHERE t.shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(HOUR, 23, util.VN_CURDATE())
GROUP BY s.ticketFk
HAVING saleNum = iptNull;
DROP TEMPORARY TABLE IF EXISTS tmp.sectorTypeTicket;
CREATE TEMPORARY TABLE tmp.sectorTypeTicket
(ticketFk INT PRIMARY KEY)
SELECT s.ticketFk , sum(i.itemPackingTypeFk <=> sc.itemPackingTypeFk) iptSector
FROM sale s
JOIN item i ON i.id = s.itemFk
JOIN ticket t ON t.id = s.ticketFk
JOIN sector sc ON sc.id = vSectorFk
WHERE t.shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(HOUR, 23, util.VN_CURDATE())
GROUP BY s.ticketFk
HAVING iptSector;
CALL productionControl(vWarehouseFk, 0);
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 AS lastTicket
FROM (
SELECT * FROM (
SELECT isa.saleFk,
isa.Modificado,
isa.ticketFk,
isa.isPicked,
isa.itemFk,
isa.quantity,
isa.concept,
i.itemPackingTypeFk,
isa.`size`,
isa.Estado,
isa.sectorProdPriority,
isa.available,
isa.sectorFk,
isa.matricula,
isa.parking,
isa.itemShelving,
isa.Agency,
isa.shipped,
isa.`grouping`,
isa.packing,
isa.`hour`,
isa.isPreviousPreparable,
isa.physicalVolume,
isa.warehouseFk ,
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 itemShelvingAvailable isa
JOIN item i ON i.id = isa.itemFk
JOIN sector s ON s.id = isa.sectorFk AND s.warehouseFk = isa.warehouseFk
JOIN sectorType st ON st.id = s.typeFk
JOIN ticket t ON t.id = isa.ticketFk
LEFT JOIN tmp.whiteTicket wt ON wt.ticketFk = isa.ticketFk
LEFT JOIN tmp.sectorTypeTicket stt ON stt.ticketFk = isa.ticketFk
LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = isa.saleFk
JOIN client c ON c.id = t.clientFk
JOIN tmp.productionBuffer pb ON pb.ticketFk = t.id
JOIN packagingConfig pc
WHERE IF(st.code = 'previousByPacking',
i.`size` > pc.previousPreparationMinimumSize
AND (MOD(TRUNCATE(isa.quantity,0), isa.packing)= 0 ),
TRUE)
AND sgd.saleFk IS NULL
AND isa.sectorFk = vSectorFk
AND isa.quantity > 0
AND pb.problem = ""
AND (i.itemPackingTypeFk <=> s.itemPackingTypeFk
OR ISNULL(s.itemPackingTypeFk)
OR wt.ticketFk
OR (stt.ticketFk AND ISNULL(i.itemPackingTypeFk)))
GROUP BY saleFk
HAVING isa.quantity <= totalAvailable
) sub2
ORDER BY Hora, Minuto, ticketFk LIMIT 10000000000000000000
) sub;
DROP TEMPORARY TABLE tmp.whiteTicket;
DROP TEMPORARY TABLE tmp.sectorTypeTicket;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `raidUpdate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `raidUpdate`()
BEGIN
/**
* Actualiza el travel de las entradas de redadas
*/
UPDATE entry e
JOIN entryVirtual ev ON ev.entryFk = e.id
JOIN travel t ON t.id = e.travelFk
JOIN (
SELECT *
FROM (
SELECT t.id, t.landed, tt.warehouseInFk, tt.warehouseOutFk
FROM travel t
JOIN (
SELECT t.warehouseInFk, t.warehouseOutFk
FROM entryVirtual ev
JOIN entry e ON e.id = ev.entryFk
JOIN travel t ON t.id = e.travelFk
GROUP BY t.warehouseInFk, t.warehouseOutFk
) tt ON t.warehouseInFk = tt.warehouseInFk AND t.warehouseOutFk = tt.warehouseOutFk
WHERE shipped > util.VN_CURDATE() AND NOT isDelivered
ORDER BY t.landed
LIMIT 10000000000000000000
) t
GROUP BY t.warehouseInFk, t.warehouseOutFk
) tt ON t.warehouseInFk = tt.warehouseInFk AND t.warehouseOutFk = tt.warehouseOutFk
SET e.travelFk = t.id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `rateView` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `rateView`()
BEGIN
/**
* Muestra información sobre tasas de cambio de Dolares
*/
SELECT
t.year año,
t.month mes,
pay.dollars dolares,
pay.changePractical cambioPractico,
CAST(SUM(iit.foreignValue ) / SUM(iit.taxableBase) AS DECIMAL(5,4))cambioTeorico,
pay.changeOfficial cambioOficial
FROM invoiceIn ii
JOIN time t ON t.dated = ii.issued
JOIN invoiceInTax iit ON ii.id = iit.invoiceInFk
JOIN
( SELECT
t.year,
t.month,
CAST(SUM(p.divisa) AS DECIMAL(10,2)) dollars,
CAST(SUM(p.divisa) / SUM(p.amount) AS DECIMAL(5,4)) changePractical,
CAST(rr.value * 0.998 AS DECIMAL(5,4)) changeOfficial
FROM payment p
JOIN time t ON t.dated = p.received
JOIN referenceRate rr ON rr.dated = p.received
JOIN currency c ON c.id = rr.currencyFk
WHERE p.divisa
AND c.code = 'USD'
GROUP BY t.year, t.month
) pay ON t.year = pay.year AND t.month = pay.month
JOIN currency c ON c.id = ii.currencyFk
WHERE c.code = 'USD'
AND iit.foreignValue
AND iit.taxableBase
GROUP BY t.year, t.month;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `rate_getPrices` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `rate_getPrices`(
vDated DATE,
vWarehouseFk INT
)
BEGIN
/**
* Prepara una tabla con las tarifas aplicables
* en funcion de la fecha y el almacén.
*
* @param vDated Fecha para la cual calcula la tarifa
* @param vWarehouseFk Warehouse para el cual calcula la tarifa
* @return tmp.rate (rate0, rate1, rate2, rate3)
*/
CREATE OR REPLACE TEMPORARY TABLE tmp.rate
ENGINE = MEMORY
SELECT rate0,
rate1,
rate2,
rate3
FROM(
(SELECT 1 `order`,
rate0,
rate1,
rate2,
rate3
FROM rate
WHERE dated <= vDated
AND warehouseFk = vWarehouseFk
ORDER BY dated DESC
LIMIT 1
)
UNION
(SELECT 2,
rate0,
rate1,
rate2,
rate3
FROM rateConfig
)
ORDER BY `order` ASC
LIMIT 1
)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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `recipe_Plaster` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `recipe_Plaster`(vItemFk INT, vTicketFk INT, vQuantity INT)
BEGIN
DECLARE vLastCost DECIMAL(10,2);
DECLARE vWarehouseFk INT;
DECLARE vShipped DATE;
DECLARE vEntryFk INT;
DECLARE vTravelFk INT;
CALL cache.last_buy_refresh(FALSE);
SELECT warehouseFk, shipped
INTO vWarehouseFk, vShipped
FROM vn.ticket
WHERE id = vTicketFk;
UPDATE vn.ticket t
JOIN vn.item i ON i.id = vItemFk
SET t.nickname = CONCAT(vQuantity,' ',i.longName)
WHERE t.id = vTicketFk;
SELECT b.buyingValue INTO vLastCost
FROM vn.buy b
JOIN cache.last_buy lb ON lb.buy_id = b.id
WHERE lb.item_id = vItemFk
ORDER BY (lb.warehouse_id = vWarehouseFk) DESC
LIMIT 1;
INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price)
SELECT vTicketFk, 98, - vQuantity, i.longName, vLastCost
FROM vn.item i
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `remittance_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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `remittance_calc`(
vDated DATE
)
BEGIN
/**
* Calcula los datos de remesa, incluyendo el importe,
* el vencimiento, y otros datos relevantes.
*
* @param vDated Fecha a calcular
* @return tmp.remittance
*/
CREATE OR REPLACE TEMPORARY TABLE tmp.remittance
SELECT CONCAT(s.nif, REPEAT('0', 12 - LENGTH(s.nif))) cif,
c.id clientFk,
c.name client,
c.fi,
sub.paymentDate,
0 invoiceAmount,
CAST(sub.receipt AS DECIMAL(10,2)) receiptAmount,
0 currentAmount,
sub.companyFk,
c.socialName,
CAST(sub.receipt AS DECIMAL(10,2)) totalAmount,
CAST(sub.receipt AS DECIMAL(10,2)) balance,
s.name company,
co.code companyCode,
c.accountingAccount,
c.iban,
c.hasSepaVnl,
c.hasCoreVnl,
c.hasLcr,
be.bic,
be.`name` entityName
FROM client c
JOIN (
SELECT risk.companyFk,
c.id,
SUM(risk.amount) receipt,
IF((c.dueDay + graceDays) MOD 30.001 <= DAY(vDated),
LAST_DAY(vDated - INTERVAL 1 MONTH) + INTERVAL (c.dueDay + graceDays) MOD 30.001 DAY,
LAST_DAY(vDated - INTERVAL 2 MONTH) + INTERVAL (c.dueDay + graceDays) MOD 30.001 DAY
) paymentDate
FROM client c
JOIN payMethod pm ON pm.id = c.payMethodFk
JOIN (
SELECT cr.companyFk, cr.clientFk, cr.amount
FROM client c
JOIN clientRisk cr ON cr.clientFk = c.id
JOIN payMethod pm ON pm.id = c.payMethodFk
WHERE pm.code = 'bankDraft'
UNION ALL
SELECT io.companyFk, io.clientFk, - io.amount
FROM invoiceOut io
JOIN client c ON c.id = io.clientFk
JOIN payMethod pm ON pm.id = c.payMethodFk
WHERE io.dued > vDated
AND pm.code = 'bankDraft'
AND pm.outstandingDebt
AND io.amount > 0
) risk ON risk.clientFk = c.id
GROUP BY risk.companyFk, c.id
HAVING receipt > 10
) sub ON sub.id = c.id
JOIN supplier s ON s.id = sub.companyFk
JOIN company co ON co.id = sub.companyFk
LEFT JOIN bankEntity be ON be.id = c.bankEntityFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `reportLabelCollection_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `reportLabelCollection_get`(
vParam INT,
vLabelCount INT
)
BEGIN
/**
* Obtains tag data from a ticket or collection.
*
* @param vParam Ticket/Collection from which data is to be taken.
* @param vLabelCount number of times the collection has been printed.
*/
DECLARE vIsCollection BOOL;
SELECT IF(id, TRUE, FALSE) INTO vIsCollection
FROM vn.collection c
WHERE id = vParam;
SELECT c.itemPackingTypeFk,
CONCAT(tc.collectionFk, ' ', LEFT(cc.code, 4)) color,
CONCAT(tc.collectionFk, ' ', SUBSTRING('ABCDEFGH',tc.wagon, 1), '-', tc.level) levelV,
tc.ticketFk,
LEFT(COALESCE(et.description, zo.name, am.name),12) agencyDescription,
am.name,
t.clientFk,
CONCAT(CAST(SUM(sv.volume) AS DECIMAL(5, 2)), 'm³') m3 ,
CAST(IF(ic.code = 'plant', CONCAT(MAX(i.size), ' cm'), COUNT(*)) AS CHAR) size,
w.code workerCode,
IF(vLabelCount IS NULL, tt.labelCount, vLabelCount) labelCount,
IF(HOUR(t.shipped), TIME(t.shipped), TIME(zo.hour)) agencyHour,
t.shipped,
COUNT(*) lineCount,
t.nickName
FROM ticket t
JOIN ticketCollection tc ON tc.ticketFk = t.id
JOIN collection c ON c.id = tc.collectionFk
LEFT JOIN collectionColors cc ON cc.shelve = tc.level
AND cc.wagon = tc.wagon
AND cc.trainFk = c.trainFk
JOIN sale s ON s.ticketFk = t.id
LEFT JOIN saleVolume sv ON sv.saleFk = s.id
JOIN item i ON i.id = s.itemFk
JOIN itemType it ON it.id = i.typeFk
JOIN itemCategory ic ON ic.id = it.categoryFk
JOIN worker w ON w.id = c.workerFk
JOIN agencyMode am ON am.id = t.agencyModeFk
LEFT JOIN ticketTrolley tt ON tt.ticket = t.id
LEFT JOIN zone zo ON t.zoneFk = zo.id
LEFT JOIN routesMonitor rm ON rm.routeFk = t.routeFk
LEFT JOIN expeditionTruck et ON et.id = rm.expeditionTruckFk
WHERE IF(vIsCollection, tc.collectionFk = vParam, tc.ticketFk = vParam)
GROUP BY t.id
ORDER BY cc.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `report_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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `report_print`(
vReportName VARCHAR(100),
vPrinterFk INT,
vUserFk INT,
vParams JSON,
vPriorityName VARCHAR(100)
)
BEGIN
/**
* Inserts in the print queue the report to be printed and the necessary parameters for this
* one taking into account the paper size of both the printer and the report.
*
* @param vReportName the report to be printed.
* @param vPrinterFk the printer selected.
* @param vUserFk user id.
* @param vParams JSON with report parameters.
* @param vPriorityName the printing priority.
*/
DECLARE vI INT DEFAULT 0;
DECLARE vKeys TEXT DEFAULT JSON_KEYS(vParams);
DECLARE vLength INT DEFAULT JSON_LENGTH(vKeys);
DECLARE vKey VARCHAR(255);
DECLARE vVal VARCHAR(255);
DECLARE vPrintQueueFk INT;
DECLARE vReportSize VARCHAR(255);
DECLARE vIsThePrinterReal INT;
DECLARE vPrinteSize VARCHAR(255);
DECLARE vPriorityFk INT;
DECLARE vReportFk INT;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
SELECT id, paperSizeFk INTO vReportFk, vReportSize
FROM report
WHERE name = vReportName;
SELECT id, paperSizeFk INTO vIsThePrinterReal, vPrinteSize
FROM printer
WHERE id = vPrinterFk;
SELECT id INTO vPriorityFk
FROM queuePriority
WHERE code = vPriorityName;
IF vIsThePrinterReal IS NULL THEN
CALL util.throw('printerNotExists');
END IF;
IF vReportFk IS NULL THEN
CALL util.throw('reportNotExists');
END IF;
IF vReportSize <> vPrinteSize THEN
CALL util.throw('incorrectSize');
END IF;
START TRANSACTION;
INSERT INTO printQueue
SET printerFk = vPrinterFk,
priorityFk = vPriorityFk,
reportFk = vReportFk,
workerFk = vUserFk;
SET vPrintQueueFk = LAST_INSERT_ID();
WHILE vI < vLength DO
SET vKey = JSON_VALUE(vKeys, CONCAT('$[', vI ,']'));
SET vVal = JSON_VALUE(vParams, CONCAT('$.', vKey));
INSERT INTO printQueueArgs
SET printQueueFk = vPrintQueueFk,
name = vKey,
value = vVal;
SET vI = vI + 1;
END WHILE;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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,util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `routeInfo` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `routeInfo`(vRouteFk INT)
BEGIN
DECLARE vPackages INT;
DECLARE vM3 INT;
DECLARE vKg INT;
DECLARE vMatricula varchar(50);
SELECT sum(packages) as bultos
INTO vPackages
FROM vn.ticket t
WHERE routeFk = vRouteFk;
SELECT SUM(sv.physicalVolume), SUM(sv.physicalWeight)
INTO vM3, vKg
FROM vn.saleVolume sv
WHERE sv.routeFk = vRouteFk;
SELECT v.numberPlate as matricula
INTO vMatricula
FROM vn.route r
JOIN vn.vehicle v ON r.vehicleFk = v.id
WHERE r.id = vRouteFk;
SELECT vRouteFk as Ruta,
vPackages as Bultos,
vM3 as m3,
vKg as Kg,
vMatricula as Matricula;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `routeMonitor_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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `routeMonitor_calculate`(
vDate DATE,
vDaysAgo INT
)
BEGIN
DECLARE vDateEnd DATETIME;
SET vDate = vDate - INTERVAL vDaysAgo DAY;
SET vDateEnd = util.dayend(vDate);
CREATE OR REPLACE TEMPORARY TABLE tmp.routesMonitor
(INDEX (routeFk))
ENGINE = MEMORY
SELECT DISTINCT(t.routeFk) routeFk
FROM vn.ticket t
WHERE t.shipped BETWEEN vDate AND vDateEnd
AND t.routeFk IS NOT NULL;
INSERT IGNORE INTO routesMonitor(routeFk)
SELECT routeFk
FROM tmp.routesMonitor;
UPDATE routesMonitor rm
JOIN route r ON r.id = rm.routeFk
JOIN agencyMode a ON a.id = r.agencyModeFk
SET rm.`name` = a.name,
rm.ticketFree = 0,
rm.ticketProduction = 0,
rm.ticketPacked = 0,
rm.dated = r.created;
UPDATE routesMonitor rm
JOIN (
SELECT t.routeFk, COUNT(*) AS ticketFree
FROM vn.ticket t
JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk
JOIN ticketLastState ts ON t.id = ts.ticketFk
JOIN ticketTracking tt ON tt.id = ts.ticketTrackingFk
JOIN state s ON s.id = tt.stateFk
JOIN vn.alertLevel al ON al.id = s.alertLevel
AND al.code = "FREE"
GROUP BY t.routeFk
) sub ON sub.routeFk = rm.routeFk
SET rm.ticketFree = sub.ticketFree;
UPDATE routesMonitor rm
JOIN(
SELECT t.routeFk, COUNT(*) AS ticketPacked
FROM vn.ticket t
JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk
JOIN ticketLastState ts ON t.id = ts.ticketFk
JOIN ticketTracking tt ON tt.id = ts.ticketTrackingFk
JOIN state s ON s.id = tt.stateFk
JOIN vn.alertLevel al ON al.id = s.alertLevel
AND al.code = "PACKED"
GROUP BY t.routeFk
) sub ON sub.routeFk = rm.routeFk
SET rm.ticketPacked = sub.ticketPacked;
UPDATE routesMonitor rm
JOIN(
SELECT t.routeFk, COUNT(*) AS ticketProduction
FROM vn.ticket t
JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk
JOIN ticketLastState ts ON t.id = ts.ticketFk
JOIN ticketTracking tt ON tt.id = ts.ticketTrackingFk
JOIN state s ON s.id = tt.stateFk
JOIN vn.alertLevel al ON al.id = s.alertLevel
AND al.code = "DELIVERED"
GROUP BY t.routeFk
) sub ON sub.routeFk = rm.routeFk
SET rm.ticketProduction = sub.ticketProduction;
UPDATE routesMonitor rm
JOIN (
SELECT t.routeFk, COUNT(*) packages
FROM vn.ticket t
JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk
JOIN expedition e ON e.ticketFk = t.id
GROUP BY t.routeFk
) sub ON sub.routeFk = rm.routeFk
SET rm.packages = sub.packages;
UPDATE routesMonitor rm
JOIN( SELECT t.routeFk, SUM(sv.volume) m3
FROM vn.ticket t
JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk
JOIN vn.saleVolume sv ON sv.ticketFk = t.id
GROUP BY t.routeFk
) sub ON sub.routeFk = rm.routeFk
SET rm.m3 = sub.m3;
UPDATE routesMonitor rm
JOIN (
SELECT t.routeFk,
SUM(IFNULL(pk.volume,
pk.width * pk.height * pk.`depth`
)
) / 1000000 m3boxes
FROM vn.ticket t
JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk
JOIN vn.expedition e ON e.ticketFk = t.id
JOIN vn.packaging pk ON pk.id = e.packagingFk
GROUP BY t.routeFk
) sub ON sub.routeFk = rm.routeFk
SET rm.m3boxes = sub.m3boxes;
UPDATE routesMonitor rm
JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk
SET rm.etd = et.eta;
DROP TEMPORARY TABLE tmp.routesMonitor;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `routeUpdateM3`(vRoute INT)
BEGIN
/**
* @deprecated Use vn.route_updateM3()
*/
call route_updateM3(vRoute);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `route_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `route_calcCommission`(
vSelf INT
)
BEGIN
/**
* Calcula las comisión para una ruta y guarda los valores
* en la tabla vn.routeCommission.
*
* @param vSelf Id de ruta
*/
DECLARE vIsUpdatable, vIsFreelance BOOL DEFAULT 0;
DECLARE vAgencyModePricePercentage DOUBLE;
SELECT r.created >= rc.cutoffDated INTO vIsUpdatable
FROM route r
JOIN routeConfig rc
WHERE r.id = vSelf;
IF vIsUpdatable THEN
DELETE FROM routeCommission
WHERE routeFk = vSelf;
SELECT w.isFreelance INTO vIsFreelance
FROM route r
JOIN worker w ON w.id = r.workerFk
WHERE r.id = vSelf;
SELECT ampp.percentage INTO vAgencyModePricePercentage
FROM route r
JOIN agencyMode am ON am.id = r.agencyModeFk
JOIN agencyModePricePercentage ampp ON ampp.agencyModeFk = am.id
WHERE r.id = vSelf;
-- Falta calcular el precio, a la espera de saber el/los campo/s exacto/s al que aplicarlo/s
IF vIsFreelance THEN
INSERT INTO routeCommission (
routeFk,
workCenterFk,
freelanceYearlyM3,
cat4m3,
cat5m3
)
SELECT vSelf,
r.commissionWorkCenterFk,
IF(vAgencyModePricePercentage IS NOT NULL,
vAgencyModePricePercentage / 100,
rc.freelanceM3
) *
IF(IFNULL(r.m3, 0) >= rc.freelanceMinM3,
IFNULL(r.m3, 0),
0
),
rc.distributionCat4M3 * IFNULL(r.m3, 0),
rc.distributionCat5M3 * IFNULL(r.m3, 0)
FROM route r
JOIN vehicle v ON v.id = r.vehicleFk
JOIN routeConfig rc
WHERE r.id = vSelf
AND r.workerFk
AND r.commissionWorkCenterFk;
ELSE
INSERT INTO routeCommission (
routeFk,
workCenterFk,
km,
m3,
yearlyKm,
yearlyM3,
cat4m3,
cat5m3
)
SELECT vSelf,
r.commissionWorkCenterFk,
(r.kmEnd - r.kmStart) *
IF(v.isKmTruckRate, rc.kmHeavy, rc.kmLight),
IFNULL(r.m3, 0) *
IF(v.isKmTruckRate, rc.deliveryM3Cat5, rc.deliveryM3Cat4),
(r.kmEnd - r.kmStart) * rc.kmYearly,
IFNULL(r.m3, 0) * rc.m3Yearly,
rc.distributionCat4M3 * IFNULL(r.m3, 0),
rc.distributionCat5M3 * IFNULL(r.m3, 0)
FROM route r
JOIN vehicle v ON v.id = r.vehicleFk
JOIN routeConfig rc
WHERE r.id = vSelf
AND r.kmStart
AND r.kmEnd
AND r.workerFk
AND r.commissionWorkCenterFk;
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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `route_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `route_doRecalc`()
proc: BEGIN
/**
* Recalculates modified route.
*/
DECLARE vDone BOOL;
DECLARE vRouteFk INT;
DECLARE cCur CURSOR FOR
SELECT routeFk FROM routeRecalc;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
DO RELEASE_LOCK('vn.route_doRecalc');
ROLLBACK;
RESIGNAL;
END;
IF !GET_LOCK('vn.route_doRecalc', 0) THEN
LEAVE proc;
END IF;
OPEN cCur;
myLoop: LOOP
SET vDone = FALSE;
FETCH cCur INTO vRouteFk;
IF vDone THEN
LEAVE myLoop;
END IF;
START TRANSACTION;
CALL route_updateM3(vRouteFk);
COMMIT;
DELETE FROM routeRecalc WHERE routeFk = vRouteFk;
END LOOP;
CLOSE cCur;
DO RELEASE_LOCK('vn.route_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `route_getTickets` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `route_getTickets`(vRouteFk INT)
BEGIN
/**
* Pasado un RouteFk devuelve la información
* de sus tickets.
*
* @param vRouteFk
* @select Información de los tickets
*/
SELECT t.id Id,
t.clientFk Client,
a.id Address,
a.nickname ClientName,
t.packages Packages,
a.street AddressName,
a.postalCode PostalCode,
a.city City,
sub3.itemPackingTypeFk PackingType,
c.phone ClientPhone,
c.mobile ClientMobile,
a.phone AddressPhone,
a.mobile AddressMobile,
d.longitude Longitude,
d.latitude Latitude,
wm.mediaValue SalePersonPhone,
tob.description Note,
t.isSigned Signed,
t.priority,
t.cmrFk
FROM ticket t
JOIN client c ON t.clientFk = c.id
JOIN address a ON t.addressFk = a.id
LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk
LEFT JOIN (
SELECT t.addressFk, MAX(d.ticketFk) lastTicketFk
FROM ticket t
JOIN delivery d ON t.id = d.ticketFk
JOIN ticket ti ON ti.routeFk = vRouteFk
AND ti.id = t.id
AND ti.clientFk = t.clientFk
GROUP BY addressFk
)sub ON sub.addressFk = a.id
LEFT JOIN delivery d ON d.ticketFk = sub.lastTicketFk
LEFT JOIN(
SELECT t.id ticketFk, tob.description
FROM ticketObservation tob
JOIN ticket t ON tob.ticketFk = t.id
JOIN observationType ot ON ot.id = tob.observationTypeFk
WHERE t.routeFk = vRouteFk
AND ot.code = 'delivery'
)tob ON tob.ticketFk = t.id
LEFT JOIN(
SELECT sub2.ticketFk,
CONCAT('(',
GROUP_CONCAT(DISTINCT sub2.itemPackingTypeFk
ORDER BY sub2.items DESC SEPARATOR ','),
') ') itemPackingTypeFk
FROM (
SELECT s.ticketFk, i.itemPackingTypeFk, COUNT(*) items
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
WHERE t.routeFk = vRouteFk
GROUP BY t.id, i.itemPackingTypeFk
)sub2
GROUP BY sub2.ticketFk
)sub3 ON sub3.ticketFk = t.id
WHERE t.routeFk = vRouteFk
ORDER BY priority, 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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `route_updateM3` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `route_updateM3`(vRoute INT)
BEGIN
UPDATE vn.route r
LEFT JOIN (
SELECT routeFk, SUM(volume) AS m3
FROM saleVolume
WHERE routeFk = vRoute
) v ON v.routeFk = r.id
SET r.m3 = IFNULL(v.m3,0)
WHERE r.id =vRoute;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `saleBuy_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `saleBuy_Add`(vSaleFk INT, vBuyFk INT)
BEGIN
/* Añade un registro a la tabla saleBuy en el caso de que sea posible mantener la trazabilidad
*
* @param vSaleFk clave primaria de vn.sale
* @param vBuyFk clave primaria de vn.buy
*/
/*IF (SELECT COUNT(*)
FROM vn.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
WHERE s.id = vSaleFk
AND ic.code = 'fruit') THEN */
IF (SELECT COUNT(*) FROM vn.buy WHERE id = vBuyFk AND itemOriginalFk) THEN
INSERT INTO vn.saleBuy (saleFk, buyFk)
VALUES(vSaleFk, vBuyFk);
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `saleGroup_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `saleGroup_add`(vSectorFk INT,vTicketFk INT)
BEGIN
/**
* Añade un nuevo registro a la tabla y devuelve su id.
*
* @param vSectorFk Identificador de vn.sector
*/
INSERT INTO vn.saleGroup
SET `userFk` = account.myUser_getId(),
`sectorFk` = vSectorFk,
`ticketFk` = vTicketFk;
SELECT 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `saleGroup_setParking` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `saleGroup_setParking`(IN `vSaleGroupFk` VARCHAR(8), IN `vParkingFk` INT)
proc: BEGIN
/**
* Aparca una preparación previa en un parking
*
* @param vSaleGroupFk id de la preparación previa
* @param vParkingFk id del parking
*/
UPDATE vn.saleGroup sg
SET sg.parkingFk = vParkingFk
WHERE sg.id = vSaleGroupFk
AND sg.created >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE());
CALL vn.ticket_setNextState(vn.ticket_get(vSaleGroupFk));
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `saleMistake_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `saleMistake_Add`(vSaleFk INT, vUserFk INT, vTypeFk INT)
BEGIN
INSERT INTO vn.saleMistake(saleFk, userFk, typeFk)
VALUES(vSaleFk, vUserFk, vTypeFk);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `salePreparingList`(IN vTicketFk BIGINT)
BEGIN
/**
* Devuelve un listado con las lineas de vn.sale y los distintos estados de prepacion
*
* @param vTicketFk Identificador de vn.ticket
*/
CALL cache.last_buy_refresh(FALSE);
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`,
IF(stPrevious.saleFk,TRUE,FALSE) as isPreviousSelected,
stPrevious.isChecked as isPrevious,
stPrepared.isChecked as isPrepared,
stControled.isChecked as isControled,
ib.code as barcode,
(MAX(sgd.id) IS NOT NULL) AS hasSaleGroupDetail
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 cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = t.warehouseFk
LEFT JOIN vn.buy b ON b.id = lb.buy_id
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
LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
WHERE t.id = vTicketFk
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sales_merge` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sales_merge`(vTicketFk INT)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve
SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity
FROM sale s
JOIN item i ON i.id = s.itemFk
JOIN itemType it ON it.id = i.typeFk
WHERE s.ticketFk = vTicketFk
AND it.isMergeable
GROUP BY s.itemFk, s.price, s.discount;
START TRANSACTION;
UPDATE sale s
JOIN tSalesToPreserve stp ON stp.id = s.id
SET quantity = newQuantity
WHERE s.ticketFk = vTicketFk;
DELETE s.*
FROM sale s
LEFT JOIN tSalesToPreserve stp ON stp.id = s.id
JOIN item i ON i.id = s.itemFk
JOIN itemType it ON it.id = i.typeFk
WHERE s.ticketFk = vTicketFk
AND stp.id IS NULL
AND it.isMergeable;
COMMIT;
DROP TEMPORARY TABLE tSalesToPreserve;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sales_mergeByCollection` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sales_mergeByCollection`(vCollectionFk INT)
BEGIN
DECLARE vDone BOOL;
-- Fetch variables
DECLARE vTicketFk INT;
DECLARE cCur CURSOR FOR
SELECT ticketFk
FROM vn.ticketCollection
WHERE collectionFk = vCollectionFk;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
OPEN cCur;
myLoop: LOOP
SET vDone = FALSE;
FETCH cCur INTO vTicketFk;
IF vDone THEN
LEAVE myLoop;
END IF;
CALL vn.sales_merge(vTicketFk);
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `saleTracking_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_add`(vSaleGroupFk INT)
BEGIN
/** Inserta en vn.saleTracking las lineas de una previa
*
* @param vSaleGroupFk Identificador de vn.saleGroup
*/
REPLACE vn.saleTracking(
saleFk,
isChecked,
workerFk,
stateFk
)
SELECT sgd.saleFk ,
TRUE,
account.myUser_getId(),
s.id
FROM vn.saleGroupDetail sgd
JOIN vn.state s ON s.code = 'ON_PREPARATION'
WHERE sgd.saleGroupFk = vSaleGroupFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `saleTracking_addPreparedSaleGroup` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_addPreparedSaleGroup`(vSaleGroupFk INT)
BEGIN
/**
* Inserta lineas de vn.saleTracking para un saleGroup (previa) que escanea un sacador
*
* @param vSaleGroupFk Identificador de vn.saleGroup
*/
REPLACE vn.saleTracking(saleFk, isChecked, workerFk, stateFk)
SELECT sgd.saleFk, TRUE, account.myUser_getId(), s.id
FROM vn.saleGroupDetail sgd
JOIN vn.state s ON s.code = 'PREPARED'
WHERE sgd.saleGroupFk = vSaleGroupFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `saleTracking_addPrevOK` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_addPrevOK`(vSectorCollectionFk INT)
BEGIN
/**
* Inserta los registros de la colección de sector con el estado PREVIA OK
*
* @param vSectorCollectionFk Identificador de vn.sectorCollection
*/
REPLACE vn.saleTracking(
saleFk,
isChecked,
workerFk,
stateFk
)
SELECT sgd.saleFk,
TRUE,
sc.userFk,
s.id
FROM vn.sectorCollection sc
JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id
JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk
JOIN vn.state s ON s.code = 'OK PREVIOUS'
WHERE sc.id = vSectorCollectionFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_new`(
vSaleFK INT,
vIsChecked BOOLEAN,
vOriginalQuantity INT,
vWorkerFk INT,
vAction VARCHAR(50),
vState VARCHAR(50),
vIsScanned BOOLEAN)
BEGIN
/**
* Modifica registro de saleTracking
*
* @param vSaleFK Identificador del registro a modificar
* @param vIsChecked Indica si la línea ha sido pulsada
* @param vOriginalQuantity Cantidad original
* @param vWorkerFk Identificador del trabajador
* @param vAction Identificador de la acción realizada
* @param vState Identificador del estado a modificar
* @param vIsScanned Identificador si se ha escaneado automáticamente o manual
*/
REPLACE vn.saleTracking(saleFk,
isChecked,
originalQuantity,
workerFk,
stateFk,
isScanned)
SELECT vSaleFK,
vIsChecked,
vOriginalQuantity,
IFNULL(vWorkerFk, vn.getUser()),
s.id,
vIsScanned
FROM vn.state s
WHERE 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `saleTracking_updateIsChecked` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_updateIsChecked`(vSaleFK INT, vIsChecked BOOL, vIsScanned BOOL)
BEGIN
/**
* Actualiza el estado del campo vn.saleTracking.isChecked y elimina las lineas de vn.itemShelving
* si procede, en el caso de las preparaciones previas, por usuario
*
* @param vSaleFk Identificador de vn.sale
* @param vIsChecked Estado del registro
*/
UPDATE vn.saleTracking st
JOIN vn.state s ON s.id = st.stateFk AND s.code = 'PREVIOUS_PREPARATION'
SET st.isChecked = vIsChecked,
st.isScanned = vIsScanned
WHERE st.saleFk = vSaleFK
AND st.workerFk = account.myUser_getId();
IF vIsChecked = FALSE THEN
DELETE FROM vn.itemShelvingSale
WHERE saleFk = vSaleFK;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sale_boxPickingPrint` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_boxPickingPrint`(
IN vPrinterFk INT,
IN vSaleFk INT,
IN vPacking INT,
IN vSectorFk INT,
IN vUserFk INT,
IN vPackagingFk VARCHAR(10),
IN vPackingSiteFk INT)
BEGIN
/** Splits a line of sale to a different ticket and prints the transport sticker
*/
DECLARE vAgencyModeFk INT;
DECLARE vConcept VARCHAR(30);
DECLARE vExpeditionFk INT;
DECLARE vItemFk INT;
DECLARE vItemShelvingFk INT;
DECLARE vItemShelvingSaleFk INT;
DECLARE vItemShelvingSaleFk_old INT;
DECLARE vLastExpeditionTimeStamp DATETIME;
DECLARE vMaxPhoneLength INT DEFAULT 11;
DECLARE vMaxStreetLength INT DEFAULT 36;
DECLARE vNewSaleFk INT;
DECLARE vNewTicketFk INT;
DECLARE vParkingCode VARCHAR(10);
DECLARE vQuantity INT;
DECLARE vRemainder INT DEFAULT 0;
DECLARE vRemainderSaleFk INT;
DECLARE vShelving VARCHAR(10);
DECLARE vTicketFk INT;
SELECT s.quantity,
s.quantity MOD vPacking,
s.ticketFk,
s.itemFk,
s.concept
INTO vQuantity,
vRemainder,
vTicketFk,
vItemFk,
vConcept
FROM sale s
WHERE s.id = vSaleFk;
IF vRemainder THEN
UPDATE sale SET quantity = quantity - vRemainder WHERE id = vSaleFk;
INSERT INTO sale(ticketFk, itemFk, quantity, price, discount, concept)
SELECT ticketFk, itemFk, vRemainder, price, discount, concept
FROM sale
WHERE id = vSaleFk;
SET vRemainderSaleFk = LAST_INSERT_ID();
INSERT INTO saleComponent(saleFk, componentFk, value)
SELECT vRemainderSaleFk, componentFk, value
FROM saleComponent
WHERE saleFk = vSaleFk;
END IF;
w1: WHILE vQuantity >= vPacking DO
SET vQuantity = vQuantity - vPacking;
SET vItemShelvingFk = NULL;
SELECT sub.id
INTO vItemShelvingFk
FROM productionConfig pc
JOIN (
SELECT ish.id,
ish.visible - IFNULL(SUM(iss.quantity),0) available,
p.pickingOrder,
ish.created
FROM itemShelving ish
JOIN shelving sh ON sh.code = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
LEFT JOIN itemShelvingSale iss
ON iss.itemShelvingFk = ish.id
AND iss.created >= CURDATE()
AND iss.isPicked = FALSE
WHERE ish.itemFk = vItemFk
AND p.sectorFk = vSectorFk
GROUP BY ish.id
HAVING available >= vPacking) sub
ORDER BY IF(pc.orderMode = 'Location',sub.pickingOrder, sub.created)
LIMIT 1;
IF vItemShelvingFk THEN
INSERT INTO itemShelvingSale
SET itemShelvingFk = vItemShelvingFk,
saleFk = vSaleFk,
quantity = vPacking,
userFk = vUserFk,
isPicked = TRUE;
SET vItemShelvingSaleFk = LAST_INSERT_ID();
UPDATE sale SET isPicked = FALSE WHERE id = vSaleFk;
ELSE
LEAVE w1;
END IF;
SET vNewTicketFk = NULL;
SELECT MAX(t.id) INTO vNewTicketFk
FROM ticket t
JOIN ticketLastState tls ON tls.ticketFk = t.id
JOIN (SELECT addressFk, clientFk, date(shipped) shipped, warehouseFk
FROM ticket
WHERE id = vTicketFk) tt
ON tt.addressFk = t.addressFk
AND tt.clientFk = t.clientFk
AND t.shipped BETWEEN tt.shipped AND util.dayend(tt.shipped)
AND t.warehouseFk = tt.warehouseFk
WHERE tls.name = 'Encajado' ;
IF ISNULL(vNewTicketFk) THEN
INSERT INTO ticket( clientFk,
shipped,
addressFk,
agencyModeFk,
nickname,
warehouseFk,
companyFk,
landed,
zoneFk,
zonePrice,
zoneBonus,
routeFk,
priority,
hasPriority,
clonedFrom)
SELECT clientFk,
shipped,
addressFk,
agencyModeFk,
nickname,
warehouseFk,
companyFk,
landed,
zoneFk,
zonePrice,
zoneBonus,
routeFk,
priority,
hasPriority,
id
FROM ticket
WHERE id = vTicketFk;
SET vNewTicketFk = LAST_INSERT_ID();
INSERT INTO ticketTracking(ticketFk, stateFk, userFk)
SELECT vNewTicketFk, id, vUserFk
FROM state
WHERE code = 'PACKED';
END IF;
UPDATE sale SET quantity = quantity - vPacking WHERE id = vSaleFk;
UPDATE itemShelving SET visible = visible - vPacking WHERE id = vItemShelvingFk;
SET vNewSaleFk = NULL;
SELECT MAX(id) INTO vNewSaleFk
FROM sale
WHERE ticketFk = vNewTicketFk
AND itemFk = vItemFk;
IF vNewSaleFk THEN
UPDATE sale
SET quantity = quantity + vPacking
WHERE id = vNewSaleFk;
SET vItemShelvingSaleFk_old = NULL;
SELECT MAX(id) INTO vItemShelvingSaleFk_old
FROM itemShelvingSale
WHERE itemShelvingFk = vItemShelvingFk
AND saleFk = vNewSaleFk;
IF vItemShelvingSaleFk_old THEN
UPDATE itemShelvingSale
SET quantity = quantity + vPacking
WHERE id = vItemShelvingSaleFk_old;
DELETE FROM itemShelvingSale
WHERE id = vItemShelvingSaleFk;
SET vItemShelvingSaleFk = vItemShelvingSaleFk_old;
ELSE
UPDATE itemShelvingSale
SET saleFk = vNewSaleFk
WHERE id = vItemShelvingSaleFk;
END IF;
ELSE
INSERT INTO sale(ticketFk, itemFk, concept, quantity, discount, price)
SELECT vNewTicketFk, itemFk, concept, vPacking, discount, price
FROM sale
WHERE id = vSaleFk;
SET vNewSaleFk = LAST_INSERT_ID();
INSERT INTO saleComponent(saleFk, componentFk, value, isGreuge)
SELECT vNewSaleFk, componentFk, value, isGreuge
FROM saleComponent
WHERE saleFk = vSaleFk;
UPDATE itemShelvingSale
SET saleFk = vNewSaleFk
WHERE id = vItemShelvingSaleFk;
END IF;
INSERT IGNORE INTO saleTracking(saleFk, isChecked, workerFk, stateFk)
SELECT vNewSaleFk, TRUE, vUserFk, id
FROM state
WHERE code = 'PREPARED';
SELECT agencyModeFk INTO vAgencyModeFk
FROM ticket
WHERE id = vNewTicketFk;
INSERT INTO expedition(
agencyModeFk,
ticketFk,
freightItemFk,
workerFk,
packagingFk,
itemPackingTypeFk,
hostFk,
packingSiteFk,
monitorId,
started,
ended
)
SELECT vAgencyModeFk,
vNewTicketFk,
pc.defaultFreightItemFk,
vUserFk,
vPackagingFk,
ps.code,
h.code,
vPackingSiteFk,
ps.monitorId,
IFNULL(vLastExpeditionTimeStamp, NOW()),
NOW()
FROM packingSite ps
JOIN host h ON h.id = ps.hostFk
JOIN productionConfig pc
WHERE ps.id = vPackingSiteFk;
SET vExpeditionFk = LAST_INSERT_ID();
SET vLastExpeditionTimeStamp = NOW();
CALL dipole.expedition_Add(vExpeditionFk,vPrinterFk, TRUE);
SELECT shelvingFk, p.code
INTO vShelving, vParkingCode
FROM itemShelving ish
JOIN shelving sh ON sh.code = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
WHERE ish.id = vItemShelvingFk;
UPDATE dipole.expedition_PrintOut
SET isPrinted = FALSE,
itemFk = vItemFk,
quantity = vPacking,
longName = vConcept,
shelvingFk = vShelving,
parkingCode = vParkingCode,
phone = RIGHT(phone,vMaxPhoneLength),
street = RIGHT(street, vMAxStreetLength)
WHERE expeditionFk = vExpeditionFk;
DELETE FROM sale
WHERE quantity = 0
AND id = vSaleFk;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_calculateComponent`(vSelf INT, vOption VARCHAR(25))
proc: BEGIN
/**
* Crea tabla temporal para vn.sale_recalcComponent() para recalcular los componentes
*
* @param vSelf Id de la venta
* @param vOption indica en que componente pone el descuadre, NULL en casos habituales
*/
CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales
SELECT s.id
FROM sale s
WHERE s.id = vSelf;
CALL sale_recalcComponent(vOption);
DROP TEMPORARY TABLE tmp.recalculateSales;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sale_getBoxPickingList` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_getBoxPickingList`(vSectorFk INT, vDated DATE)
BEGIN
/**
* Returns a suitable boxPicking sales list
*
* @param vSectorFk Identifier for vn.sector table
* @param vDated Date for vn.tickets.shipping
*
* @return tmp.sale
*/
DECLARE vWarehouseFk INT;
SELECT warehouseFk INTO vWarehouseFk
FROM sector
WHERE id = vSectorFk;
CALL productionControl(vWarehouseFk, 0);
CREATE OR REPLACE TEMPORARY TABLE tmp.sale
(saleFk INT PRIMARY KEY)
SELECT
s.ticketFk,
s.id saleFk,
s.itemFk,
s.concept,
s.quantity,
MAKETIME(pb.HH,pb.mm,0) etd,
pb.routeFk,
FLOOR(s.quantity / IF(i.isBoxPickingMode, ish.packing, i.packingOut)) stickers,
IF(i.isBoxPickingMode, ish.packing, i.packingOut) packing,
b.packagingFk
FROM sale s
JOIN item i ON i.id = s.itemFk
JOIN itemShelving ish ON ish.itemFk = s.itemFk
LEFT JOIN ( SELECT iss.itemShelvingFk,
s.itemFk,
SUM(iss.quantity) reserve
FROM itemShelvingSale iss
JOIN sale s ON s.id = iss.saleFk
WHERE iss.isPicked = FALSE
AND iss.created >= vDated
GROUP BY iss.itemShelvingFk, s.itemFk) tISS
ON tISS.itemFk = ish.itemFk AND tISS.itemShelvingFk = ish.id
JOIN shelving sh ON sh.code = ish.shelvingFk
JOIN parking p ON p.id = sh.parkingFk
JOIN tmp.productionBuffer pb ON pb.ticketFk = s.ticketFk
JOIN agencyMode am ON am.id = pb.agencyModeFk
JOIN agency a ON a .id = am.agencyFk
LEFT JOIN routesMonitor rm ON rm.routeFk = pb.routeFk
LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
LEFT JOIN ticketState ts ON ts.ticketFk = s.ticketFk
LEFT JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = vWarehouseFk
LEFT JOIN buy b ON b.id = lb.buy_id
WHERE IF(i.isBoxPickingMode, ish.packing, i.packingOut)
<= LEAST(s.quantity, ish.visible - IFNULL(tISS.reserve,0))
AND NOT pb.problem
AND sgd.saleFk IS NULL
AND p.sectorFk = vSectorFk
AND ts.isPreviousPreparable
AND ((rm.bufferFk AND rm.isPickingAllowed)
OR am.code = 'REC_ALG')
AND pb.shipped = vDated
AND a.isOwn
GROUP BY s.id
ORDER BY etd;
SELECT *
FROM tmp.sale
WHERE stickers;
DROP TEMPORARY TABLE tmp.productionBuffer;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sale_getFromTicketOrCollection` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_getFromTicketOrCollection`(vParam INT)
BEGIN
/**
* Visualizar lineas de la tabla sale a través del parámetro vParam que puede
* ser ticket o collection.
*
* @param vParam Identificador de ticket o collection
*/
DECLARE vIsCollection BOOL;
SELECT COUNT(*) INTO vIsCollection
FROM collection c
WHERE c.id = vParam;
DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
DROP TEMPORARY TABLE IF EXISTS tmp.ticket2;
IF vIsCollection THEN
CREATE TEMPORARY TABLE tmp.ticket
(INDEX (id))
ENGINE = MEMORY
SELECT tc.ticketFk id
FROM ticketCollection tc
JOIN ticket t ON t.id = tc.ticketFk
WHERE tc.collectionFk = vParam;
CREATE TEMPORARY TABLE tmp.ticket2
(INDEX (id))
ENGINE = MEMORY
SELECT tc.ticketFk id
FROM ticketCollection tc
JOIN ticket t ON t.id = tc.ticketFk
WHERE tc.collectionFk = vParam;
ELSE
CREATE TEMPORARY TABLE tmp.ticket
(INDEX (id))
ENGINE = MEMORY
SELECT vParam id;
CREATE TEMPORARY TABLE tmp.ticket2
(INDEX (id))
ENGINE = MEMORY
SELECT vParam id;
END IF;
SELECT s.ticketFk,
sgd.saleGroupFk,
s.id saleFk,
s.itemFk,
s.quantity,
i.longName,
i.size,
s.reserved,
MAX(IF(st.semaphore <=> 1, TRUE, FALSE)) isPreviousPrepared,
MAX(IF(st.semaphore <=> 2, TRUE, FALSE)) isPrepared,
MAX(IF(st.semaphore <=> 3, TRUE, FALSE)) isControlled,
MAX(IF(st.semaphore <=> 4, TRUE, FALSE)) isPreControlled,
ic.color,
ip.productor,
s.discount,
s.price,
i.stems,
i.category,
o.code origin,
tt.clientFk,
s.originalQuantity,
TRIM(CONCAT(LPAD(s.concept,30,' '), ' ',
RPAD(IFNULL(i.size,''),5,' '))) line1,
'' cel1,
TRIM(CONCAT(LPAD(IFNULL(ip.productor,''),30,' '), ' ',LPAD(IFNULL(o.code,''),4,' '))) line2,
IF(s.quantity MOD IFNULL(b.packing,s.quantity + 1),
CONCAT(CAST(s.quantity/IFNULL(b.`grouping`,1) AS DECIMAL(10,0)),' x ',IFNULL(b.`grouping`,1)),
CONCAT(CAST(s.quantity / IFNULL(b.packing,1) AS DECIMAL(10,0)),' pack de ',IFNULL(b.packing,1))) cel2,
TRIM(CONCAT(ic.color)) line3,
p.code cel3,
s.isAdded,
IF(c.workerFk IS NULL, getUser(), c.workerFk) workerFk,
IF(SUM(iss.quantity) IS NULL, 0, SUM(iss.quantity)) pickedQuantity,
MIN(iss.created) picked,
IF(sm.id, TRUE, FALSE) hasMistake,
sg.sectorFk,
b.packing,
b.grouping,
o.code
FROM tmp.ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN ticket tt ON tt.id = t.id
LEFT JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = tt.warehouseFk
LEFT JOIN buy b ON b.id = lb.buy_id
JOIN item i ON i.id = s.itemFk
LEFT JOIN ticketCollection tc ON tc.ticketFk = t.id
LEFT JOIN collection c ON c.id = tc.collectionFk
LEFT JOIN (SELECT sub.saleFk, sub.isChecked, sub.stateFk, sub.originalQuantity
FROM (SELECT DISTINCT st.id, st.saleFk, st.isChecked, st.stateFk, st.originalQuantity
FROM tmp.ticket2 t
JOIN sale s ON s.ticketFk = t.id
JOIN saleTracking st ON st.saleFk = s.id
ORDER BY st.id DESC
LIMIT 10000000000000000000) sub
GROUP BY sub.saleFk, sub.stateFK) sub2 ON sub2.saleFk = s.id AND sub2.isChecked = 1
LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id
LEFT JOIN state st ON st.id = sub2.stateFk
LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk
LEFT JOIN itemProductor ip ON ip.itemFk = s.itemFk
LEFT JOIN origin o ON o.id = i.originFk
LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk
LEFT JOIN parking p ON p.id = sg.parkingFk
LEFT JOIN saleMistake sm ON sm.saleFk = s.id
GROUP BY s.id;
DROP TEMPORARY TABLE
tmp.ticket,
tmp.ticket2;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sale_getProblems` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_getProblems`(IN vIsTodayRelative tinyint(1))
BEGIN
/**
* Calcula los problemas de cada venta para un conjunto de tickets.
*
* @param vIsTodayRelative Indica si se calcula el disponible como si todo saliera hoy
* @table tmp.sale_getProblems(ticketFk, clientFk, warehouseFk, shipped) Identificadores de los tickets a calcular
* @return tmp.sale_problems
*/
DECLARE vWarehouseFk INT;
DECLARE vDate DATE;
DECLARE vAvailableCache INT;
DECLARE vVisibleCache INT;
DECLARE vDone BOOL;
DECLARE vComponentCount INT;
DECLARE vCursor CURSOR FOR
SELECT DISTINCT tt.warehouseFk, IF(vIsTodayRelative, util.VN_CURDATE(), DATE(tt.shipped))
FROM tmp.sale_getProblems tt
WHERE DATE(tt.shipped) BETWEEN util.VN_CURDATE()
AND util.VN_CURDATE() + INTERVAL IF(vIsTodayRelative, 9.9, 1.9) DAY;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DELETE tt.*
FROM tmp.sale_getProblems tt
JOIN ticketObservation tto ON tto.ticketFk = tt.ticketFk
JOIN observationType ot ON ot.id = tto.observationTypeFk
WHERE ot.code = 'administrative'
AND tto.description = 'Miriam';
CREATE OR REPLACE TEMPORARY TABLE tmp.sale_problems (
ticketFk INT(11),
saleFk INT(11),
isFreezed INTEGER(1) DEFAULT 0,
risk DECIMAL(10,2) DEFAULT 0,
hasHighRisk TINYINT(1) DEFAULT 0,
hasTicketRequest INTEGER(1) DEFAULT 0,
itemShortage VARCHAR(255),
isTaxDataChecked INTEGER(1) DEFAULT 1,
itemDelay VARCHAR(255),
itemLost VARCHAR(255),
hasComponentLack INTEGER(1),
hasRounding VARCHAR(255),
isTooLittle BOOL DEFAULT FALSE,
PRIMARY KEY (ticketFk, saleFk)
) ENGINE = MEMORY;
CREATE OR REPLACE TEMPORARY TABLE tmp.ticket_list
(PRIMARY KEY (ticketFk))
ENGINE = MEMORY
SELECT ticketFk, clientFk
FROM tmp.sale_getProblems;
SELECT COUNT(*) INTO vComponentCount
FROM component
WHERE isRequired;
-- Too Little
INSERT INTO tmp.sale_problems(ticketFk, isTooLittle)
SELECT tp.ticketFk, TRUE
FROM tmp.sale_getProblems tp
JOIN ticket t ON t.id = tp.ticketFk
JOIN (
SELECT t.addressFk, SUM(sv.litros) litros, t.totalWithoutVat
FROM tmp.ticket_list tl
JOIN saleVolume sv ON sv.ticketFk = tl.ticketFk
JOIN ticket t ON t.id = tl.ticketFk
JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk
AND zc.dated = util.VN_CURDATE()
JOIN agencyMode am ON am.id = t.agencyModeFk
JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
WHERE util.VN_NOW() < (util.VN_CURDATE() + INTERVAL HOUR(zc.`hour`) HOUR) + INTERVAL MINUTE(zc.`hour`) MINUTE
AND dm.code IN ('AGENCY','DELIVERY','PICKUP')
AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight()
GROUP BY t.addressFk
) sub ON sub.addressFk = t.addressFk
JOIN volumeConfig vc
WHERE sub.litros < vc.minTicketVolume
AND sub.totalWithoutVat < vc.minTicketValue;
-- Faltan componentes
INSERT INTO tmp.sale_problems(ticketFk, hasComponentLack, saleFk)
SELECT ticketFk, (vComponentCount > nComp) hasComponentLack, saleFk
FROM (
SELECT COUNT(s.id) nComp, tl.ticketFk, s.id saleFk
FROM tmp.ticket_list tl
JOIN vn.sale s ON s.ticketFk = tl.ticketFk
LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id
LEFT JOIN vn.component c ON c.id = sc.componentFk AND c.isRequired
JOIN vn.ticket t ON t.id = tl.ticketFk
JOIN vn.agencyMode am ON am.id = t.agencyModeFk
JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk
WHERE dm.code IN ('AGENCY','DELIVERY','PICKUP')
AND s.quantity > 0
GROUP BY s.id
) sub
HAVING hasComponentLack;
-- Cliente congelado
INSERT INTO tmp.sale_problems(ticketFk, isFreezed)
SELECT DISTINCT tl.ticketFk, TRUE
FROM tmp.ticket_list tl
JOIN client c ON c.id = tl.clientFk
WHERE c.isFreezed
ON DUPLICATE KEY UPDATE isFreezed = c.isFreezed;
-- Credit exceeded
CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt
(PRIMARY KEY (clientFk))
ENGINE = MEMORY
SELECT DISTINCT clientFk
FROM tmp.ticket_list;
CALL client_getDebt(util.VN_CURDATE());
INSERT INTO tmp.sale_problems(ticketFk, risk, hasHighRisk)
SELECT DISTINCT tl.ticketFk, r.risk, ((r.risk - cc.riskTolerance) > c.credit + 10)
FROM tmp.ticket_list tl
JOIN ticket t ON t.id = tl.ticketFk
JOIN agencyMode a ON t.agencyModeFk = a.id
JOIN tmp.risk r ON r.clientFk = t.clientFk
JOIN client c ON c.id = t.clientFk
JOIN clientConfig cc
WHERE r.risk > c.credit + 10
AND NOT a.isRiskFree
ON DUPLICATE KEY UPDATE
risk = r.risk, hasHighRisk = ((r.risk - cc.riskTolerance) > c.credit + 10);
-- Antiguo COD 100, son peticiones de compra sin terminar
INSERT INTO tmp.sale_problems(ticketFk, hasTicketRequest)
SELECT DISTINCT tl.ticketFk, TRUE
FROM tmp.ticket_list tl
JOIN ticketRequest tr ON tr.ticketFk = tl.ticketFk
WHERE tr.isOK IS NULL
ON DUPLICATE KEY UPDATE hasTicketRequest = TRUE;
CREATE OR REPLACE TEMPORARY TABLE tItemShelvingStock_byWarehouse
(INDEX (itemFk, warehouseFk))
ENGINE = MEMORY
SELECT ish.itemFk itemFk,
SUM(ish.visible) visible,
s.warehouseFk warehouseFk
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
GROUP BY ish.itemFk,
s.warehouseFk;
-- Disponible, Faltas, Inventario y Retrasos
OPEN vCursor;
l: LOOP
SET vDone = FALSE;
FETCH vCursor INTO vWarehouseFk, vDate;
IF vDone THEN
LEAVE l;
END IF;
-- Disponible: no va a haber suficiente producto para preparar todos los pedidos
CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouseFk, vDate);
-- Faltas: visible, disponible y ubicado son menores que la cantidad vendida
CALL cache.visible_refresh(vVisibleCache, FALSE, vWarehouseFk);
INSERT INTO tmp.sale_problems(ticketFk, itemShortage, saleFk)
SELECT ticketFk, problem, saleFk
FROM (
SELECT tl.ticketFk,
LEFT(CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')),250) problem,
s.id AS saleFk
FROM tmp.ticket_list tl
JOIN ticket t ON t.id = tl.ticketFk
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
JOIN itemType it on it.id = i.typeFk
JOIN itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN cache.visible v ON v.item_id = i.id
AND v.calc_id = vVisibleCache
LEFT JOIN cache.available av ON av.item_id = i.id
AND av.calc_id = vAvailableCache
LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
AND issw.warehouseFk = t.warehouseFk
WHERE IFNULL(v.visible,0) < s.quantity
AND IFNULL(av.available ,0) < s.quantity
AND IFNULL(issw.visible, 0) < s.quantity
AND NOT s.isPicked
AND NOT s.reserved
AND ic.merchandise
AND IF(vIsTodayRelative, TRUE, DATE(t.shipped) = vDate)
AND NOT i.generic
AND util.VN_CURDATE() = vDate
AND t.warehouseFk = vWarehouseFk
GROUP BY tl.ticketFk) sub
ON DUPLICATE KEY UPDATE itemShortage = sub.problem, saleFk = sub.saleFk;
-- Inventario: Visible suficiente, pero ubicado menor a la cantidad vendida
INSERT INTO tmp.sale_problems(ticketFk, itemLost, saleFk)
SELECT ticketFk, problem, saleFk
FROM (
SELECT tl.ticketFk,
LEFT(GROUP_CONCAT('I: ', i.id, ' ', i.longName, ' '), 250) problem,
s.id saleFk
FROM tmp.ticket_list tl
JOIN ticket t ON t.id = tl.ticketFk
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
JOIN itemType it on it.id = i.typeFk
JOIN itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN cache.visible v ON v.item_id = s.itemFk
AND v.calc_id = vVisibleCache
LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
AND issw.warehouseFk = t.warehouseFk
WHERE IFNULL(v.visible,0) >= s.quantity
AND IFNULL(issw.visible, 0) < s.quantity
AND s.quantity > 0
AND NOT s.isPicked
AND NOT s.reserved
AND ic.merchandise
AND IF(vIsTodayRelative, TRUE, DATE(t.shipped) = vDate)
AND NOT i.generic
AND util.VN_CURDATE() = vDate
AND t.warehouseFk = vWarehouseFk
GROUP BY tl.ticketFk
) sub
ON DUPLICATE KEY UPDATE itemDelay = sub.problem, saleFk = sub.saleFk;
-- Retraso: Disponible suficiente, pero no visible ni ubicado
INSERT INTO tmp.sale_problems(ticketFk, itemDelay, saleFk)
SELECT ticketFk, problem, saleFk
FROM (
SELECT tl.ticketFk,
LEFT(GROUP_CONCAT('R: ', i.id, ' ', i.longName, ' '), 250) problem,
s.id saleFk
FROM tmp.ticket_list tl
JOIN ticket t ON t.id = tl.ticketFk
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
JOIN itemType it on it.id = i.typeFk
JOIN itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN cache.visible v ON v.item_id = s.itemFk
AND v.calc_id = vVisibleCache
LEFT JOIN cache.available av ON av.item_id = i.id
AND av.calc_id = vAvailableCache
LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
AND issw.warehouseFk = t.warehouseFk
WHERE IFNULL(v.visible, 0) < s.quantity
AND IFNULL(av.available, 0) >= s.quantity
AND IFNULL(issw.visible, 0) < s.quantity
AND s.quantity > 0
AND NOT s.isPicked
AND NOT s.reserved
AND ic.merchandise
AND IF(vIsTodayRelative, TRUE, DATE(t.shipped) = vDate)
AND NOT i.generic
AND util.VN_CURDATE() = vDate
AND t.warehouseFk = vWarehouseFk
GROUP BY tl.ticketFk
) sub
ON DUPLICATE KEY UPDATE itemDelay = sub.problem, saleFk = sub.saleFk;
-- Redondeo: Cantidad pedida incorrecta en al grouping de la última compra
CALL buyUltimate(vWarehouseFk, vDate);
INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk)
SELECT ticketFk, problem, saleFk
FROM (
SELECT tl.ticketFk,
s.id saleFk ,
LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem,
MOD(s.quantity, b.`grouping`) hasRounding
FROM tmp.ticket_list tl
JOIN ticket t ON t.id = tl.ticketFk
AND t.warehouseFk = vWarehouseFk
JOIN sale s ON s.ticketFk = tl.ticketFk
JOIN item i ON i.id = s.itemFk
JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
JOIN buy b ON b.id = bu.buyFk
GROUP BY tl.ticketFk
HAVING hasRounding
) sub
ON DUPLICATE KEY UPDATE hasRounding = sub.problem, saleFk = sub.saleFk;
END LOOP;
CLOSE vCursor;
INSERT INTO tmp.sale_problems(ticketFk, isTaxDataChecked)
SELECT DISTINCT tl.ticketFk, FALSE
FROM tmp.ticket_list tl
JOIN client c ON c.id = tl.clientFk
WHERE NOT c.isTaxDataChecked
ON DUPLICATE KEY UPDATE isTaxDataChecked = FALSE;
DROP TEMPORARY TABLE
tmp.clientGetDebt,
tmp.ticket_list,
tItemShelvingStock_byWarehouse;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sale_getProblemsByTicket` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_getProblemsByTicket`(IN vTicketFk INT, IN vIsTodayRelative TINYINT(1))
BEGIN
/**
* Calcula los problemas de cada venta
* para un conjunto de tickets.
*
* @return Problems result
*/
DROP TEMPORARY TABLE IF EXISTS tmp.sale_getProblems;
CREATE TEMPORARY TABLE tmp.sale_getProblems
(INDEX (ticketFk))
ENGINE = MEMORY
SELECT t.id ticketFk, t.clientFk, t.warehouseFk, t.shipped
FROM ticket t
WHERE t.id = vTicketFk;
CALL sale_getProblems(vIsTodayRelative);
SELECT * FROM tmp.sale_problems;
DROP TEMPORARY TABLE
tmp.sale_getProblems,
tmp.sale_problems;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sale_PriceFix` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_PriceFix`(vTicketFk INT)
BEGIN
DELETE sc.*
FROM vn.saleComponent sc
JOIN vn.sale s ON s.id = sc.saleFk
JOIN vn.component c ON c.id = sc.componentFk
JOIN vn.componentType ct ON ct.id = c.typeFk
WHERE s.ticketFk = vTicketFk
AND ct.`type` = 'otros';
UPDATE vn.sale s
JOIN (
SELECT sc.saleFk, sum(sc.value ) price
FROM vn.saleComponent sc
JOIN vn.sale s ON s.id = sc.saleFk
WHERE s.ticketFk = vTicketFk
GROUP BY sc.saleFk) sub ON sub.saleFk = s.id
SET s.price = sub.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sale_recalcComponent` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_recalcComponent`(vOption VARCHAR(25))
proc: BEGIN
/**
* Este procedimiento recalcula los componentes de un conjunto de sales,
* eliminando los componentes existentes e insertandolos de nuevo
*
* @param vOption si no se quiere forzar llamar con NULL
* @table tmp.recalculateSales (id)
*/
DECLARE vShipped DATE;
DECLARE vWarehouseFk SMALLINT;
DECLARE vAgencyModeFk INT;
DECLARE vAddressFk INT;
DECLARE vTicketFk INT;
DECLARE vLanded DATE;
DECLARE vIsEditable BOOLEAN;
DECLARE vZoneFk INTEGER;
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vCur CURSOR FOR
SELECT DISTINCT s.ticketFk
FROM tmp.recalculateSales rs
JOIN vn.sale s ON s.id = rs.id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN vCur;
l: LOOP
SET vDone = FALSE;
FETCH vCur INTO vTicketFk;
IF vDone THEN
LEAVE l;
END IF;
SELECT (hasToRecalcPrice OR ts.alertLevel IS NULL) AND t.refFk IS NULL,
t.zoneFk,
t.warehouseFk,
t.shipped,
t.addressFk,
t.agencyModeFk,
t.landed
INTO vIsEditable,
vZoneFk,
vWarehouseFk,
vShipped,
vAddressFk,
vAgencyModeFk,
vLanded
FROM ticket t
LEFT JOIN ticketState ts ON t.id = ts.ticketFk
LEFT JOIN alertLevel al ON al.id = ts.alertLevel
WHERE t.id = vTicketFk;
CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk, TRUE);
IF NOT EXISTS (SELECT TRUE FROM tmp.zoneGetLanded LIMIT 1) THEN
CALL util.throw(CONCAT('There is no zone for these parameters ', vTicketFk));
END IF;
IF vLanded IS NULL OR vZoneFk IS NULL THEN
UPDATE ticket t
SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1)
WHERE t.id = vTicketFk AND t.landed IS NULL;
IF vZoneFk IS NULL THEN
SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1;
UPDATE ticket t
SET t.zoneFk = vZoneFk
WHERE t.id = vTicketFk AND t.zoneFk IS NULL;
END IF;
END IF;
DROP TEMPORARY TABLE tmp.zoneGetLanded;
-- rellena la tabla buyUltimate con la ultima compra
CALL buyUltimate (vWarehouseFk, vShipped);
CREATE OR REPLACE TEMPORARY TABLE tmp.sale
(PRIMARY KEY (saleFk)) ENGINE = MEMORY
SELECT s.id saleFk, vWarehouseFk warehouseFk
FROM sale s
JOIN tmp.recalculateSales rs ON s.id = rs.id
WHERE s.ticketFk = vTicketFk;
CREATE OR REPLACE TEMPORARY TABLE tmp.ticketLot
SELECT vWarehouseFk warehouseFk, NULL available, s.itemFk, bu.buyFk, vZoneFk zoneFk
FROM sale s
JOIN tmp.recalculateSales rs ON s.id = rs.id
LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
WHERE s.ticketFk = vTicketFk
GROUP BY s.itemFk;
CALL catalog_componentPrepare();
CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk);
IF vOption IS NULL THEN
SET vOption = IF(vIsEditable, 'renewPrices', 'imbalance');
END IF;
CALL ticketComponentUpdateSale(vOption);
CALL catalog_componentPurge();
DROP TEMPORARY TABLE tmp.buyUltimate;
DROP TEMPORARY TABLE tmp.sale;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sale_replaceItem` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_replaceItem`(vSaleFk INT, vNewItemFk INT, vQuantity INT)
BEGIN
/**
* Añade un nuevo articulo para sustituir a otro, y actualiza la memoria de sustituciones.
*
* @param vSaleFk id de la tabla sale
* @param vNewItemFk articulo sustituto
* @param vQuantity cantidad que se va a sustituir
*/
DECLARE vTicketFk INT;
DECLARE vItemFk INT;
DECLARE vWarehouseFk SMALLINT;
DECLARE vDate DATE;
DECLARE vGrouping INT;
DECLARE vGroupingMode VARCHAR(255);
DECLARE vPacking INT;
DECLARE vRoundQuantity INT DEFAULT 1;
DECLARE vLanded DATE;
DECLARE vAddressFk INT;
DECLARE vAgencyModeFk INT;
DECLARE vNewPrice DECIMAL(10,2);
DECLARE vOldPrice DECIMAL(10,2);
DECLARE vOption VARCHAR(255);
DECLARE vNewSaleFk INT;
DECLARE vFinalPrice DECIMAL(10,2);
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
SELECT s.ticketFk,
LEAST(s.quantity, vQuantity),
s.itemFk,
t.shipped,
t.warehouseFk,
t.landed,
t.addressFk,
t.agencyModeFk,
s.price
INTO vTicketFk,
vQuantity,
vItemFk,
vDate,
vWarehouseFk,
vLanded,
vAddressFk,
vAgencyModeFk,
vOldPrice
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
WHERE s.id = vSaleFk;
CALL buyUltimate(vWarehouseFk, vDate);
SELECT `grouping`, groupingMode, packing
INTO vGrouping,vGroupingMode,vPacking
FROM buy b
JOIN tmp.buyUltimate tmp ON b.id = tmp.buyFk
WHERE tmp.itemFk = vNewItemFk AND tmp.WarehouseFk = vWarehouseFk;
IF vGroupingMode = 'packing' AND vPacking > 0 THEN
SET vRoundQuantity = vPacking;
END IF;
IF vGroupingMode = 'grouping' AND vGrouping > 0 THEN
SET vRoundQuantity = vGrouping;
END IF;
CALL catalog_calcFromItem(
vLanded,
vAddressFk,
vAgencyModeFk,
vNewItemFk);
SELECT price INTO vNewPrice
FROM tmp.ticketComponentPrice
ORDER BY (vQuantity % `grouping`) ASC
LIMIT 1;
IF vNewPrice IS NULL THEN
CALL util.throw('price retrieval failed');
END IF;
IF vNewPrice > vOldPrice THEN
SET vFinalPrice = vOldPrice;
SET vOption = 'substitution';
ELSE
SET vFinalPrice = vNewPrice;
SET vOption = 'renewPrices';
END IF;
START TRANSACTION;
UPDATE sale
SET originalQuantity = quantity - vQuantity,
quantity = quantity - vQuantity
WHERE id = vSaleFk;
INSERT INTO vn.sale(ticketFk,
itemFk,
quantity,
concept,
price)
SELECT vTicketFk,
vNewItemFk,
CEIL(vQuantity / vRoundQuantity) * vRoundQuantity,
CONCAT('+ ', i.name),
vFinalPrice
FROM vn.item i
WHERE id = vNewItemFk;
SELECT LAST_INSERT_ID() INTO vNewSaleFk;
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 id = vNewSaleFk;
CALL ticketComponentUpdateSale(vOption);
CALL catalog_componentPurge();
INSERT INTO itemProposal(itemFk, mateFk, counter)
VALUES(vItemFk, vNewItemFk, 1)
ON DUPLICATE KEY UPDATE counter = counter + 1;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sectorCollectionSaleGroup_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollectionSaleGroup_add`(vSaleGroupFk INT, vSectorCollectionFk INT)
BEGIN
/**
* Inserta un nuevo registro en vn.sectorCollectionSaleGroup
* Actualiza el usuario en vn.saleGroup y reemplaza los registros de vn.saleTracking
*
* @param vSaleGroupFk Identificador de vn.saleGroup
* @param vSectorCollectionFk Identificador de vn.sectorCollection
*/
DECLARE vHasSaleGroup INT;
DECLARE vHasSectorCollection INT;
SELECT COUNT(id) INTO vHasSaleGroup
FROM saleGroup
WHERE id = vSaleGroupFk;
IF !vHasSaleGroup THEN
CALL util.throw ("invalid saleGroup");
END IF;
SELECT COUNT(id) INTO vHasSectorCollection
FROM sectorCollection
WHERE id = vSectorCollectionFk;
IF !vHasSectorCollection THEN
CALL util.throw ("invalid sectorCollection");
END IF;
REPLACE sectorCollectionSaleGroup
SET sectorCollectionFk = vSectorCollectionFk,
saleGroupFk = vSaleGroupFk;
UPDATE saleGroup sg
JOIN sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sg.id
JOIN sectorCollection sc ON sc.id = scsg.sectorCollectionFk
SET sg.userFk = sc.userFk
WHERE sg.id = vSaleGroupFk;
INSERT IGNORE saleTracking(
saleFk,
isChecked,
workerFk,
stateFk
)
SELECT sgd.saleFk ,
FALSE,
sc.userFk,
s.id
FROM saleGroupDetail sgd
JOIN sectorCollectionSaleGroup scsg
ON scsg.saleGroupFk = sgd.saleGroupFk
JOIN sectorCollection sc ON sc.id = scsg.sectorCollectionFk
JOIN state s ON s.code = 'PREVIOUS_PREPARATION'
WHERE sgd.saleGroupFk = vSaleGroupFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sectorCollection_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_get`()
BEGIN
/**
* Devuelve las colecciones del sector que corresponden al usuario conectado, y que estan incompletas
*
*/
SELECT DISTINCT sc.id collectionFk, sc.created
FROM vn.sectorCollection sc
JOIN vn.state s ON s.code = 'PREVIOUS_PREPARATION'
LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id
LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk
LEFT JOIN vn.saleTracking st ON st.saleFk = sgd.saleFk AND st.stateFk = s.id AND st.workerFk = sc.userFk
LEFT JOIN vn.sale sl ON sl.id = st.saleFk
WHERE sc.userFk = account.myUser_getId()
AND (
ISNULL(scsg.sectorCollectionFk)
OR (NOT st.isChecked AND sl.quantity > 0)
)
AND sc.created > util.VN_CURDATE();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sectorCollection_getSale` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_getSale`(vSelf INT)
BEGIN
/**
* Devuelve las lineas de venta correspondientes a esa coleccion de sector
*
* @param vSelf Identificador de vn.sectorCollection
*/
SELECT s.ticketFk,
s.itemFk,
i.longName,
itemPackingTypeFk,
subName,
s.quantity,
w.code workerCode,
sgd.saleFk,
iss.quantity pickedQuantity,
c.salesPersonFk
FROM vn.sale s
JOIN item i ON i.id = s.itemFk
JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
JOIN sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sgd.saleGroupFk
JOIN saleTracking st ON st.saleFk = s.id
JOIN `state` stt ON stt.id = st.stateFk AND stt.code = 'PREVIOUS_PREPARATION'
JOIN worker w ON w.id = st.workerFk
JOIN ticket t ON t.id= s.ticketFk
JOIN client c ON c.id=t.clientFk
LEFT JOIN itemShelvingSaleSum iss ON iss.saleFk = s.id
WHERE scsg.sectorCollectionFk = vSelf
AND st.workerFk = account.myUser_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sectorCollection_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_new`(vSectorFk INT)
BEGIN
/**
* Inserta una nueva colección, si el usuario no tiene ninguna vacia.
* Esto se hace para evitar que por error se generen colecciones sin sentido.
*
* @param vSectorFk Identificador de #vn.sector
*/
DECLARE hasEmptyCollections BOOL;
DECLARE vUserFk INT;
SET vUserFk = account.myUser_getId();
SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections
FROM vn.sectorCollection sc
LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id
WHERE ISNULL(scsg.id)
AND sc.userFk = vUserFk
AND sc.sectorFk = vSectorFk
AND sc.created >= util.VN_CURDATE();
IF NOT hasEmptyCollections THEN
INSERT INTO vn.sectorCollection(userFk, sectorFk)
VALUES(vUserFk, vSectorFk);
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sectorProductivity_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorProductivity_add`()
BEGIN
DECLARE vDatedFrom DATETIME;
DECLARE vDatedTo DATETIME;
SELECT DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY), CONCAT(DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY),' 23:59:59') INTO vDatedFrom, vDatedTo;
DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate;
DROP TEMPORARY TABLE IF EXISTS tmp.errorsByChecker;
DROP TEMPORARY TABLE IF EXISTS tmp.previousErrors;
CALL timeControl_calculateAll(vDatedFrom, vDatedTo);
CREATE TEMPORARY TABLE tmp.errorsByChecker
ENGINE = MEMORY
SELECT sc.userFk workerFk, COUNT(DISTINCT s.ticketFk) errorsByChecker
FROM saleMistake sm
JOIN vn.saleGroupDetail sgd on sgd.saleFk = sm.saleFk
JOIN vn.sectorCollectionSaleGroup scsg on scsg.saleGroupFk = sgd.saleGroupFk
JOIN vn.sectorCollection sc on sc.id = scsg.sectorCollectionFk
JOIN sale s ON s.id = sm.saleFk
JOIN ticket t on t.id = s.ticketFk
WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo)
GROUP BY sc.userFk ;
CREATE TEMPORARY TABLE tmp.previousErrors -- Errores de previa, derivadores de los revisadores (por reclamación)
ENGINE = MEMORY
SELECT tt.userFk, COUNT(c.ticketFk) errorsByClaim
FROM claimDevelopment cd
JOIN claim c ON cd.claimFk = c.id
JOIN ticket t ON c.ticketFk = t.id
JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id
JOIN ticketTracking tt ON tt.ticketFk = t.id
JOIN `state` s ON s.id = tt.stateFk
WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND cr.description = 'Revisadores' AND s.code = 'OK PREVIOUS'
GROUP BY tt.userFk;
DELETE FROM sectorProductivity
WHERE dated = vDatedFrom
AND sector IN ('Algemesi Artificial','Algemesi Complementos');
INSERT INTO sectorProductivity(workerFk, firstName, lastName, sector, ticketCount, saleCount, error, volume, hourWorked, dated)
SELECT w.id workerFk,
w.firstName,
w.lastName,
se.description sector,
COUNT(DISTINCT s.ticketFk) ticketCount,
COUNT(sgd.id) saleCount,
IFNULL(ec2.errorsByChecker,0) + IFNULL(pe.errorsByClaim, 0) errors,
wp.volume,
IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) AS hourWorked,
DATE(vDatedFrom) dated
FROM vn.saleGroupDetail sgd
JOIN vn.saleGroup sg on sg.id = sgd.saleGroupFk
JOIN vn.sectorCollectionSaleGroup scsg on scsg.saleGroupFk = sgd.saleGroupFk
JOIN vn.sectorCollection sc on sc.id = scsg.sectorCollectionFk
join vn.sector se on se.id = sc.sectorFk
JOIN vn.worker w ON w.id = sc.userFk
LEFT JOIN vn.sale s ON s.id = sgd.saleFk
LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = w.id
LEFT JOIN bs.workerProductivity wp ON wp.workerFk = w.id
LEFT JOIN `state` s2 ON s2.id = wp.stateFk AND s2.code = 'OK PREVIOUS'
LEFT JOIN tmp.errorsByChecker ec2 ON ec2.workerFk = w.id
LEFT JOIN tmp.previousErrors pe ON pe.userFk = w.id
WHERE DATE(sc.created) = vDatedFrom
AND wp.dated = vDatedFrom
GROUP BY w.id;
DROP TEMPORARY TABLE tmp.timeControlCalculate;
DROP TEMPORARY TABLE tmp.errorsByChecker;
DROP TEMPORARY TABLE tmp.previousErrors;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sector_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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sector_getWarehouse`(vSectorFk INT)
BEGIN
SELECT s.warehouseFk
FROM vn.sector s
WHERE s.id = vSectorFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `setParking` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `setParking`(IN `vParam` VARCHAR(8), IN `vParkingCode` VARCHAR(8))
proc: BEGIN
/**
* Aparca una colección, un ticket, un saleGroup o un shelving en un parking
*
* @param vParam id del ticket, colección, saleGroup o shelving
* @param vParkingCode código del parking
*/
DECLARE vParkingFk INT;
DECLARE vIsSaleGroup BOOL;
DECLARE vIsTicket BOOL;
DECLARE vIsCollection BOOL;
SET vParkingCode = replace(vParkingCode,' ','');
SELECT id INTO vParkingFk
FROM vn.parking
WHERE code = vParkingCode COLLATE utf8_unicode_ci;
IF vParkingFk IS NULL THEN
CALL util.throw('parkingNotExist');
LEAVE proc;
END IF;
-- Se comprueba si es una preparación previa
SELECT COUNT(*) INTO vIsSaleGroup
FROM vn.saleGroup sg
WHERE sg.id = vParam;
IF vIsSaleGroup THEN
CALL vn.saleGroup_setParking(vParam, vParkingFk);
LEAVE proc;
END IF;
-- Se comprueba si es un ticket
SELECT COUNT(*) INTO vIsTicket
FROM vn.ticket t
WHERE t.id = vParam
AND t.shipped >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE());
IF vIsTicket THEN
CALL vn.ticket_setParking(vParam, vParkingFk);
LEAVE proc;
END IF;
-- Se comprueba si es una coleccion de tickets
SELECT COUNT(*) INTO vIsCollection
FROM vn.collection c
WHERE c.id = vParam
AND c.created >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE());
IF vIsCollection THEN
CALL vn.collection_setParking(vParam, vParkingFk);
LEAVE proc;
END IF;
-- Por descarte, se considera una matrícula
CALL vn.shelving_setParking(vParam, vParkingFk);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `shelvingLog_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `shelvingLog_get`(shelvingFk VARCHAR(10))
BEGIN
/* Lista el log de un carro
*
* @param shelvingFk matrícula del carro
*
*/
SELECT originFk, name, creationDate, description
FROM shelvingLog sl
JOIN account.user u ON u.id = sl.userFk
WHERE sl.originFk = shelvingFk COLLATE utf8_general_ci
ORDER BY creationDate 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `shelvingParking_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `shelvingParking_get`(vShelvingFk VARCHAR(10), vWarehouseFk INT, vDayRange INT)
BEGIN
SELECT s.itemFk,
s.concept,
CAST(SUM(s.quantity) AS DECIMAL(10,0)) as sinServir,
CAST(IFNULL(ist.visible,0) AS DECIMAL(10,0)) as aparcado
FROM vn.sale s
LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id
JOIN vn.ticket t ON t.id = s.ticketFk
LEFT JOIN vn.itemShelvingStock ist ON ist.itemFk = s.itemFk AND ist.warehouseFk = vWarehouseFk
JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk AND ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci
WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(TIMESTAMPADD(DAY, GREATEST(0,vDayRange), util.VN_CURDATE()))
AND iss.saleFk IS NULL
AND t.warehouseFk = vWarehouseFk
GROUP BY s.itemFk
HAVING sinServir > aparcado;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `shelvingPriority_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `shelvingPriority_update`(priority INT,vShelvingFk VARCHAR(10))
BEGIN
UPDATE vn.shelving SET priority = priority WHERE code=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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `shelving_clean`()
BEGIN
DELETE FROM shelving
WHERE length(code) > 3
AND parked < TIMESTAMPADD(WEEK,-1,util.VN_CURDATE());
DELETE FROM itemShelving
WHERE visible <= 0
AND created < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE());
DELETE ish.*
FROM itemShelving ish
JOIN vn.shelving sh ON sh.code = ish.shelvingFk
WHERE sh.parkingFk IS NULL
AND ish.created < TIMESTAMPADD(WEEK,-1,util.VN_CURDATE());
UPDATE shelving sh
LEFT JOIN itemShelving its ON its.shelvingFk = sh.`code`
SET isPrinted = 0,
parkingFk = NULL
WHERE its.id IS NULL
AND sh.isRecyclable
AND (
sh.parked IS NULL
OR
sh.parked < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())
)
AND IF(code REGEXP '^[A-Za-z]{2}[0-9]', LEFT (code, 2) NOT IN (
SELECT DISTINCT LEFT(its.shelvingFk, 2)
FROM itemShelving its
WHERE its.shelvingFk REGEXP '^[A-Za-z]{2}[0-9]'
), 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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `shelving_getSpam` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `shelving_getSpam`(vDated DATE, vWarehouseFk INT)
BEGIN
/**
* Devuelve las matrículas con productos que no son necesarios para la venta
* hasta la fecha señalada.
*
* @param vDated Fecha hasta la que se puede pasar sin esos productos
* @param vWarehouse Identificador único de vn.warehouse
*/
DROP TEMPORARY TABLE IF EXISTS tmp.stock;
CALL cache.stock_refresh(FALSE);
CREATE TEMPORARY TABLE tmp.stock
SELECT i.id itemFk,
v.amount - IFNULL(fue.reserva,0) as visible,
fue.reserva,
sale.venta,
IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra,
IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) - IFNULL(fue.reserva,0) as saldo
FROM vn.item i
JOIN vn.itemType it ON it.id = i.typeFk
JOIN vn.itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN (
SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS reserva
FROM vn.itemShelving ish
JOIN vn.shelving sh ON sh.code = ish.shelvingFk
JOIN vn.parking p ON p.id = sh.parkingFk
JOIN vn.sector s ON s.id = p.sectorFk
WHERE s.code = 'FUENTES_PICASSE'
OR sh.isSpam
GROUP BY ish.itemFk
) fue ON fue.itemFk = i.id
LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk
LEFT JOIN (
SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as venta
FROM itemTicketOut
WHERE shipped BETWEEN util.VN_CURDATE() AND util.dayend(vDated)
AND warehouseFk = vWarehouseFk
GROUP BY itemFk
) sale ON sale.item_id = i.id
LEFT JOIN (
SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as compra
FROM itemEntryIn
WHERE landed BETWEEN util.VN_CURDATE() AND util.dayend(vDated)
AND warehouseInFk = vWarehouseFk
AND isVirtualStock = FALSE
GROUP BY itemFk
) buy ON buy.item_id = i.id
LEFT JOIN (
SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as traslado
FROM itemEntryOut
WHERE shipped BETWEEN util.VN_CURDATE() AND util.dayend(vDated)
AND warehouseOutFk = vWarehouseFk
GROUP BY itemFk
) mov ON mov.item_id = i.id
WHERE v.amount;
SELECT ish.shelvingFk matricula,
i.longName articulo,
ish.visible,
count(*) lineas,
sum(ish.visible <= s.saldo) spam,
p.code parking,
s.description sector ,
w.name AS almacen,
sh.isSpam
FROM vn.itemShelving ish
JOIN vn.item i ON i.id = ish.itemFk
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
JOIN vn.warehouse w ON w.id = s.warehouseFk
LEFT JOIN tmp.stock s ON s.itemFk = ish.itemFk
WHERE (w.name = 'Algemesi'
OR (w.name = 'NuncaJamas' AND ish.created < util.VN_CURDATE()))
AND ish.visible
GROUP BY ish.shelvingFk
HAVING lineas = spam OR isSpam;
DROP TEMPORARY TABLE tmp.stock;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `shelving_setParking` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `shelving_setParking`(IN `vShelvingCode` VARCHAR(8), IN `vParkingFk` INT)
proc: BEGIN
/**
* Aparca una matrícula en un parking
*
* @param vShelvingCode code de la matrícula
* @param vParkingFk id del parking
*/
INSERT INTO vn.shelvingLog (originFk, userFk, action , description,changedModel,changedModelId)
SELECT s.id, account.myUser_getId(), 'update', CONCAT("Cambio parking ",vShelvingCode," de ", p.code," a ", pNew.code),'Shelving',s.id
FROM parking p
JOIN shelving s ON s.parkingFk = p.id
JOIN parking pNew ON pNew.id = vParkingFk
WHERE s.code = vShelvingCode COLLATE utf8_unicode_ci;
UPDATE vn.shelving
SET parkingFk = vParkingFk,
parked = util.VN_NOW(),
isPrinted = TRUE
WHERE code = vShelvingCode 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `sleep_X_min` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sleep_X_min`()
BEGIN
# Ernesto. 4.8.2020
# Para su uso en las tareas ejecutadas a las 2AM (visibles con: SELECT * FROM bs.nightTask order by started asc;)
# Simplemente esperar unos minutos para que en las graficas de rendimiento de Percona PMM y escritura a disco de vCenter se puedan ver los efectos de cada tarea.
do SLEEP(300);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `stockBuyedByWorker`(
vDated DATE,
vWorker INT
)
BEGIN
/**
* Inserta el volumen de compra de un comprador
* en stockBuyed de acuerdo con la fecha.
*
* @param vDated Fecha de compra
* @param vWorker Id de trabajador
*/
CREATE OR REPLACE TEMPORARY TABLE tStockBuyed
(INDEX (userFk))
ENGINE = MEMORY
SELECT requested, reserved, userFk
FROM stockBuyed
WHERE dated = vDated
AND userFk = vWorker;
DELETE FROM stockBuyed
WHERE dated = vDated
AND userFk = vWorker;
CALL stockTraslation(vDated);
INSERT INTO stockBuyed(userFk, buyed, `dated`, reserved, requested, description)
SELECT it.workerFk,
SUM((ti.quantity / b.packing) * buy_getVolume(b.id)) / vc.palletM3 / 1000000,
vDated,
sb.reserved,
sb.requested,
u.name
FROM itemType it
JOIN item i ON i.typeFk = it.id
LEFT JOIN tmp.item ti ON ti.itemFk = i.id
JOIN itemCategory ic ON ic.id = it.categoryFk
JOIN warehouse wh ON wh.code = 'VNH'
JOIN tmp.buyUltimate bu ON bu.itemFk = i.id
AND bu.warehouseFk = wh.id
JOIN buy b ON b.id = bu.buyFk
JOIN volumeConfig vc
JOIN account.`user` u ON u.id = it.workerFk
LEFT JOIN tStockBuyed sb ON sb.userFk = it.workerFk
WHERE ic.display
AND it.workerFk = vWorker;
SELECT b.entryFk Id_Entrada,
i.id Id_Article,
i.name Article,
ti.quantity Cantidad,
(ac.conversionCoefficient * (ti.quantity / b.packing) * buy_getVolume(b.id))
/ (vc.trolleyM3 * 1000000) buyed,
b.packagingFk id_cubo,
b.packing
FROM tmp.item ti
JOIN item i ON i.id = ti.itemFk
JOIN itemType it ON i.typeFk = it.id
JOIN itemCategory ic ON ic.id = it.categoryFk
JOIN worker w ON w.id = it.workerFk
JOIN auctionConfig ac
JOIN tmp.buyUltimate bu ON bu.itemFk = i.id
AND bu.warehouseFk = ac.warehouseFk
JOIN buy b ON b.id = bu.buyFk
JOIN volumeConfig vc
WHERE ic.display
AND w.id = vWorker;
DROP TEMPORARY TABLE tmp.buyUltimate,
tmp.item,
tStockBuyed;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `stockBuyed_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `stockBuyed_add`(
vDated DATE
)
BEGIN
/**
* Inserta el volumen de compra por comprador
* en stockBuyed de acuerdo con la fecha.
*
* @param vDated Fecha de compra
*/
CREATE OR REPLACE TEMPORARY TABLE tStockBuyed
(INDEX (userFk))
ENGINE = MEMORY
SELECT requested, reserved, userFk
FROM stockBuyed
WHERE dated = vDated;
DELETE FROM stockBuyed WHERE dated = vDated;
CALL stockTraslation(vDated);
INSERT INTO stockBuyed(userFk, buyed, `dated`, description)
SELECT it.workerFk,
SUM((ti.quantity / b.packing) * buy_getVolume(b.id)) / vc.palletM3 / 1000000,
vDated,
u.name
FROM itemType it
JOIN item i ON i.typeFk = it.id
LEFT JOIN tmp.item ti ON ti.itemFk = i.id
JOIN itemCategory ic ON ic.id = it.categoryFk
JOIN warehouse wh ON wh.code = 'VNH'
JOIN tmp.buyUltimate bu ON bu.itemFk = i.id AND bu.warehouseFk = wh.id
JOIN buy b ON b.id = bu.buyFk
JOIN volumeConfig vc
JOIN account.`user` u ON u.id = it.workerFk
JOIN workerDepartment wd ON wd.workerFk = u.id
JOIN department d ON d.id = wd.departmentFk
WHERE ic.display
AND d.code IN ('shopping', 'logistic', 'franceTeam')
GROUP BY it.workerFk;
INSERT INTO stockBuyed(buyed, dated, description)
SELECT SUM(ic.cm3 * ito.quantity / vc.palletM3 / 1000000),
vDated,
IF(c.code = 'ES', p.name, c.country) destiny
FROM itemTicketOut ito
JOIN ticket t ON t.id = ito.ticketFk
JOIN `address` a ON a.id = t.addressFk
JOIN province p ON p.id = a.provinceFk
JOIN country c ON c.id = p.countryFk
JOIN warehouse wh ON wh.id = t.warehouseFk
JOIN itemCost ic ON ic.itemFk = ito.itemFk
AND ic.warehouseFk = t.warehouseFk
JOIN volumeConfig vc
WHERE ito.shipped BETWEEN vDated AND util.dayend(vDated)
AND wh.code = 'VNH'
GROUP BY destiny;
UPDATE stockBuyed s
JOIN tStockBuyed ts ON ts.userFk = s.userFk
SET s.requested = ts.requested,
s.reserved = ts.reserved
WHERE s.dated = vDated;
DROP TEMPORARY TABLE tmp.buyUltimate,
tmp.item,
tStockBuyed;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `stockTraslation`(
vDated DATE
)
BEGIN
/**
* Calcula el stock del almacén de subasta desde FechaInventario hasta vDated
* sin tener en cuenta las salidas del mismo dia vDated
* para ver el transporte a reservar
*
* @param vDated Fecha hasta la cual calcula el stock
* @return tmp.item
*/
DECLARE vAuctionWarehouseFk INT;
SELECT warehouseFk INTO vAuctionWarehouseFk
FROM auctionConfig;
CREATE OR REPLACE TEMPORARY TABLE tmp.item
(UNIQUE INDEX i USING HASH (itemFk))
ENGINE = MEMORY
SELECT itemFk, SUM(quantity) quantity
FROM itemEntryIn
WHERE landed = vDated
AND vDated >= util.VN_CURDATE()
AND warehouseInFk = vAuctionWarehouseFk
AND NOT isVirtualStock
GROUP BY itemFk
HAVING quantity;
CALL `cache`.stock_refresh(FALSE);
INSERT INTO tmp.item (itemFk, quantity)
SELECT item_id, amount
FROM `cache`.stock
WHERE warehouse_id = vAuctionWarehouseFk
ON DUPLICATE KEY UPDATE quantity = tmp.item.quantity + VALUES(quantity);
CALL buyUltimate(vAuctionWarehouseFk, 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `supplierPackaging_ReportSource`(
vFromDated DATE,
vSupplierFk INT
)
BEGIN
/**
* Selecciona los embalajes de un proveedor a partir de una fecha
*
* @param vFromDated Fecha de la que partir
* @param vSupplierFk Id del proveedor
*/
SET @vBalance = 0;
SET @vItemFk = NULL;
CREATE OR REPLACE TEMPORARY TABLE tSupplierPackaging
SELECT supplierFk,
itemFk,
longName,
supplier,
entryFk,
landed,
`in`,
`out`,
warehouse,
buyingValue,
IF (
NOT (@vItemFk <=> sub.itemFk),
@vBalance := (`in` - `out`),
@vBalance := (`in` - `out` + @vBalance)
) balance,
@vItemFk := sub.itemFk previousItemFk
FROM (
SELECT supplierFk,
itemFk,
longName,
supplier,
entryFk,
landed,
`in`,
`out`,
warehouse,
buyingValue
FROM supplierPackaging
WHERE supplierFk = vSupplierFk
AND landed >= vFromDated
UNION ALL
SELECT vSupplierFk,
itemFk,
longName,
supplier,
'previous',
vFromDated,
SUM(`in`),
SUM(`out`),
NULL,
buyingValue
FROM supplierPackaging
WHERE supplierFk = vSupplierFk
AND landed < vFromDated
GROUP BY itemFk
ORDER BY itemFk, landed, entryFk
) sub
WHERE `out` OR `in`;
SELECT supplierFk,
itemFk,
longName,
supplier,
entryFk,
landed,
`in`,
`out`,
warehouse,
buyingValue,
balance
FROM tSupplierPackaging
WHERE NOT (NOT balance AND landed < CURDATE() - INTERVAL 1 YEAR);
DROP TEMPORARY TABLE tSupplierPackaging;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `supplier_checkBalance` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `supplier_checkBalance`(IN vDateTo DATETIME, IN vIsConciliated BOOL)
BEGIN
/**
* Compara los datos de nuestros proveedores con
* los que hay en la base de datos de sage
*
* @param vDateTo
* @param vIsConciliated
* @table tmp.ledgerComparative (id, date, account, debit, credit, companyFk)
*/
DECLARE vDateFrom DATE;
DECLARE vMaxTolerance DECIMAL(10,2);
SET vDateTo = TIMESTAMP(vDateTo,'23:59:59');
SELECT util.firstDayOfYear(vDateTo) INTO vDateFrom;
SELECT maxTolerance INTO vMaxTolerance
FROM vn.ledgerConfig;
SELECT c.code,
s.id supplierFk,
s.account,
sub1.mysql,
sub1.sage,
sub1.mysql - sub1.sage difference,
sub1.companyFk,
s.name
FROM supplier s
JOIN (SELECT companyFk,
supplierFk,
CAST(ROUND(SUM(mysql),2) AS DECIMAL(10,2)) mysql,
CAST(ROUND(SUM(sage),2) AS DECIMAL(10,2)) sage
FROM (SELECT companyFk,
supplierFk,
- SUM(iid.amount) mysql,
0 sage
FROM invoiceInDueDay iid
JOIN invoiceIn ii ON ii.id = iid.invoiceInFk
WHERE IFNULL(ii.bookEntried, ii.issued) BETWEEN vDateFrom AND vDateTo
AND ii.isBooked
GROUP BY ii.id
UNION ALL
SELECT p.companyFk,
p.supplierFk,
p.amount,
0
FROM payment p
JOIN payMethod pm ON pm.id = p.payMethodFk
WHERE p.received BETWEEN vDateFrom AND vDateTo
AND IF(vIsConciliated, p.isConciliated, TRUE) = TRUE
AND NOT pm.code <=>'previousBalance'
UNION ALL
SELECT se.companyFk,
se.supplierFk,
- se.amount,
0
FROM supplierExpense se
WHERE se.dated BETWEEN vDateFrom AND vDateTo
AND IF(vIsConciliated, se.isConciliated, TRUE) = TRUE
UNION ALL
SELECT lc.companyFk,
s.id,
0,
- (IFNULL(lc.debit, 0) - IFNULL(lc.credit, 0))
FROM tmp.ledgerComparative lc
JOIN supplier s ON s.account = lc.account
WHERE lc.`date` BETWEEN vDateFrom AND vDateTo
) sub
GROUP BY companyFk, supplierFk
) sub1 ON sub1.supplierFk = s.id
JOIN company c ON c.id = sub1.companyFk
HAVING ABS(difference) > vMaxTolerance
ORDER BY s.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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `supplier_checkIsActive` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `supplier_checkIsActive`(vSelf INT)
BEGIN
/**
* Comprueba si un proveedor esta activo.
*/
DECLARE vIsActive BOOL;
SELECT isActive INTO vIsActive
FROM vn.supplier
WHERE id = vSelf;
IF NOT vIsActive THEN
CALL util.throw('INACTIVE_PROVIDER');
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `supplier_disablePayMethodChecked` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `supplier_disablePayMethodChecked`()
BEGIN
/*
* Deshabilita la comprobación de los datos bancarios de todos aquellos proveedores que tengan
* un número que no sea 0 en el campo graceMonthsDisableChecked de la tabla vn.payMethod
* y que no hayan recibido un pago desde el mes indicado
*/
UPDATE vn.supplier s
JOIN ( SELECT p.supplierFk
FROM supplier s
JOIN payMethod pm ON pm.id = s.payMethodFk
JOIN (SELECT supplierFk,MAX(created) created
FROM payment
GROUP BY supplierFk) p ON p.supplierFk = s.id
WHERE p.created < (util.VN_CURDATE() - INTERVAL pm.graceMonthsDisableChecked MONTH)
AND pm.graceMonthsDisableChecked
AND s.isPayMethodChecked
GROUP BY p.supplierFk) sdpmc ON sdpmc.supplierFk = s.id
SET s.isPayMethodChecked = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `supplier_statement` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `supplier_statement`(
vSupplierFk INT,
vCurrencyFk INT,
vCompanyFk INT,
vOrderBy VARCHAR(15),
vIsConciliated BOOL
)
BEGIN
/**
* Crea un estado de cuenta de proveedores calculando
* los saldos en euros y en la moneda especificada.
*
* @param vSupplierFk Id del proveedor
* @param vCurrencyFk Id de la moneda
* @param vCompanyFk Id de la empresa
* @param vOrderBy Criterio de ordenación
* @param vIsConciliated Indica si está conciliado o no
* @return tmp.supplierStatement
*/
SET @euroBalance:= 0;
SET @currencyBalance:= 0;
CREATE OR REPLACE TEMPORARY TABLE tmp.supplierStatement
ENGINE = MEMORY
SELECT *,
@euroBalance:= ROUND(
@euroBalance + IFNULL(paymentEuros, 0) -
IFNULL(invoiceEuros, 0), 2
) euroBalance,
@currencyBalance:= ROUND(
@currencyBalance + IFNULL(paymentCurrency, 0) -
IFNULL(invoiceCurrency, 0), 2
) currencyBalance
FROM (
SELECT * FROM
(
SELECT NULL bankFk,
ii.companyFk,
ii.serial,
ii.id,
CASE
WHEN vOrderBy = 'issued' THEN ii.issued
WHEN vOrderBy = 'bookEntried' THEN ii.bookEntried
WHEN vOrderBy = 'booked' THEN ii.booked
WHEN vOrderBy = 'dueDate' THEN iid.dueDated
END dated,
CONCAT('S/Fra ', ii.supplierRef) sref,
IF(ii.currencyFk > 1,
ROUND(SUM(iid.foreignValue) / SUM(iid.amount), 3),
NULL
) changeValue,
CAST(SUM(iid.amount) AS DECIMAL(10,2)) invoiceEuros,
CAST(SUM(iid.foreignValue) AS DECIMAL(10,2)) invoiceCurrency,
NULL paymentEuros,
NULL paymentCurrency,
ii.currencyFk,
ii.isBooked,
c.code,
'invoiceIn' statementType
FROM invoiceIn ii
JOIN invoiceInDueDay iid ON iid.invoiceInFk = ii.id
JOIN currency c ON c.id = ii.currencyFk
WHERE ii.issued > '2014-12-31'
AND ii.supplierFk = vSupplierFk
AND vCurrencyFk IN (ii.currencyFk, 0)
AND vCompanyFk IN (ii.companyFk, 0)
AND (vIsConciliated = ii.isBooked OR NOT vIsConciliated)
GROUP BY iid.id
UNION ALL
SELECT p.bankFk,
p.companyFk,
NULL,
p.id,
CASE
WHEN vOrderBy = 'issued' THEN p.received
WHEN vOrderBy = 'bookEntried' THEN p.received
WHEN vOrderBy = 'booked' THEN p.received
WHEN vOrderBy = 'dueDate' THEN p.dueDated
END,
CONCAT(IFNULL(pm.name, ''),
IF(pn.concept <> '',
CONCAT(' : ', pn.concept),
'')
),
IF(p.currencyFk > 1, p.divisa / p.amount, NULL),
NULL,
NULL,
p.amount,
p.divisa,
p.currencyFk,
p.isConciliated,
c.code,
'payment'
FROM payment p
LEFT JOIN currency c ON c.id = p.currencyFk
LEFT JOIN accounting a ON a.id = p.bankFk
LEFT JOIN payMethod pm ON pm.id = p.payMethodFk
LEFT JOIN promissoryNote pn ON pn.paymentFk = p.id
WHERE p.received > '2014-12-31'
AND p.supplierFk = vSupplierFk
AND vCurrencyFk IN (p.currencyFk, 0)
AND vCompanyFk IN (p.companyFk, 0)
AND (vIsConciliated = p.isConciliated OR NOT vIsConciliated)
UNION ALL
SELECT NULL,
companyFk,
NULL,
se.id,
CASE
WHEN vOrderBy = 'issued' THEN se.dated
WHEN vOrderBy = 'bookEntried' THEN se.dated
WHEN vOrderBy = 'booked' THEN se.dated
WHEN vOrderBy = 'dueDate' THEN se.dueDated
END,
se.description,
1,
amount,
NULL,
NULL,
NULL,
currencyFk,
isConciliated,
c.`code`,
'expense'
FROM supplierExpense se
JOIN currency c ON c.id = se.currencyFk
WHERE se.supplierFk = vSupplierFk
AND vCurrencyFk IN (se.currencyFk,0)
AND vCompanyFk IN (se.companyFk,0)
AND (vIsConciliated = se.isConciliated OR NOT vIsConciliated)
) sub
ORDER BY (dated IS NULL AND NOT isBooked),
dated,
IF(vOrderBy = 'dueDate', id, NULL)
LIMIT 10000000000000000000
) 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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.packagingFk
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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
ticketFk,
created as builtTime
FROM
ticketTracking
WHERE created BETWEEN vDateStart AND vDateEnd
ORDER BY ticketFk, created DESC
LIMIT 10000000000000000000
) 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCalculateClon`(IN vTicketNew INT, vTicketOld INT)
BEGIN
/*
* Recalcula los componentes un ticket clonado,
* las lineas a precio cero fuerza para que tengan precio, el resto lo respeta
* @param vTicketNew nuevo ticket clonado
* @param vTicketOld icket original, a partir del qual se clonara el nuevo
*/
REPLACE INTO orderTicket(orderFk,ticketFk)
SELECT orderFk, vTicketNew
FROM orderTicket
WHERE ticketFk = vTicketOld;
-- Bionizamos lineas con Preu = 0
CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales
(PRIMARY KEY (id)) ENGINE = MEMORY
SELECT id
FROM sale
WHERE ticketFk = vTicketNew AND price = 0;
CALL sale_recalcComponent('renewPrices');
-- Bionizamos lineas con Preu > 0
CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales
(PRIMARY KEY (id)) ENGINE = MEMORY
SELECT id
FROM sale
WHERE ticketFk = vTicketNew AND price > 0;
CALL sale_recalcComponent('buyerDiscount');
DROP TEMPORARY TABLE IF EXISTS tmp.recalculateSales;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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, FALSE);
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketClon` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketClon`(vTicketFk INT, vNewShipped DATE)
BEGIN
DECLARE vNewTicketFk INT;
CALL ticket_cloneAll(vTicketFk, vNewShipped, TRUE, vNewTicketFk);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketClon_OneYear` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketClon_OneYear`(vTicketFk INT)
BEGIN
DECLARE vShipped DATE;
DECLARE vMaxDated DATE;
SELECT shipped, TIMESTAMPADD(YEAR,1,shipped)
INTO vShipped, vMaxDated
FROM vn.ticket
WHERE id = vTicketFk;
WHILE vShipped <= vMaxDated DO
SET vShipped = TIMESTAMPADD(WEEK, 1, vShipped);
CALL vn.ticketClon(vTicketFk, vShipped);
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketCollection_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCollection_get`(vTicketFk INT)
BEGIN
SELECT tc.collectionFk
FROM vn.ticketCollection tc
WHERE 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketCollection_setUsedShelves` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCollection_setUsedShelves`(vTicketFk INT, vUsedShelves INT)
BEGIN
/*
* Inserta número de baldas que ocupa un ticket
*
* @param vTicketFk Identificador de ticket
* @param vUsedShelves Número de baldas
*/
UPDATE ticketCollection tc
SET tc.usedShelves = vUsedShelves
WHERE tc.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketComponentUpdate`(
vTicketFk INT,
vClientFk INT,
vAgencyModeFk INT,
vAddressFk INT,
vWarehouseFk TINYINT,
vCompanyFk SMALLINT,
vShipped DATETIME,
vLanded DATE,
vIsDeleted BOOLEAN,
vHasToBeUnrouted BOOLEAN,
vOption VARCHAR(25))
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;
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;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketComponentUpdateSale`(vCode VARCHAR(25))
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;
IF vCode <> 'renewPrices' THEN
SELECT id INTO vComponentFk FROM component WHERE `code` = vCode;
END IF;
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);
-- Añadir componente venta por paquete
REPLACE INTO saleComponent(saleFk, componentFk, value)
SELECT t.id, t.componentFk, t.cost
FROM (
SELECT s.id, tc.componentFk, tc.cost, MOD(s.quantity, b.packing) as resto
FROM vn.sale s
JOIN tmp.sale tmps ON tmps.saleFk = s.id
JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND tmps.warehouseFk = lb.warehouse_id
JOIN vn.buy b ON b.id = buy_id
JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk
JOIN `component` c ON c.id = tc.componentFk AND c.code = 'salePerPackage'
LEFT JOIN (
SELECT s.id
FROM vn.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
JOIN saleComponent sc ON sc.saleFk = s.id AND sc.componentFk = tc.componentFk
JOIN `component` c ON c.id = sc.componentFk AND c.code = 'lastUnitsDiscount'
) tp ON tp.id = s.id
WHERE tp.id IS NULL
HAVING resto <> 0) t;
IF vCode <> 'renewPrices' 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 / ((100 - s.discount) / 100)
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.isBase
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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.ticket_getTax(NULL);
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketGetTotal`(vTaxArea VARCHAR(25))
BEGIN
/**
* Calcula el total con IVA para un conjunto de tickets.
*
* @param vTaxArea
* @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
* @return tmp.ticketTotal Total para cada ticket
*/
CALL ticket_getTax(vTaxArea);
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,
SUM(ta.taxableBase) totalWithoutVat
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 >= util.VN_CURDATE() THEN
CALL cache.available_refresh(vAvailableCalc, FALSE, vWarehouse, vShipped);
END IF;
IF vShipped = util.VN_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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
LIMIT 1;
SELECT created, parkingFk
INTO vParked, vParkingFk
FROM vn.ticketParking
WHERE ticketFk = vTicketFk;
SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' - ', 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.ticketFk = 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) )
)
)) -- Etiquetas que no se han escaneado y ya estamos con una posterior
OR
(s.alertLevel > 1
AND tp.parkingFk = vParkingFk
AND sc.isPackagingArea
AND tp.created < vParked
AND t.packages <=> 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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(NULL);
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketObservation_addNewBorn` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketObservation_addNewBorn`(vTicketFk INT)
BEGIN
/**
* Inserta observaciones para los tickets con clientes nuevos o recuperados
*
* @param vTicketFk Identificador de vn.ticket
*/
DECLARE vDescription VARCHAR(20) DEFAULT '¡Cliente NUEVO! ';
INSERT INTO vn.ticketObservation(ticketFk, observationTypeFk, description)
SELECT vTicketFk, ot.id, vDescription
FROM vn.observationType ot
WHERE ot.hasNewBornMessage
ON DUPLICATE KEY UPDATE description = CONCAT(vDescription, ticketObservation.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketPackaging_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 = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketPackaging_add`(
vClientFk INT,
vDated DATE,
vCompanyFk INT,
vWithoutPeriodGrace BOOLEAN)
BEGIN
/**
* Genera nuevos tickets de embalajes para los clientes no han los han retornado
* y actualiza los valores para la tabla ticketPackaging
*
* @param vClientFk Cliente en caso de NULL todos los clientes
* @param vDated Fecha hasta la cual se revisan los embalajes
* @param vCompanyFk Empresa de la cual se comprobaran sus clientes
* @param vWithoutPeriodGrace si no se aplica el periodo de gracia de un mes
*/
DECLARE vNewTicket INT;
DECLARE vDateStart DATE;
DECLARE vDateEnd DATE;
DECLARE vGraceDate DATE DEFAULT vDated;
DECLARE vWarehouseInventory INT;
DECLARE vComponentCost INT;
DECLARE vDone INT DEFAULT FALSE;
DECLARE vClientId INT;
DECLARE vCursor CURSOR FOR
SELECT DISTINCT clientFk
FROM (
SELECT clientFk, SUM(quantity) totalQuantity
FROM tmp.packagingToInvoice
GROUP BY itemFk, clientFk
HAVING totalQuantity > 0)sub;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
SELECT id INTO vWarehouseInventory
FROM warehouse
WHERE `code`= 'inv';
SELECT id INTO vComponentCost
FROM component
WHERE `code`= 'purchaseValue';
SELECT packagingInvoicingDated INTO vDateStart
FROM ticketConfig;
IF vWarehouseInventory IS NULL THEN
CALL util.throw('Warehouse inventory not set');
END IF;
IF vComponentCost IS NULL THEN
CALL util.throw('Component cost not set');
END IF;
SET vDateEnd = vDated + INTERVAL 1 DAY;
IF NOT vWithoutPeriodGrace THEN
SET vGraceDate = vGraceDate -INTERVAL 1 MONTH;
END IF;
DROP TEMPORARY TABLE IF EXISTS tmp.packagingToInvoice;
CREATE TEMPORARY TABLE tmp.packagingToInvoice
(INDEX (clientFk))
ENGINE = MEMORY
SELECT p.itemFk,
tp.packagingFk,
tp.quantity,
tp.ticketFk,
p.price,
t.clientFk
FROM ticketPackaging tp
JOIN packaging p ON p.id = tp.packagingFk
JOIN ticket t ON t.id = tp.ticketFk
JOIN client c ON c.id = t.clientFk
WHERE c.isActive
AND (vClientFk IS NULL OR t.clientFk = vClientFk)
AND t.shipped BETWEEN vDateStart AND vDateEnd
AND (tp.quantity < 0 OR (tp.quantity > 0 AND t.shipped < vGraceDate))
AND tp.quantity
AND p.itemFk;
OPEN vCursor;
l: LOOP
FETCH vCursor INTO vClientId;
IF vDone THEN
LEAVE l;
END IF;
START TRANSACTION;
CALL ticket_add(
vClientId,
vDateEnd,
vWarehouseInventory,
vCompanyFk,
NULL,
NULL,
NULL,
vDateEnd,
account.myUser_getId(),
TRUE,
vNewTicket);
INSERT INTO ticketPackaging(ticketFk, packagingFk, quantity, pvp)
SELECT vNewTicket, packagingFk, - SUM(quantity) totalQuantity, price
FROM tmp.packagingToInvoice
WHERE clientFk = vClientId
GROUP BY packagingFk
HAVING IF(vWithoutPeriodGrace, totalQuantity <> 0, totalQuantity < 0);
INSERT INTO sale(ticketFk, itemFk, concept, quantity, price)
SELECT vNewTicket, pti.itemFk, i.name, SUM(pti.quantity) totalQuantity, pti.price
FROM tmp.packagingToInvoice pti
JOIN item i ON i.id = pti.itemFk
WHERE pti.clientFk = vClientId
GROUP BY pti.itemFk
HAVING IF(vWithoutPeriodGrace, totalQuantity <> 0, totalQuantity > 0);
INSERT INTO saleComponent(saleFk, componentFk, value)
SELECT id, vComponentCost, price
FROM sale
WHERE ticketFk = vNewTicket;
COMMIT;
END LOOP;
CLOSE vCursor;
DROP TEMPORARY TABLE tmp.packagingToInvoice;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketParking_findSkipped` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketParking_findSkipped`(vTicketFk INT, vItemPackingTypeFk VARCHAR(1))
BEGIN
/**
* Averigua los tickets que se han saltado por un error en el proceso encajado
* @param vTicketFk Ticket
* @param vItemPackingTypeFk Modo de encajado
* @return un select con los tickets afectados
*/
DECLARE vParkingFk INT;
DECLARE vParked DATETIME;
DECLARE vLevel INT;
DECLARE vWagon INT;
DECLARE vCollectionFk INT;
SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0)
INTO vLevel, vWagon, vCollectionFk
FROM vn.ticketCollection tc
JOIN vn.collection c ON c.id = tc.collectionFk AND c.itemPackingTypeFk = vItemPackingTypeFk
WHERE ticketFk = vTicketFk
ORDER BY c.id DESC
LIMIT 1;
SELECT created, parkingFk
INTO vParked, vParkingFk
FROM vn.ticketParking tp
JOIN vn.parking p ON p.id = tp.parkingFk
JOIN vn.sector s ON s.id = p.sectorFk
WHERE ticketFk = vTicketFk
AND s.itemPackingTypeFk = vItemPackingTypeFk
AND s.isPackagingArea ;
SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' ', tc.wagon, ' - ', 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.ticketFk = 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.wagon,1) < LEFT(vWagon,1)
OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1)))
)
)
) -- Etiquetas que no se han escaneado y ya estamos con una posterior
OR
(s.alertLevel > 1
AND tp.parkingFk = vParkingFk
AND sc.isPackagingArea
AND tp.created < vParked
AND t.packages <=> 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketRefund_beforeUpsert` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketRefund_beforeUpsert`(vRefundTicketFk INT, vOriginalTicketFk INT)
BEGIN
DECLARE vAlreadyExists BOOLEAN DEFAULT FALSE;
IF vRefundTicketFk = vOriginalTicketFk THEN
CALL util.throw('Original ticket and refund ticket has same id');
END IF;
SELECT COUNT(*) INTO vAlreadyExists
FROM ticketRefund
WHERE refundTicketFk = vOriginalTicketFk;
IF vAlreadyExists > 0 THEN
CALL util.throw('This ticket is already a refund');
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketStateToday_setState` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketStateToday_setState`(vTicketFk INT, vStateCode VARCHAR(45))
BEGIN
/* Modifica el estado de un ticket de hoy
*
* @param vTicketFk el id del ticket
* @param vStateCode estado a modificar del ticket
*
*/
DECLARE vAlertLevel INT;
SELECT s.alertLevel INTO vAlertLevel
FROM state s
JOIN ticketStateToday tst ON tst.state = s.id
WHERE tst.ticketFk = vTicketFk
LIMIT 1;
IF vAlertLevel < 2 THEN
CALL vn.ticket_setState(vTicketFk, vStateCode);
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketStateUpdate`(vTicketFk INT, vStateCode VARCHAR(45))
BEGIN
/*
* @deprecated:utilizar ticket_setState
*/
DECLARE vAlertLevel INT;
SELECT s.alertLevel INTO vAlertLevel
FROM vn.state s
JOIN vn.ticketState ts ON ts.stateFk = s.id
WHERE ts.ticketFk = vTicketFk;
IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN
INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
SELECT id, vTicketFk, account.myUser_getId()
FROM vn.state
WHERE `code` = vStateCode 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketToInvoiceByAddress`(
vStarted DATE,
vEnded DATETIME,
vAddress INT,
vCompany INT
)
BEGIN
SET vEnded = util.dayEnd(vEnded);
DROP TEMPORARY TABLE IF EXISTS tmp.ticketToInvoice;
CREATE TEMPORARY TABLE tmp.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketToInvoiceByDate`(
vStarted DATE,
vEnded DATETIME,
vClient INT,
vCompany INT
)
BEGIN
SET vEnded = util.dayEnd(vEnded);
DROP TEMPORARY TABLE IF EXISTS tmp.ticketToInvoice;
CREATE TEMPORARY TABLE tmp.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 tmp.ticketToInvoice;
CREATE TEMPORARY TABLE tmp.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_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 = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_add`(
vClientId INT
,vShipped DATE
,vWarehouseFk INT
,vCompanyFk INT
,vAddressFk INT
,vAgencyModeFk INT
,vRouteFk INT
,vlanded DATE
,vUserId INT
,vIsRequiredZone INT
,OUT vNewTicket INT)
BEGIN
/**
* Crea un ticket,
* ¡¡NO se debe llamar directamente, llamar a salix que hace comprobaciones previas!!
*
* @param vClientId id del cliente
* @param vShipped dia preparacion
* @param vWarehouseFk id del warehouse
* @param vCompanyFk id la empresa
* @param vAddressFk id del consignatario
* @param vAgencyModeFk id de la agencia
* @param vRouteFk id de la ruta | NULL
* @param vlanded dia llegada
* @param vUserId que crea el ticket
* @param vIsRequiredZone Indica si tiene que tener zona valida para ser creado
* @return vNewTicket id del ticket creado
*/
DECLARE vZoneFk INT;
DECLARE vPrice DECIMAL(10,2);
DECLARE vBonus DECIMAL(10,2);
DECLARE vIsActive BOOL;
IF vClientId IS NULL THEN
CALL util.throw ('CLIENT_NOT_ESPECIFIED');
END IF;
SELECT isActive INTO vIsActive
FROM vn.client
WHERE id = vClientId;
IF NOT vIsActive THEN
CALL util.throw ('CLIENT_NOT_ACTIVE');
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_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE);
SELECT zoneFk, price, bonus
INTO vZoneFk, vPrice, vBonus
FROM tmp.zoneGetShipped
WHERE shipped = vShipped
AND warehouseFk = vWarehouseFk
LIMIT 1;
IF (vZoneFk IS NULL OR vZoneFk = 0) AND vIsRequiredZone 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,
zonePrice,
zoneBonus
)
SELECT vClientId,
vShipped,
a.id,
vAgencyModeFk,
a.nickname,
vWarehouseFk,
IF(vRouteFk,vRouteFk,NULL),
vCompanyFk,
vlanded,
vZoneFk,
vPrice,
vBonus
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;
IF (SELECT COUNT(*)
FROM bs.clientNewBorn cnb
WHERE cnb.clientFk = vClientId
AND NOT cnb.isRookie) = 0 THEN
CALL vn.ticketObservation_addNewBorn(vNewTicket);
END IF;
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 ticketTracking(stateFk, ticketFk, userFk)
SELECT id, vNewTicket, account.myUser_getId()
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_administrativeCopy` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_administrativeCopy`(vOriginalTicket INT, OUT vNewTicket INT)
BEGIN
INSERT INTO vn.ticket(clientFk, addressFk, shipped, warehouseFk, companyFk, landed)
SELECT t.clientFk , t.addressFk , t.shipped ,w.id, t.companyFk , t.landed
FROM vn.ticket t
JOIN vn.warehouse w ON w.name = 'INVENTARIO'
WHERE t.id = vOriginalTicket;
SELECT LAST_INSERT_ID() INTO vNewTicket;
INSERT INTO vn.sale(ticketFk, itemFk, concept, quantity, price, discount)
SELECT vNewTicket, s.itemFk , s.concept , s.quantity , s.price , s.discount
FROM vn.sale s
WHERE s.ticketFk = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_canAdvance` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT)
BEGIN
/**
* Devuelve los tickets y la cantidad de lineas de venta que se pueden adelantar.
*
* @param vDateFuture Fecha de los tickets que se quieren adelantar.
* @param vDateToAdvance Fecha a cuando se quiere adelantar.
* @param vWarehouseFk Almacén
*/
CALL item_getStock(vWarehouseFk, vDateToAdvance, NULL);
CALL item_getMinacum(
vWarehouseFk,
vDateToAdvance,
DATEDIFF(DATE_SUB(vDateFuture, INTERVAL 1 DAY), vDateToAdvance),
NULL
);
CREATE OR REPLACE TEMPORARY TABLE tmp.filter
(INDEX (id))
SELECT
origin.ticketFk futureId,
dest.ticketFk id,
dest.state,
origin.futureState,
origin.futureIpt,
dest.ipt,
origin.workerFk,
origin.futureLiters,
origin.futureLines,
dest.shipped,
origin.shipped futureShipped,
dest.totalWithVat,
origin.totalWithVat futureTotalWithVat,
dest.agency,
dest.agencyModeFk,
origin.futureAgency,
origin.agencyModeFk futureAgencyModeFk,
dest.lines,
dest.liters,
origin.futureLines - origin.hasStock AS notMovableLines,
(origin.futureLines = origin.hasStock) AS isFullMovable,
dest.zoneFk,
origin.futureZoneFk,
origin.futureZoneName,
origin.classColor futureClassColor,
dest.classColor,
origin.clientFk futureClientFk,
origin.addressFk futureAddressFk,
origin.warehouseFk futureWarehouseFk,
origin.companyFk futureCompanyFk,
IFNULL(dest.nickname, origin.nickname) nickname,
dest.landed
FROM (
SELECT
s.ticketFk,
c.salesPersonFk workerFk,
t.shipped,
t.totalWithVat,
st.name futureState,
am.name futureAgency,
count(s.id) futureLines,
GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt,
CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters,
SUM(s.quantity <= (IFNULL(il.stock,0) + IFNULL(im.amount, 0))) hasStock,
z.id futureZoneFk,
z.name futureZoneName,
st.classColor,
t.clientFk,
t.nickname,
t.addressFk,
t.warehouseFk,
t.companyFk,
t.agencyModeFk
FROM ticket t
JOIN client c ON c.id = t.clientFk
JOIN sale s ON s.ticketFk = t.id
JOIN saleVolume sv ON sv.saleFk = s.id
JOIN item i ON i.id = s.itemFk
JOIN ticketState ts ON ts.ticketFk = t.id
JOIN state st ON st.id = ts.stateFk
JOIN agencyMode am ON t.agencyModeFk = am.id
JOIN zone z ON t.zoneFk = z.id
LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
LEFT JOIN tmp.itemMinacum im ON im.itemFk = i.id
AND im.warehouseFk = vWarehouseFk
LEFT JOIN tmp.itemList il ON il.itemFk = i.id
WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture)
AND t.warehouseFk = vWarehouseFk
GROUP BY t.id
) origin
LEFT JOIN (
SELECT
t.id ticketFk,
st.name state,
GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) ipt,
t.shipped,
t.totalWithVat,
am.name agency,
CAST(SUM(litros) AS DECIMAL(10,0)) liters,
CAST(COUNT(*) AS DECIMAL(10,0)) `lines`,
st.classColor,
t.clientFk,
t.nickname,
t.addressFk,
t.zoneFk,
t.warehouseFk,
t.companyFk,
t.landed,
t.agencyModeFk
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN saleVolume sv ON sv.saleFk = s.id
JOIN item i ON i.id = s.itemFk
JOIN ticketState ts ON ts.ticketFk = t.id
JOIN state st ON st.id = ts.stateFk
JOIN agencyMode am ON t.agencyModeFk = am.id
LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
WHERE t.shipped BETWEEN vDateToAdvance AND util.dayend(vDateToAdvance)
AND t.warehouseFk = vWarehouseFk
AND st.order <= 5
GROUP BY t.id
) dest ON dest.addressFk = origin.addressFk
WHERE origin.hasStock;
DROP TEMPORARY TABLE IF EXISTS
tmp.itemList,
tmp.itemMinacum;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_canbePostponed` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_canbePostponed`(vOriginDated DATE, vFutureDated DATE, vWarehouseFk INT)
BEGIN
/**
* Devuelve un listado de tickets susceptibles de fusionarse con otros tickets en el futuro
*
* @param vOriginDated Fecha en cuestión
* @param vFutureDated Fecha en el futuro a sondear
* @param vWarehouseFk Identificador de vn.warehouse
*/
CREATE OR REPLACE TEMPORARY TABLE tmp.filter
(INDEX (id))
SELECT sv.ticketFk id,
sub2.id futureId,
GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt,
CAST(sum(litros) AS DECIMAL(10,0)) liters,
CAST(count(*) AS DECIMAL(10,0)) `lines`,
st.name state,
sub2.iptd futureIpt,
sub2.state futureState,
t.clientFk,
t.warehouseFk,
ts.alertLevel,
t.shipped,
t.totalWithVat,
sub2.shipped futureShipped,
t.workerFk,
st.code stateCode,
sub2.code futureStateCode,
st.classColor,
sub2.classColor futureClassColor
FROM vn.saleVolume sv
JOIN vn.sale s ON s.id = sv.saleFk
JOIN vn.item i ON i.id = s.itemFk
JOIN vn.ticket t ON t.id = sv.ticketFk
JOIN vn.address a ON a.id = t.addressFk
JOIN vn.province p ON p.id = a.provinceFk
JOIN vn.country c ON c.id = p.countryFk
JOIN vn.ticketState ts ON ts.ticketFk = t.id
JOIN vn.state st ON st.id = ts.stateFk
JOIN vn.alertLevel al ON al.id = ts.alertLevel
LEFT JOIN vn.ticketParking tp ON tp.ticketFk = t.id
LEFT JOIN (
SELECT *
FROM (
SELECT
t.addressFk,
t.id,
t.shipped,
st.name state,
st.code,
st.classColor,
GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) iptd
FROM vn.ticket t
JOIN vn.ticketState ts ON ts.ticketFk = t.id
JOIN vn.state st ON st.id = ts.stateFk
JOIN vn.sale s ON s.ticketFk = t.id
JOIN vn.item i ON i.id = s.itemFk
WHERE t.shipped BETWEEN vFutureDated
AND util.dayend(vFutureDated)
AND t.warehouseFk = vWarehouseFk
GROUP BY t.id
) sub
GROUP BY sub.addressFk
) sub2 ON sub2.addressFk = t.addressFk AND t.id != sub2.id
WHERE t.shipped BETWEEN vOriginDated AND util.dayend(vOriginDated)
AND t.warehouseFk = vWarehouseFk
AND al.code = 'FREE'
AND tp.ticketFk IS NULL
GROUP BY sv.ticketFk
HAVING futureId;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_canMerge` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_canMerge`(vDated DATE, vScopeDays INT, vLitersMax INT, vLinesMax INT, vWarehouseFk INT)
BEGIN
/**
* Devuelve un listado de tickets susceptibles de fusionarse con otros tickets en el futuro
*
* @param vDated Fecha en cuestión
* @param vScopeDays Dias en el futuro a sondear
* @param vLitersMax Volumen máximo de los tickets a catapultar
* @param vLinesMax Número máximo de lineas de los tickets a catapultar
* @param vWarehouseFk Identificador de vn.warehouse
*/
SELECT sv.ticketFk,
GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt,
CAST(SUM(litros) AS DECIMAL(10,0)) liters,
CAST(COUNT(*) AS DECIMAL(10,0)) `lines`,
st.name state,
sub2.id ticketFuture,
sub2.shipped,
sub2.iptd tfIpt,
sub2.state tfState
FROM vn.saleVolume sv
JOIN vn.sale s ON s.id = sv.saleFk
JOIN vn.item i ON i.id = s.itemFk
JOIN vn.ticket t ON t.id = sv.ticketFk
JOIN vn.address a ON a.id = t.addressFk
JOIN vn.province p ON p.id = a.provinceFk
JOIN vn.country c ON c.id = p.countryFk
JOIN vn.ticketState ts ON ts.ticketFk = t.id
JOIN vn.state st ON st.id = ts.stateFk
JOIN vn.alertLevel al ON al.id = ts.alertLevel
LEFT JOIN vn.ticketParking tp ON tp.ticketFk = t.id
LEFT JOIN (
SELECT *
FROM (
SELECT t.addressFk,
t.id,
t.shipped,
st.name state,
GROUP_CONCAT(DISTINCT i.itemPackingTypeFk
ORDER BY i.itemPackingTypeFk) iptd
FROM vn.ticket t
JOIN vn.ticketState ts ON ts.ticketFk = t.id
JOIN vn.state st ON st.id = ts.stateFk
JOIN vn.sale s ON s.ticketFk = t.id
JOIN vn.alertLevel al ON al.id = st.alertLevel
JOIN vn.item i ON i.id = s.itemFk
WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, vScopeDays,vDated)
AND util.dayend(TIMESTAMPADD(DAY, vScopeDays,vDated))
AND t.warehouseFk = vWarehouseFk
AND al.code = 'FREE'
GROUP BY t.id
) sub
GROUP BY sub.addressFk
) sub2 ON sub2.addressFk = t.addressFk AND t.id != sub2.id
WHERE t.shipped BETWEEN vDated AND util.dayend(vDated)
AND t.warehouseFk = vWarehouseFk
AND al.code = 'FREE'
AND tp.ticketFk IS NULL
GROUP BY sv.ticketFk
HAVING liters <= vLitersMax
AND `lines` <= vLinesMax
AND ticketFuture;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_checkNoComponents` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_checkNoComponents`(vShippedFrom DATETIME, vShippedTo DATETIME)
BEGIN
/**
* Comprueba que los tickets entre un rango de fechas tienen componentes
* y recalcula sus componentes
*
* @param vShippedFrom rango inicial de fecha
* @param vShippedTo rango final de fecha
*/
CREATE OR REPLACE TEMPORARY TABLE tmp.coste
(primary key (id)) ENGINE = MEMORY
SELECT s.id
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
JOIN itemType tp ON tp.id = i.typeFk
JOIN itemCategory ic ON ic.id = tp.categoryFk
JOIN saleComponent sc ON sc.saleFk = s.id
JOIN component c ON c.id = sc.componentFk
JOIN componentType ct ON ct.id = c.typeFk AND ct.id = 1
WHERE t.shipped BETWEEN vShippedFrom AND vShippedTo
AND ic.merchandise;
CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales
(primary key (id)) ENGINE = MEMORY
SELECT DISTINCT s.id
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
JOIN itemType tp ON tp.id = i.typeFk
JOIN itemCategory ic ON ic.id = tp.categoryFk
LEFT JOIN tmp.coste c ON c.id = s.id
WHERE t.shipped >= vShippedFrom AND t.shipped <= vShippedTo
AND c.id IS NULL
AND ic.merchandise;
CALL sale_recalcComponent('renewPrices');
DROP TEMPORARY TABLE tmp.recalculateSales;
DROP TEMPORARY TABLE tmp.coste;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_Clone`(vOriginalTicket INT, OUT vNewTicket INT)
BEGIN
/**
* Clona el contenido de un ticket en otro
*
* @param vOriginalTicket ticket Original
* @param vNewTicket ticket creado
*/
DECLARE vStateFk INT;
INSERT INTO ticket (
clientFk,
shipped,
addressFk,
agencyModeFk,
nickname,
warehouseFk,
companyFk,
landed,
zoneFk,
zonePrice,
zoneBonus,
routeFk,
priority,
hasPriority,
clonedFrom
)
SELECT
clientFk,
shipped,
addressFk,
agencyModeFk,
nickname,
warehouseFk,
companyFk,
landed,
zoneFk,
zonePrice,
zoneBonus,
routeFk,
priority,
hasPriority,
vOriginalTicket
FROM ticket
WHERE id = vOriginalTicket;
SET vNewTicket = LAST_INSERT_ID();
INSERT INTO ticketObservation(ticketFk, observationTypeFk, description)
SELECT vNewTicket, observationTypeFk, description
FROM ticketObservation
WHERE ticketFk = vOriginalTicket;
INSERT INTO ticketTracking(ticketFk, stateFk, userFk, created)
SELECT vNewTicket, stateFk, userFk, created
FROM ticketTracking
WHERE ticketFk = vOriginalTicket
ORDER BY created;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_cloneAll` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_cloneAll`(vTicketFk INT, vNewShipped DATE, vWithWarehouse BOOLEAN, OUT vNewTicketFk INT)
BEGIN
DECLARE vDone BOOLEAN DEFAULT FALSE;
DECLARE vOldSaleFk INT;
DECLARE vNewSaleFk INT;
DECLARE cur1 CURSOR FOR
SELECT id
FROM sale
WHERE ticketFk = vTicketFk;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SET vNewShipped = IFNULL(vNewShipped, util.VN_CURDATE());
CALL ticket_Clone(vTicketFk, vNewTicketFk);
UPDATE ticket
SET landed = TIMESTAMPADD(DAY, DATEDIFF(vNewShipped, shipped), landed),
shipped = vNewShipped,
warehouseFk = IF(vWithWarehouse, warehouseFk, NULL)
WHERE id = vNewTicketFk;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO vOldSaleFk;
IF vDone THEN
LEAVE read_loop;
END IF;
INSERT INTO sale(ticketFk, itemFk, quantity, concept, price, discount, priceFixed, isPriceFixed)
SELECT vNewTicketFk, itemFk, quantity, concept, price, discount, priceFixed, isPriceFixed
FROM sale
WHERE id = vOldSaleFk;
SELECT max(id) INTO vNewSaleFk
FROM sale
WHERE ticketFk = vNewTicketFk;
INSERT INTO saleComponent(saleFk, componentFk, value, isGreuge)
SELECT vNewSaleFk, componentFk, value, isGreuge
FROM saleComponent
WHERE saleFk = vOldSaleFk;
END LOOP;
CLOSE cur1;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_cloneWeekly` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_cloneWeekly`(vDateFrom DATE, vDateTo DATE)
BEGIN
DECLARE vIsDone BOOL;
DECLARE vLanding DATE;
DECLARE vShipment DATE;
DECLARE vWarehouseFk INT;
DECLARE vTicketFk INT;
DECLARE vClientFk INT;
DECLARE vCompanyFk INT;
DECLARE vAddressFk INT;
DECLARE vAgencyModeFk INT;
DECLARE vNewTicket INT;
DECLARE vYear INT;
DECLARE vSalesPersonFK INT;
DECLARE vItemPicker INT;
DECLARE rsTicket CURSOR FOR
SELECT tt.ticketFk,
t.clientFk,
t.warehouseFk,
t.companyFk,
t.addressFk,
tt.agencyModeFk,
ti.dated
FROM ticketWeekly tt
JOIN ticket t ON tt.ticketFk = t.id
JOIN tmp.time ti
WHERE WEEKDAY(ti.dated) = tt.weekDay;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE;
CALL `util`.`time_generate`(vDateFrom,vDateTo);
OPEN rsTicket;
myLoop: LOOP
BEGIN
DECLARE vSalesPersonEmail VARCHAR(150);
DECLARE vIsDuplicateMail BOOL;
DECLARE vSubject VARCHAR(150);
DECLARE vMessage TEXT;
SET vIsDone = FALSE;
FETCH rsTicket INTO vTicketFk,vClientFk, vWarehouseFk, vCompanyFk, vAddressFk, vAgencyModeFk,vShipment;
IF vIsDone THEN
LEAVE myLoop;
END IF;
-- busca si el ticket ya ha sido clonado
IF EXISTS (SELECT TRUE FROM ticket tOrig
JOIN sale saleOrig ON tOrig.id = saleOrig.ticketFk
JOIN saleCloned sc ON sc.saleOriginalFk = saleOrig.id
JOIN sale saleClon ON saleClon.id = sc.saleClonedFk
JOIN ticket tClon ON tClon.id = saleClon.ticketFk
WHERE tOrig.id = vTicketFk
AND tClon.isDeleted = FALSE
AND DATE(tClon.shipped) = vShipment)
THEN
ITERATE myLoop;
END IF;
IF vAgencyModeFk IS NULL THEN
SELECT agencyModeFk INTO vAgencyModeFk
FROM address
WHERE clientFk = vClientFk
AND isDefaultAddress;
END IF;
CALL zone_getLanded(vShipment, vAddressFk, vAgencyModeFk, vWarehouseFk,FALSE);
SET vLanding = NULL;
SELECT landed INTO vLanding FROM tmp.zoneGetLanded LIMIT 1;
CALL ticket_add(
vClientFk,
vShipment,
vWarehouseFk,
vCompanyFk,
vAddressFk,
vAgencyModeFk,
NULL,
vLanding,
account.myUser_getId(),
FALSE,
vNewTicket);
UPDATE ticket
SET clonedFrom = vTicketFk
WHERE id = vNewTicket;
INSERT INTO sale (ticketFk, itemFk, concept, quantity, price,
discount, priceFixed, isPriceFixed)
SELECT vNewTicket,
saleOrig.itemFk,
saleOrig.concept,
saleOrig.quantity,
saleOrig.price,
saleOrig.discount,
saleOrig.priceFixed,
saleOrig.isPriceFixed
FROM sale saleOrig
WHERE saleOrig.ticketFk = vTicketFk;
INSERT IGNORE INTO saleCloned(saleOriginalFk, saleClonedFk)
SELECT saleOriginal.id, saleClon.id
FROM sale saleOriginal
JOIN sale saleClon ON saleOriginal.itemFk = saleClon.itemFk
AND saleOriginal.quantity = saleClon.quantity
WHERE saleOriginal.ticketFk = vTicketFk
AND saleClon.ticketFk = vNewTicket;
INSERT INTO ticketRequest (description,
ordered,
shipped,
quantity,
price,
itemFk,
clientFk,
response,
total,
buyed,
requesterFk
,attenderFk,
ticketFk)
SELECT description,
ordered,
shipped,
quantity,
price,
itemFk,
clientFk,
response,
total,
buyed,
requesterFk,
attenderFk,
vNewTicket
FROM ticketRequest
WHERE ticketFk =vTicketFk;
SELECT id INTO vSalesPersonFK
FROM observationType
WHERE code = 'salesPerson';
SELECT id INTO vItemPicker
FROM observationType
WHERE code = 'itemPicker';
INSERT INTO ticketObservation(
ticketFk,
observationTypeFk,
description)
VALUES(
vNewTicket,
vSalesPersonFK,
CONCAT('turno desde ticket: ',vTicketFk))
ON DUPLICATE KEY UPDATE description =
CONCAT(ticketObservation.description,VALUES(description),' ');
INSERT INTO ticketObservation(ticketFk,
observationTypeFk,
description)
VALUES(
vNewTicket,
vItemPicker,
'ATENCION: Contiene lineas de TURNO')
ON DUPLICATE KEY UPDATE description =
CONCAT(ticketObservation.description,VALUES(description),' ');
IF (vLanding IS NULL) THEN
SELECT e.email INTO vSalesPersonEmail
FROM client c
JOIN account.emailUser e ON e.userFk = c.salesPersonFk
WHERE c.id = vClientFk;
SET vSubject = CONCAT('Turnos - No se ha podido clonar correctamente el ticket ',
vTicketFk,' para el dia: ', vShipment);
SET vMessage = CONCAT('No se ha podido clonar el ticket ', vTicketFk,
' para el dia: ', vShipment,
' porque no hay una zona de envío disponible. Se ha creado el ticket: ',
vNewTicket, ' pero ha que revisar las fechas y la agencia');
SELECT COUNT(*) INTO vIsDuplicateMail
FROM mail
WHERE receiver = vSalesPersonEmail
AND subject = vSubject;
IF NOT vIsDuplicateMail THEN
CALL mail_insert(vSalesPersonEmail, NULL, vSubject, vMessage);
END IF;
CALL ticketStateUpdate (vNewTicket, 'FIXING');
ELSE
CALL ticketCalculateClon(vNewTicket, vTicketFk);
END IF;
END;
END LOOP;
CLOSE rsTicket;
DROP TEMPORARY TABLE IF EXISTS tmp.time;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_close` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_close`()
BEGIN
/**
* Realiza el cierre de todos los
* tickets de la tabla tmp.ticket_close.
*
* @table tmp.ticket_close(ticketFk) Identificadores de los tickets a cerrar
*/
DECLARE vDone BOOL;
DECLARE vClientFk INT;
DECLARE vCurTicketFk INT;
DECLARE vIsTaxDataChecked BOOL;
DECLARE vCompanyFk INT;
DECLARE vShipped DATE;
DECLARE vNewInvoiceId INT;
DECLARE vHasDailyInvoice BOOL;
DECLARE vWithPackage BOOL;
DECLARE vHasToInvoice BOOL;
DECLARE cur CURSOR FOR
SELECT ticketFk FROM tmp.ticket_close;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN
RESIGNAL;
END;
OPEN cur;
proc: LOOP
SET vDone = FALSE;
FETCH cur INTO vCurTicketFk;
IF vDone THEN
LEAVE proc;
END IF;
SELECT
c.id,
c.isTaxDataChecked,
t.companyFk,
t.shipped,
IFNULL(a.hasDailyInvoice, co.hasDailyInvoice),
w.isManaged,
c.hasToInvoice
INTO vClientFk,
vIsTaxDataChecked,
vCompanyFk,
vShipped,
vHasDailyInvoice,
vWithPackage,
vHasToInvoice
FROM ticket t
JOIN `client` c ON c.id = t.clientFk
JOIN province p ON p.id = c.provinceFk
LEFT JOIN autonomy a ON a.id = p.autonomyFk
JOIN country co ON co.id = p.countryFk
JOIN warehouse w ON w.id = t.warehouseFk
WHERE t.id = vCurTicketFk;
INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity)
(SELECT vCurTicketFk, p.id, COUNT(*)
FROM expedition e
JOIN packaging p ON p.id = e.packagingFk
WHERE e.ticketFk = vCurTicketFk 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.freightItemFk, vCurTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.freightItemFk, vClientFk), 1
FROM expedition e
JOIN item i ON i.id = e.freightItemFk
LEFT JOIN packaging p ON p.itemFk = i.id
WHERE e.ticketFk = vCurTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0
AND getSpecialPrice(e.freightItemFk, vClientFk) > 0
GROUP BY e.freightItemFk);
IF(vHasDailyInvoice) AND vHasToInvoice THEN
-- Facturacion rapida
CALL ticket_setState(vCurTicketFk, 'DELIVERED');
-- Facturar si está contabilizado
IF vIsTaxDataChecked THEN
CALL invoiceOut_newFromClient(
vClientFk,
(SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')),
vShipped,
vCompanyFk,
NULL,
NULL,
vNewInvoiceId);
END IF;
ELSE
CALL ticket_setState(vCurTicketFk, (SELECT vn.getAlert3State(vCurTicketFk)));
END IF;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_closeByTicket` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_closeByTicket`(IN vTicketFk int)
BEGIN
/**
* Inserta el ticket en la tabla temporal
* para ser cerrado.
*
* @param vTicketFk Id del ticket
*/
DROP TEMPORARY TABLE IF EXISTS tmp.ticket_close;
CREATE TEMPORARY TABLE tmp.ticket_close ENGINE = MEMORY (
SELECT
t.id AS ticketFk
FROM ticket t
JOIN agencyMode am ON am.id = t.agencyModeFk
LEFT JOIN ticketState ts ON ts.ticketFk = t.id
JOIN alertLevel al ON al.id = ts.alertLevel
WHERE (al.code = 'PACKED' OR (am.code = 'refund' AND al.code != 'delivered'))
AND t.id = vTicketFk
AND t.refFk IS NULL
GROUP BY t.id
);
CALL ticket_close();
DROP TEMPORARY TABLE tmp.ticket_close;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_componentMakeUpdate`(
vTicketFk INT,
vClientFk INT,
vNickname VARCHAR(50),
vAgencyModeFk INT,
vAddressFk INT,
vZoneFk INT,
vWarehouseFk INT,
vCompanyFk INT,
vShipped DATETIME,
vLanded DATE,
vIsDeleted BOOLEAN,
vHasToBeUnrouted BOOLEAN,
vOption VARCHAR(25))
BEGIN
/**
* Modifica en el ticket los campos que se le pasan por parámetro
* y cambia sus componentes
*
* @param vTicketFk Id del ticket a modificar
* @param vClientFk nuevo cliente
* @param vNickname nuevo alias
* @param vAgencyModeFk nueva agencia
* @param vAddressFk nuevo consignatario
* @param vZoneFk nueva zona
* @param vWarehouseFk nuevo almacen
* @param vCompanyFk nueva empresa
* @param vShipped nueva fecha del envio de mercancia
* @param vLanded nueva fecha de recepcion de mercancia
* @param vIsDeleted si se borra el ticket
* @param vHasToBeUnrouted si se le elimina la ruta al ticket
* @param vOption opcion para el case del proc ticketComponentUpdateSale
*/
DECLARE vPrice DECIMAL(10,2);
DECLARE vBonus DECIMAL(10,2);
CALL ticket_componentPreview (vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk);
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;
CALL zone_getShipped(vLanded, vAddressFk, vAgencyModeFk, TRUE);
SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus
FROM tmp.zoneGetShipped
WHERE shipped BETWEEN DATE(vShipped) AND util.dayEnd(vShipped) AND warehouseFk = vWarehouseFk LIMIT 1;
UPDATE ticket t
SET
t.clientFk = vClientFk,
t.nickname = vNickname,
t.agencyModeFk = vAgencyModeFk,
t.addressFk = vAddressFk,
t.zoneFk = vZoneFk,
t.zonePrice = vPrice,
t.zoneBonus = vBonus,
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;
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;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent;
CREATE TEMPORARY TABLE tmp.ticketComponent
SELECT * FROM tmp.ticketComponentPreview;
CALL ticketComponentUpdateSale (vOption);
DROP TEMPORARY TABLE tmp.sale;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent;
DROP TEMPORARY TABLE tmp.zoneGetShipped, tmp.ticketComponentPreview;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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.ticketComponentPreview (warehouseFk, itemFk, componentFk, cost)
*/
DECLARE vHasDataChanged BOOL DEFAULT FALSE;
DECLARE vHasAddressChanged BOOL;
DECLARE vHasZoneChanged BOOL DEFAULT FALSE;
DECLARE vHasWarehouseChanged BOOL DEFAULT FALSE;
DECLARE vShipped DATE;
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,
vZoneFk zoneFk
FROM sale s
LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
WHERE s.ticketFk = vTicketFk
GROUP BY bu.warehouseFk, bu.itemFk);
CALL catalog_componentPrepare();
CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk);
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))));
DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPreview;
CREATE TEMPORARY TABLE tmp.ticketComponentPreview
SELECT * FROM tmp.ticketComponent;
CALL catalog_componentPurge();
DROP TEMPORARY TABLE tmp.buyUltimate;
IF vShipped IS NULL THEN
CALL util.throw('NO_ZONE_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_DelayTruck` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_DelayTruck`(vWarehouserFk INT, vHour INT, vMinute INT)
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE vTicketFk INT;
DECLARE cur1 CURSOR FOR SELECT ticketFk FROM tmp.ticket;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
CALL vn.productionControl(vWarehouserFk,0) ;
DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
CREATE TEMPORARY TABLE tmp.ticket
SELECT ticketFk
FROM tmp.productionBuffer
WHERE shipped = util.VN_CURDATE()
AND problem LIKE '%I:%'
AND (HH <= vHour OR HH = vHour AND mm < vMinute)
AND alertLevel = 0;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO vTicketFk;
IF done THEN
LEAVE read_loop;
END IF;
CALL vn.ticket_DelayTruckSplit(vTicketFk);
END LOOP;
CLOSE cur1;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_DelayTruckSplit` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_DelayTruckSplit`(vTicketFk INT)
BEGIN
/**
* Splita las lineas de ticket que no estan ubicadas
*
* @param vTicketFk Id ticket
*/
DECLARE vNewTicketFk INT;
DECLARE vTotalLines INT;
DECLARE vLinesToSplit INT;
DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit;
SELECT COUNT(*) INTO vTotalLines
FROM sale
WHERE ticketFk = vTicketFk;
CREATE TEMPORARY TABLE tmp.SalesToSplit
SELECT s.id saleFk
FROM ticket t
JOIN sale s ON t.id = s.ticketFk
LEFT JOIN (
SELECT ish.itemFk itemFk,
SUM(ish.visible) visible,
s.warehouseFk warehouseFk
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
GROUP BY ish.itemFk,
s.warehouseFk
) issw ON issw.itemFk = s.itemFk
AND issw.warehouseFk = t.warehouseFk
WHERE s.quantity > IFNULL(issw.visible, 0)
AND s.quantity > 0
AND NOT s.isPicked
AND NOT s.reserved
AND t.id = vTicketFk;
SELECT COUNT(*) INTO vLinesToSplit
FROM tmp.SalesToSplit;
IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN
SET vNewTicketFk = vTicketFk;
ELSE
CALL ticket_Clone(vTicketFk, vNewTicketFk);
UPDATE sale s
JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id
SET s.ticketFk = vNewTicketFk;
END IF;
CALL ticketStateUpdate(vNewTicketFk, 'FIXING');
DROP TEMPORARY TABLE tmp.SalesToSplit;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_doCmr` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_doCmr`(vSelf INT)
BEGIN
/**
* Crea u actualiza la información del CMR asociado con
* un ticket específico en caso de que sea necesario.
*
* @param vSelf El id del ticket
*/
DECLARE vCmrFk, vPreviousCmrFk, vCurrentCmrFk INT;
SELECT cmrFk INTO vCmrFk
FROM ticket
WHERE id = vSelf;
CREATE OR REPLACE TEMPORARY TABLE tTicket
SELECT wo.firstName,
v.numberPlate,
com.id companyFk,
a.id addressFk,
c2.defaultAddressFk,
su.id supplierFk,
t.landed
FROM ticket t
JOIN ticketState ts ON ts.ticketFk = t.id
JOIN `state` s ON s.id = ts.stateFk
JOIN alertLevel al ON al.id = s.alertLevel
JOIN client c ON c.id = t.clientFk
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 agencyMode am ON am.id = t.agencyModeFk
JOIN warehouse w ON w.id = t.warehouseFk
JOIN company com ON com.id = t.companyFk
JOIN client c2 ON c2.id = com.clientFk
JOIN supplierAccount sa ON sa.id = com.supplierAccountFk
JOIN supplier su ON su.id = sa.supplierFk
LEFT JOIN route r ON r.id = t.routeFk
LEFT JOIN worker wo ON wo.id = r.workerFk
LEFT JOIN vehicle v ON v.id = r.vehicleFk
WHERE al.code IN ('PACKED', 'DELIVERED')
AND co.code <> 'ES'
AND am.name <> 'ABONO'
AND w.code = 'ALG'
AND t.id = vSelf
GROUP BY t.id;
START TRANSACTION;
IF vCmrFk THEN
UPDATE cmr c
JOIN tTicket t
SET c.senderInstruccions = t.firstName,
c.truckPlate = t.numberPlate,
c.companyFk = t.companyFk,
c.addressToFk = t.addressFk,
c.addressFromFk = t.defaultAddressFk,
c.supplierFk = t.supplierFk,
c.ead = t.landed
WHERE id = vCmrFk;
ELSE
SELECT MAX(id) INTO vPreviousCmrFk FROM cmr;
INSERT INTO cmr (
senderInstruccions,
truckPlate,
companyFk,
addressToFk,
addressFromFk,
supplierFk,
ead
)
SELECT * FROM tTicket;
SELECT MAX(id) INTO vCurrentCmrFk FROM cmr;
IF vPreviousCmrFk <> vCurrentCmrFk THEN
UPDATE ticket
SET cmrFk = vCurrentCmrFk
WHERE id = vSelf;
END IF;
END IF;
COMMIT;
DROP TEMPORARY TABLE tTicket;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_getFromFloramondo` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_getFromFloramondo`(vDateFrom DATE, vDateTo DATE)
BEGIN
/**
* Genera una tabla con la lista de tickets de Floramondo
* para una fecha determinada.
*
* @param vDated Fecha de preparación de los pedidos
* @table tmp.ticketFloramondo(ticketFk, clientName, agencyName,
* agencyModeFk, supplierName, supplierFk, freight, expeditionCount,
* margin, trolleys, pallets, shipped, created)
*/
DROP TEMPORARY TABLE IF EXISTS tmp.ticketFloramondo;
CREATE TEMPORARY TABLE tmp.ticketFloramondo
(ticketFk INT PRIMARY KEY,
clientName VARCHAR(50),
agencyName VARCHAR(50),
agencyModeFk INT,
supplierName VARCHAR(50),
supplierFk INT,
freight DECIMAL(10,2) DEFAULT 0,
expeditionCount INT,
margin DECIMAL(10,3) DEFAULT 0,
trolleys INT DEFAULT 0,
pallets INT DEFAULT 0,
shipped DATE,
created DATE)
ENGINE = MEMORY;
INSERT INTO tmp.ticketFloramondo(ticketFk,
clientName,
agencyName,
agencyModeFk,
shipped,
supplierName,
supplierFk,
created)
SELECT t.id ticketFk,
t.nickname,
am.name,
am.id,
t.shipped,
s.name,
sat.supplierFk,
t.created
FROM vn.ticket t
JOIN vn.agencyMode am ON am.id = t.agencyModeFk
JOIN vn.warehouse w ON w.id = t.warehouseFk
AND w.code IN ('VNH','FLM')
AND t.shipped BETWEEN vDateFrom AND util.dayend(vDateTo)
JOIN vn.agency a ON a.id = am.agencyFk
LEFT JOIN vn.supplierAgencyTerm sat ON sat.agencyFk = a.id
LEFT JOIN vn.supplier s ON s.id = sat.supplierFk;
DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
CREATE TEMPORARY TABLE tmp.ticket
(ticketFk INT(11) PRIMARY KEY)
SELECT ticketFk
FROM tmp.ticketFloramondo;
-- Freight
UPDATE tmp.ticketFloramondo tf
JOIN (SELECT SUM(sc.value * s.quantity) freight, t.ticketFk
FROM vn.saleComponent sc
JOIN vn.component c ON c.id = sc.componentFk
JOIN vn.componentType ct ON ct.id = c.typeFk
JOIN vn.sale s ON s.id = sc.saleFk
JOIN tmp.ticket t ON t.ticketFk = s.ticketFk
WHERE ct.code = 'FREIGHT'
GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk
SET tf.freight = sb.freight;
-- Freight service
UPDATE tmp.ticketFloramondo tf
JOIN (SELECT SUM(ts.price * ts.quantity) service, t.ticketFk
FROM vn.ticketService ts
JOIN tmp.ticket t ON t.ticketFk = ts.ticketFk
GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk
SET tf.freight = tf.freight + sb.service;
-- Expedition Count
UPDATE tmp.ticketFloramondo tf
JOIN (SELECT COUNT(e.id) expeditionCount, t.ticketFk
FROM vn.expedition e
RIGHT JOIN tmp.ticket t ON t.ticketFk = e.ticketFk
GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk
SET tf.expeditionCount = sb.expeditionCount;
-- Margin
UPDATE tmp.ticketFloramondo tf
JOIN (SELECT SUM(IF(ct.code = 'COST',sc.value, 0)) cost,
SUM(IF(ct.isMargin, sc.value, 0)) margin,
t.ticketFk
FROM vn.saleComponent sc
JOIN vn.component c ON c.id = sc.componentFk
JOIN vn.componentType ct ON ct.id = c.typeFk
JOIN vn.sale s ON s.id = sc.saleFk
JOIN tmp.ticket t ON t.ticketFk = s.ticketFk
GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk
SET tf.margin = sb.margin / sb.cost;
-- Trolleys
UPDATE tmp.ticketFloramondo tf
JOIN (SELECT SUM(tp.quantity) trolleys, t.ticketFk
FROM vn.ticketPackaging tp
JOIN tmp.ticket t ON t.ticketFk = tp.ticketFk
JOIN vn.packaging p ON p.id = tp.packagingFk
WHERE p.isTrolley
GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk
SET tf.trolleys = sb.trolleys;
-- Pallets
UPDATE tmp.ticketFloramondo tf
JOIN (SELECT SUM(tp.quantity) pallets, t.ticketFk
FROM vn.ticketPackaging tp
JOIN tmp.ticket t ON t.ticketFk = tp.ticketFk
JOIN vn.packaging p ON p.id = tp.packagingFk
WHERE p.isPallet
GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk
SET tf.pallets = sb.pallets;
SELECT * FROM tmp.ticketFloramondo;
DROP TEMPORARY TABLE tmp.ticket;
DROP TEMPORARY TABLE tmp.ticketFloramondo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_getMovable` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_getMovable`(
vTicketFk INT,
vNewShipped DATETIME,
vWarehouseFk INT
)
BEGIN
/**
* Cálcula el stock movible para los artículos de un ticket
* vNewShipped debe ser menor que vOldShipped, en los otros casos se
* asume que siempre es posible
*
* @param vTicketFk -> Ticket
* @param vNewShipped -> Nueva fecha
* @return Sales con Movible
*/
DECLARE vOldShipped DATETIME;
SELECT t.shipped INTO vOldShipped
FROM ticket t
WHERE t.id = vTicketFk;
-- Añadimos un dia más para calcular el stock hasta vNewShipped inclusive
CALL item_getStock(vWarehouseFk, vNewShipped, NULL);
CALL item_getMinacum(
vWarehouseFk,
vNewShipped,
DATEDIFF(DATE_SUB(vOldShipped, INTERVAL 1 DAY), vNewShipped),
NULL
);
SELECT s.id,
s.itemFk,
s.quantity,
s.concept,
s.price,
s.reserved,
s.discount,
i.image,
i.subName,
IFNULL(il.stock,0) + IFNULL(im.amount, 0) AS movable
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
LEFT JOIN tmp.itemMinacum im ON im.itemFk = s.itemFk
AND im.warehouseFk = vWarehouseFk
LEFT JOIN tmp.itemList il ON il.itemFk = s.itemFk
WHERE t.id = vTicketFk;
DROP TEMPORARY TABLE IF EXISTS
tmp.itemList,
tmp.itemMinacum;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_getProblems` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_getProblems`(IN vIsTodayRelative tinyint(1))
BEGIN
/**
* Calcula los problemas para un conjunto de tickets.
* Agrupados por ticket
*
* @table tmp.sale_getProblems(ticketFk, clientFk, warehouseFk, shipped) Identificadores de los tickets a calcular
* @return tmp.ticket_problems
*/
CALL sale_getProblems(vIsTodayRelative);
CREATE OR REPLACE TEMPORARY TABLE tmp.ticket_problems
(PRIMARY KEY (ticketFk))
ENGINE = MEMORY
SELECT ticketFk,
MAX(isFreezed) isFreezed,
MAX(risk) risk,
MAX(hasHighRisk) hasHighRisk,
MAX(hasTicketRequest) hasTicketRequest,
MAX(itemShortage) itemShortage,
MIN(isTaxDataChecked) isTaxDataChecked,
MAX(hasComponentLack) hasComponentLack,
MAX(isTooLittle) isTooLittle,
MAX(itemDelay) itemDelay,
MAX(hasRounding) hasRounding,
MAX(itemLost) itemLost,
0 totalProblems
FROM tmp.sale_problems
GROUP BY ticketFk;
UPDATE tmp.ticket_problems tp
SET tp.totalProblems = (
(tp.isFreezed) +
IF(tp.risk,TRUE, FALSE) +
(tp.hasTicketRequest) +
(tp.isTaxDataChecked = 0) +
(tp.hasComponentLack) +
(tp.itemDelay) +
(tp.isTooLittle) +
(tp.itemLost) +
(tp.hasRounding) +
(tp.itemShortage)
);
DROP TEMPORARY TABLE tmp.sale_problems;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_getSplitList` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_getSplitList`(vDated DATE, vHour TIME, vWarehouseFk INT)
BEGIN
/**
* Devuelve un listado con los tickets posibles para splitar HOY.
*
* @param vDated Fecha a estudiar
* @param vHour Hora a partir de la cual todavía se puede enviar, si la fecha es la de hoy
* @param vWarehouseFk Almacén
*/
DECLARE vAvailableCache INT;
DECLARE vVisibleCache INT;
CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouseFk, util.VN_CURDATE());
CALL cache.visible_refresh(vVisibleCache, FALSE, vWarehouseFk);
CALL `vn`.`zoneClosure_recalc`();
CREATE OR REPLACE TEMPORARY TABLE tmp.salesToSplit
(saleFk INT PRIMARY KEY,
ticketFk INT,
problem VARCHAR(1),
INDEX(ticketFk)) ENGINE = MEMORY;
CREATE OR REPLACE TEMPORARY TABLE tItemShelvingStock_byWarehouse
(INDEX (itemFk, warehouseFk))
ENGINE = MEMORY
SELECT ish.itemFk itemFk,
SUM(ish.visible) visible,
s.warehouseFk warehouseFk
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
GROUP BY ish.itemFk,
s.warehouseFk;
INSERT INTO tmp.salesToSplit(saleFk, ticketFk, problem)
SELECT s.id, s.ticketFk, 'F'
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
JOIN itemType it on it.id = i.typeFk
JOIN itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN cache.visible v ON v.item_id = i.id
AND v.calc_id = vVisibleCache
LEFT JOIN cache.available av ON av.item_id = i.id
AND av.calc_id = vAvailableCache
LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
AND issw.warehouseFk = t.warehouseFk
WHERE IFNULL(v.visible,0) < s.quantity
AND IFNULL(av.available ,0) < s.quantity
AND IFNULL(issw.visible, 0) < s.quantity
AND s.isPicked = FALSE
AND s.reserved = FALSE
AND ic.merchandise = TRUE
AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
AND NOT i.generic
AND t.warehouseFk = vWarehouseFk;
INSERT IGNORE INTO tmp.salesToSplit(saleFk, ticketFk, problem)
SELECT s.id, s.ticketFk, 'I'
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
JOIN itemType it on it.id = i.typeFk
JOIN itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN cache.visible v ON v.item_id = s.itemFk
AND v.calc_id = vVisibleCache
LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
AND issw.warehouseFk = t.warehouseFk
WHERE IFNULL(v.visible,0) >= s.quantity
AND IFNULL(issw.visible, 0) < s.quantity
AND s.quantity > 0
AND NOT s.isPicked
AND NOT s.reserved
AND ic.merchandise
AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
AND NOT i.generic
AND t.warehouseFk = vWarehouseFk;
INSERT IGNORE INTO tmp.salesToSplit(saleFk, ticketFk, problem)
SELECT s.id, s.ticketFk, 'R'
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
JOIN itemType it on it.id = i.typeFk
JOIN itemCategory ic ON ic.id = it.categoryFk
LEFT JOIN cache.visible v ON v.item_id = s.itemFk
AND v.calc_id = vVisibleCache
LEFT JOIN cache.available av ON av.item_id = i.id
AND av.calc_id = vAvailableCache
LEFT JOIN tItemShelvingStock_byWarehouse issw ON issw.itemFk = i.id
AND issw.warehouseFk = t.warehouseFk
WHERE IFNULL(v.visible,0) < s.quantity
AND IFNULL(av.available ,0) >= s.quantity
AND IFNULL(issw.visible, 0) < s.quantity
AND s.quantity > 0
AND NOT s.isPicked
AND NOT s.reserved
AND ic.merchandise
AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
AND NOT i.generic
AND t.warehouseFk = vWarehouseFk;
CREATE OR REPLACE TEMPORARY TABLE tTicketsToSplit(
ticketFk INT PRIMARY KEY,
problems VARCHAR(100),
addressFk INT,
ipt VARCHAR(10),
etd TIME,
INDEX(addressFk)
) ENGINE = MEMORY;
INSERT INTO tTicketsToSplit
SELECT ss.ticketFk,
GROUP_CONCAT(DISTINCT ss.problem ORDER BY ss.problem) problems,
t.addressFk,
GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt,
DATE_FORMAT(IF(HOUR(t.shipped),
t.shipped,
IFNULL(zc.hour, z.HOUR)),'%H:%i') etd
FROM tmp.salesToSplit ss
JOIN ticket t ON t.id = ss.ticketFk
JOIN sale s ON s.id = ss.saleFk
JOIN item i ON i.id = s.itemFk
LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk
LEFT JOIN zone z ON z.id = t.zoneFk
GROUP BY ss.ticketFk;
SELECT ts.*,
t.id ticketFuture,
st.name state,
zc.`hour` tfEtd,
GROUP_CONCAT(
DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk
) tfIpt,
st2.name tfState
FROM tTicketsToSplit ts
LEFT JOIN ticketState ts2 ON ts2.ticketFk = ts.ticketFk
LEFT JOIN `state` st ON st.id = ts2.stateFk
LEFT JOIN ticket t ON t.id != ts.ticketFk
AND t.addressFk = ts.addressFk
AND t.shipped BETWEEN vDated AND util.dayend(vDated)
LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk AND zc.dated = vDated
LEFT JOIN sale s ON s.ticketFk = t.id
LEFT JOIN item i ON i.id = s.itemFk
LEFT JOIN ticketState tst ON tst.ticketFk = t.id
LEFT JOIN state st2 ON st2.id = tst.stateFk
WHERE (t.id IS NULL
OR (vDated > util.VN_CURDATE())
OR (vDated = util.VN_CURDATE() AND vHour >= zc.`hour`))
AND ts.etd <= vHour
GROUP BY ts.ticketFk, t.id
ORDER BY ts.etd, ts.ticketFk;
DROP TEMPORARY TABLE
tTicketsToSplit,
tItemShelvingStock_byWarehouse;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_getTax`(IN vTaxArea VARCHAR(25))
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 (ticketFk, taxableBase, tax, code)
* @return tmp.ticketTax (ticketFk, pgcFk, taxableBase, rate, code) Impuesto desglosado para cada ticket.
*/
-- Mantengo el drop porque si no da error en los tests de back de salix
-- Table 'addressCompany' was locked with a READ lock and can't be updated'
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 IS NOT NULL 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
CREATE OR REPLACE TEMPORARY TABLE tmp.ticketTax
(PRIMARY KEY (ticketFk, code, rate))
ENGINE = MEMORY
SELECT * FROM (
SELECT tmpTicket.ticketFk,
bp.pgcFk,
SUM(s.quantity * s.price * (100 - s.discount) / 100 ) 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
) t3
ORDER BY priority;
CREATE OR REPLACE TEMPORARY TABLE tmp.ticketServiceTax
(PRIMARY KEY (ticketFk, code, rate))
ENGINE = MEMORY
SELECT tt.ticketFk,
pgc.code pgcFk,
SUM(ts.quantity * ts.price) taxableBase,
pgc.rate,
tc.code
FROM tmp.ticket 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
JOIN taxClass tc ON tc.id = bp.taxClassFk
GROUP BY tt.ticketFk, pgc.code
HAVING taxableBase;
INSERT INTO tmp.ticketTax (ticketFk, pgcFk, taxableBase, rate, code)
SELECT ts.ticketFk, ts.pgcFk, ts.taxableBase, ts.rate, ts.code
FROM tmp.ticketServiceTax ts
ON DUPLICATE KEY UPDATE ticketTax.taxableBase = VALUES (taxableBase) + ticketTax.taxableBase ;
CREATE OR REPLACE 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
tmp.addressCompany,
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_getWarnings` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_getWarnings`()
BEGIN
/**
* Calcula las adventencias para un conjunto de tickets.
* Agrupados por ticket
*
* @table tmp.sale_getWarnings(ticketFk) Identificadores de los tickets a calcular
* @return tmp.ticket_warnings
*/
CREATE OR REPLACE TEMPORARY TABLE tSaleWarnings (
ticketFk INT(11),
saleFk INT(11),
isFragile INTEGER(1) DEFAULT 0,
PRIMARY KEY (ticketFk, saleFk)
) ENGINE = MEMORY;
-- Fragile
INSERT INTO tSaleWarnings(ticketFk, saleFk, isFragile)
SELECT tt.ticketFk, s.id, TRUE
FROM tmp.sale_getWarnings tt
LEFT JOIN sale s ON s.ticketFk = tt.ticketFk
LEFT JOIN item i ON i.id = s.itemFk
LEFT JOIN itemType it ON it.id = i.typeFk
LEFT JOIN agencyMode am ON am.id = tt.agencyModeFk
LEFT JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
WHERE dm.code IN ('AGENCY')
AND it.isFragile;
CREATE OR REPLACE TEMPORARY TABLE tmp.ticket_warnings
(PRIMARY KEY (ticketFk))
ENGINE = MEMORY
SELECT
sw.ticketFk,
MAX(sw.isFragile) AS isFragile
FROM tSaleWarnings sw
GROUP BY sw.ticketFk;
DROP TEMPORARY TABLE
tSaleWarnings;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_getWithParameters` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_getWithParameters`(
vClientFk INT,
vWarehouseFk INT,
vShipped DATE,
vAddressFk INT,
vCompanyFk INT,
vAgencyModeFk INT,
OUT vTicketFk INT
)
BEGIN
/**
* Devuelve un ticket con los parametros, en caso de no existir lo crea
*
* @param vClientFk Cliente
* @param vWarehouseFk almacen
* @param vShipped Fecha de preparacion
* @param vAddressFk Consignatario
* @param vCompanyFk Empresa
* @param vAgencyModeFk agencia
*/
SELECT t.id INTO vTicketFk
FROM vn.ticket t
WHERE t.clientFk <=> vClientFk
AND t.warehouseFk <=> vWarehouseFk
AND (t.shipped <=> vShipped OR vShipped IS NULL)
AND (t.addressFk <=> vAddressFk OR vAddressFk IS NULL)
AND (t.companyFk <=> vCompanyFk OR vCompanyFk IS NULL)
AND (t.agencyModeFk <=> vAgencyModeFk OR vAgencyModeFk IS NULL)
LIMIT 1;
IF vTicketFk IS NULL THEN
CALL vn.ticket_add(
vClientFk,
IFNULL(vShipped, util.VN_CURDATE()),
vWarehouseFk,
vCompanyFk,
vAddressFk,
vAgencyModeFk,
NULL,
vShipped,
`account`.`myUser_getId`(),
TRUE,
vTicketFk
);
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 > '2020-01-01' AND zoneFk is null;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET vDone = 1;
OPEN vCursor;
REPEAT
FETCH vCursor INTO vFechedTicket, vLanded, vAddressFk, vAgencyModeFk, vWarehouseFk;
CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE);
UPDATE vn.ticket t
JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = vWarehouseFk
SET t.zoneFk = zgs.zoneFk
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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.ticketComponentPreview tc ON tc.itemFk = s.itemFk
AND tc.warehouseFk = vWarehouseFk
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.ticketComponentPreview;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_printLabelPrevious` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_printLabelPrevious`(vTicketFk INT)
BEGIN
/**
* Calls the report_print procedure and passes it
* the necessary parameters for printing.
*
* @param vTicketFk id ticket to print.
*/
DECLARE vPrinterFk INT;
DECLARE vSaleGroup INT;
DECLARE vUserFk INT DEFAULT account.myUser_getId();
SELECT sg.id, o.labelerFk INTO vSaleGroup, vPrinterFk
FROM saleGroup sg
JOIN sector sc ON sc.id = sg.sectorFk
JOIN saleGroupDetail sgd ON sg.id = sgd.saleGroupFk
JOIN sale s ON sgd.saleFk = s.id
JOIN ticket t ON s.ticketFk = t.id
JOIN operator o ON o.workerFk = vUserFk
WHERE sc.id = o.sectorFk
AND t.id = vTicketFk
LIMIT 1;
CALL report_print(
'LabelPrevia',
vPrinterFk,
vUserFk,
JSON_OBJECT('id', vSaleGroup, 'userFk', vUserFk),
'high'
);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_recalc`(vSelf INT, vTaxArea VARCHAR(25))
proc:BEGIN
/**
* Calcula y guarda el total con/sin IVA en un ticket.
*
* @param vSelf Identificador del ticket
* @param vTaxArea
*/
DECLARE hasInvoice BOOL;
SELECT COUNT(*) INTO hasInvoice
FROM ticket
WHERE id = vSelf
AND refFk IS NOT NULL;
IF hasInvoice THEN
LEAVE proc;
END IF;
DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
CREATE TEMPORARY TABLE tmp.ticket
ENGINE = MEMORY
SELECT vSelf ticketFk;
CALL ticketGetTotal(vTaxArea);
UPDATE ticket t
JOIN tmp.ticketTotal tt ON tt.ticketFk = t.id
SET t.totalWithVat = tt.total,
t.totalWithoutVat = tt.totalWithoutVat;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_recalcByScope` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_recalcByScope`(
vScope VARCHAR(255),
vId INT
)
BEGIN
/**
* Recalculates tickets in an scope.
*
* @param vScope The scope name
* @param vId The scope id
*/
DECLARE vDone BOOL;
DECLARE vTicketFk INT;
DECLARE cTickets CURSOR FOR
SELECT id FROM ticket
WHERE refFk IS NULL
AND ((vScope = 'client' AND clientFk = vId)
OR (vScope = 'address' AND addressFk = vId));
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
OPEN cTickets;
myLoop: LOOP
SET vDone = FALSE;
FETCH cTickets INTO vTicketFk;
IF vDone THEN
LEAVE myLoop;
END IF;
CALL ticket_recalc(vTicketFk, NULL);
END LOOP;
CLOSE cTickets;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_recalcComponents`(vSelf INT, vOption VARCHAR(25))
proc: BEGIN
/**
* Crea tabla temporal para sale_recalcComponent() para recalcular los componentes
*
* @param vSelf Id del ticket
* @param vOption si no se quiere forzar llamar con NULL
*/
CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales
SELECT s.id
FROM sale s
WHERE s.ticketFk = vSelf;
CALL sale_recalcComponent(vOption);
DROP TEMPORARY TABLE tmp.recalculateSales;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_setNextState` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setNextState`(vSelf INT)
BEGIN
/**
* Cambia el estado del ticket al siguiente estado según la tabla state
*
* @param vSelf id dle ticket
*/
DECLARE vStateFk INT;
DECLARE vNewStateFk INT;
SELECT stateFk INTO vStateFk
FROM ticketState
WHERE ticketFk = vSelf;
SELECT nextStateFk INTO vNewStateFk
FROM state
WHERE id = vStateFk;
INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
VALUES (vNewStateFk, vSelf, account.myUser_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_setParking` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setParking`(IN `vTicketFk` VARCHAR(8), IN `vParkingFk` INT)
proc: BEGIN
/**
* Aparca un ticket en un parking
*
* @param vTicketFk id del ticket
* @param vParkingFk id del parking
*/
DECLARE vDone INT DEFAULT FALSE;
DECLARE vCollectionTicketFk INT;
DECLARE vCursor CURSOR FOR
SELECT IFNULL(tc2.ticketFk, t.id)
FROM ticket t
LEFT JOIN ticketCollection tc1 ON tc1.ticketFk = t.id
LEFT JOIN ticketCollection tc2 ON tc2.collectionFk = tc1.collectionFk
WHERE t.id = vTicketFk;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
INSERT INTO vn.ticketParking(ticketFk, parkingFk)
SELECT IFNULL(tc2.ticketFk, t.id), vParkingFk
FROM ticket t
LEFT JOIN ticketCollection tc1 ON tc1.ticketFk = t.id
LEFT JOIN ticketCollection tc2 ON tc2.collectionFk = tc1.collectionFk
WHERE t.id = vTicketFk
ON DUPLICATE KEY UPDATE parkingFk = vParkingFk;
OPEN vCursor;
l: LOOP
FETCH vCursor INTO vCollectionTicketFk;
IF vDone THEN
LEAVE l;
END IF;
CALL vn.ticket_setNextState(vCollectionTicketFk);
END LOOP;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_setPreviousState` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setPreviousState`(vTicketFk INT)
BEGIN
DECLARE vControlFk INT;
SELECT MAX(id) INTO vControlFk
FROM ticketTracking
WHERE ticketFk = vTicketFk;
IF (SELECT s.code
FROM vn.state s
JOIN ticketTracking tt ON tt.stateFk = s.id
WHERE tt.id = vControlFk)
= 'PREVIOUS_PREPARATION' THEN
SELECT id
INTO vControlFk
FROM ticketTracking tt
JOIN vn.state s ON tt.stateFk = s.id
WHERE ticketFk = vTicketFk
AND id < vControlFk
AND s.code != 'PREVIOUS_PREPARATION'
ORDER BY id DESC
LIMIT 1;
INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
SELECT s.nextStateFk, tt.ticketFk, account.myUser_getId()
FROM ticketTracking tt
JOIN vn.state s ON tt.stateFk = s.id
WHERE id = vControlFk;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_setState` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setState`(
vSelf INT,
vStateCode VARCHAR(255) COLLATE utf8_general_ci
)
BEGIN
/**
* Modifica el estado de un ticket si se cumplen las condiciones necesarias.
*
* @param vSelf el id del ticket
* @param vStateCode estado a modificar del ticket
*/
DECLARE vticketAlertLevel INT;
DECLARE vTicketStateCode VARCHAR(255);
DECLARE vCanChangeState BOOL;
DECLARE vPackedAlertLevel INT;
DECLARE vZoneFk INT;
SELECT s.alertLevel, s.`code`, t.zoneFk
INTO vticketAlertLevel, vTicketStateCode, vZoneFk
FROM state s
JOIN ticketTracking tt ON tt.stateFk = s.id
JOIN ticket t ON t.id = tt.ticketFk
WHERE tt.ticketFk = vSelf
ORDER BY tt.created DESC
LIMIT 1;
SELECT id INTO vPackedAlertLevel FROM alertLevel WHERE code = 'PACKED';
IF vStateCode = 'OK' AND vZoneFk IS NULL THEN
CALL util.throw('ASSIGN_ZONE_FIRST');
END IF;
SET vCanChangeState = ((
vStateCode <> 'ON_CHECKING' AND vStateCode <> 'CHECKED') OR
vticketAlertLevel < vPackedAlertLevel
)AND NOT (
vTicketStateCode IN ('CHECKED', 'CHECKING')
AND vStateCode IN ('PREPARED', 'ON_PREPARATION')
);
IF vCanChangeState THEN
INSERT INTO ticketTracking (stateFk, ticketFk, userFk)
SELECT id, vSelf, account.myUser_getId()
FROM state
WHERE `code` = vStateCode COLLATE utf8_unicode_ci;
IF vStateCode = 'PACKED' THEN
CALL ticket_doCmr(vSelf);
END IF;
ELSE
CALL util.throw('INCORRECT_TICKET_STATE');
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_split` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_split`(vTicketFk INT, vTicketFutureFk INT, vDated DATE)
proc:BEGIN
/**
* Mueve las lineas con problemas a otro ticket existente o a uno nuevo.
*
* @param vTicketFk Identificador del ticket a splittar
* @param vTicketFutureFk Identificador del ticket al que se quieren mover las lineas
* @param vDate Fecha a la que se va a mover
* @table tmp.salesToSplit(saleFk, ticketFk, problem)
*/
DECLARE vHasFullProblem BOOL;
DECLARE vProblemLines INT;
DECLARE vTotalLines INT;
SELECT COUNT(*) INTO vProblemLines
FROM tmp.salesToSplit
WHERE ticketFk = vTicketFk;
SELECT count(*) INTO vTotalLines
FROM vn.sale s
WHERE s.ticketFk = vTicketFk;
SET vHasFullProblem = (vTotalLines = vProblemLines);
-- Ticket completo
IF vHasFullProblem THEN
UPDATE vn.ticket
SET landed = vDated + INTERVAL 1 DAY,
shipped = vDated,
nickname = CONCAT('(',DAY(util.VN_CURDATE()),') ', nickname )
WHERE id = vTicketFk;
SELECT "moved" message, NULL ticketFuture;
LEAVE proc;
END IF;
-- Ticket a futuro existe
IF vTicketFutureFk THEN
UPDATE vn.sale s
JOIN tmp.salesToSplit ss ON s.id = ss.saleFk
SET s.ticketFk = vTicketFutureFk,
s.concept = CONCAT('(s) ', s.concept)
WHERE ss.ticketFk = vTicketFk;
SELECT "future" message, NULL ticketFuture;
LEAVE proc;
END IF;
-- Ticket nuevo
CALL vn.ticket_Clone(vTicketFk, vTicketFutureFk);
UPDATE vn.ticket t
JOIN vn.productionConfig pc
SET t.routeFk = IF(t.shipped = vDated , t.routeFk, NULL),
t.landed = vDated + INTERVAL 1 DAY,
t.shipped = vDated,
t.agencyModeFk = pc.defautlAgencyMode,
t.zoneFk = pc.defaultZone
WHERE t.id = vTicketFutureFk;
UPDATE vn.sale s
JOIN tmp.salesToSplit sts ON sts.saleFk = s.id
SET s.ticketFk = vTicketFutureFk,
s.concept = CONCAT('(s) ', s.concept)
WHERE sts.ticketFk = vTicketFk;
CALL vn.ticketStateUpdate(vTicketFutureFk, 'FIXING');
SELECT "new" message,vTicketFutureFk ticketFuture;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_splitItemPackingType` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_splitItemPackingType`(vTicketFk INT, vOriginalItemPackingTypeFk VARCHAR(1))
proc:BEGIN
/**
* Clona y reparte las ventas de un ticket en funcion del tipo de empaquetado.
* Respeta el id inicial para el tipo propuesto.
*
* @param vTicketFk Identificador de vn.ticket
* @param vOriginalItemPackingTypeFk Tipo para el que se reserva el número de ticket original
* @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk)
*/
DECLARE vItemPackingTypeFk VARCHAR(1) DEFAULT 'H';
DECLARE vNewTicketFk INT;
DECLARE vPackingTypesToSplit INT;
DECLARE vDone INT DEFAULT FALSE;
DECLARE cur1 CURSOR FOR
SELECT itemPackingTypeFk
FROM tmp.saleGroup
WHERE itemPackingTypeFk IS NOT NULL
ORDER BY (itemPackingTypeFk = vOriginalItemPackingTypeFk) DESC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DELETE FROM vn.sale
WHERE quantity = 0
AND ticketFk = vTicketFk;
DROP TEMPORARY TABLE IF EXISTS tmp.sale;
CREATE TEMPORARY TABLE tmp.sale
(PRIMARY KEY (id))
SELECT s.id, i.itemPackingTypeFk , IFNULL(sv.litros, 0) litros
FROM vn.sale s
JOIN vn.item i ON i.id = s.itemFk
LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id
WHERE s.ticketFk = vTicketFk;
DROP TEMPORARY TABLE IF EXISTS tmp.saleGroup;
CREATE TEMPORARY TABLE tmp.saleGroup
SELECT itemPackingTypeFk , sum(litros) AS totalLitros
FROM tmp.sale
GROUP BY itemPackingTypeFk;
SELECT COUNT(*) INTO vPackingTypesToSplit
FROM tmp.saleGroup
WHERE itemPackingTypeFk IS NOT NULL;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketIPT;
CREATE TEMPORARY TABLE tmp.ticketIPT
(ticketFk INT,
itemPackingTypeFk VARCHAR(1));
CASE vPackingTypesToSplit
WHEN 0 THEN
INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk)
VALUES(vTicketFk, vItemPackingTypeFk);
WHEN 1 THEN
INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk)
SELECT vTicketFk, itemPackingTypeFk
FROM tmp.saleGroup
WHERE itemPackingTypeFk IS NOT NULL;
ELSE
OPEN cur1;
FETCH cur1 INTO vItemPackingTypeFk;
INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk)
VALUES(vTicketFk, vItemPackingTypeFk);
read_loop: LOOP
FETCH cur1 INTO vItemPackingTypeFk;
IF vDone THEN
LEAVE read_loop;
END IF;
CALL vn.ticket_Clone(vTicketFk, vNewTicketFk);
INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk)
VALUES(vNewTicketFk, vItemPackingTypeFk);
END LOOP;
CLOSE cur1;
UPDATE vn.sale s
JOIN tmp.sale ts ON ts.id = s.id
JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk
SET s.ticketFk = t.ticketFk;
SELECT itemPackingTypeFk INTO vItemPackingTypeFk
FROM tmp.saleGroup sg
WHERE NOT ISNULL(sg.itemPackingTypeFk)
ORDER BY sg.itemPackingTypeFk
LIMIT 1;
UPDATE vn.sale s
JOIN tmp.sale ts ON ts.id = s.id
JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = vItemPackingTypeFk
SET s.ticketFk = t.ticketFk
WHERE ts.itemPackingTypeFk IS NULL;
END CASE;
DROP TEMPORARY TABLE tmp.sale;
DROP TEMPORARY TABLE tmp.saleGroup;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_splitPackingComplete` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_splitPackingComplete`(vTicketFk INT, vSectorFk INT)
BEGIN
DECLARE vNeedToSplit BOOLEAN;
DECLARE vNewTicketFk INT;
DROP TEMPORARY TABLE IF EXISTS tmpSale;
CREATE TEMPORARY TABLE tmpSale
SELECT DISTINCT s.id
FROM vn.ticket t
JOIN vn.sale s ON s.ticketFk = t.id
JOIN vn.item i ON i.id = s.itemFk
LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = s.itemFk AND iss.sectorFk = vSectorFk
JOIN vn.packagingConfig pc
WHERE t.id = vTicketFk
AND ( s.quantity MOD IFNULL(iss.packing,1) != 0
OR
IFNULL(iss.packing,1) = 1
OR
i.`size` <= pc.previousPreparationMinimumSize
);
SELECT COUNT(*)
INTO vNeedToSplit
FROM tmpSale;
IF vNeedToSplit THEN
CALL vn.ticket_Clone(vTicketFk, vNewTicketFk);
UPDATE vn.sale s
JOIN vn.tmpSale ts ON ts.id = s.id
SET s.ticketFk = vNewTicketFk;
END IF;
DROP TEMPORARY TABLE tmpSale;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_WeightDeclaration` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_WeightDeclaration`(vClientFk INT, vDated DATE)
BEGIN
DECLARE vTheorycalWeight DECIMAL(10,2);
DECLARE vRealWeight DECIMAL(10,2);
DECLARE vRatio DOUBLE;
SELECT IFNULL(sum(tob.description),0) INTO vRealWeight
FROM vn.ticketObservation tob
JOIN vn.observationType ot ON ot.id = tob.observationTypeFk
JOIN vn.ticket t ON t.id = tob.ticketFk
WHERE ot.description = 'Peso Aduana'
AND t.clientFk = vClientFk
AND t.shipped BETWEEN vDated AND util.dayend(vDated);
SELECT sum(IF(sv.physicalWeight = 0, sv.weight, sv.physicalWeight)) INTO vTheorycalWeight
FROM vn.ticket t
JOIN vn.sale s ON s.ticketFk = t.id
JOIN vn.saleVolume sv ON sv.saleFk = s.id
JOIN vn.item i ON i.id = s.itemFk
JOIN vn.itemCost ic ON ic.itemFk = i.id AND ic.warehouseFk = t.warehouseFk
WHERE t.clientFk = vClientFk
AND t.shipped BETWEEN vDated AND util.dayend(vDated);
SET vRatio = vRealWeight / vTheorycalWeight;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketWeight;
CREATE TEMPORARY TABLE tmp.ticketWeight
ENGINE = MEMORY
SELECT i.intrastatFk,
ib.ediBotanic,
FLOOR(sum(s.quantity)) as quantity,
CAST(vRatio * SUM(IF(sv.physicalWeight = 0, sv.weight, sv.physicalWeight) ) AS DECIMAL(10,2)) physicalWeight,
o.code as countryCode,
vDated as Dated
FROM vn.ticket t
JOIN vn.sale s ON s.ticketFk = t.id
JOIN vn.saleVolume sv ON sv.saleFk = s.id
JOIN vn.item i ON i.id = s.itemFk
LEFT JOIN vn.itemBotanicalWithGenus ib ON ib.itemFk = i.id
LEFT JOIN vn.origin o ON o.id = i.originFk
WHERE t.clientFk = vClientFk
AND t.shipped BETWEEN vDated AND util.dayend(vDated)
GROUP BY ib.ediBotanic, o.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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
*/
DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate;
CREATE TEMPORARY TABLE tmp.timeBusinessCalculate
(INDEX (departmentFk))
SELECT dated,
businessFk,
sub.id userFk,
departmentFk,
hourStart,
hourEnd,
timeTable,
timeWorkSeconds,
SEC_TO_TIME(timeWorkSeconds) timeWorkSexagesimal,
timeWorkSeconds / 3600 timeWorkDecimal,
timeWorkSeconds timeBusinessSeconds,
SEC_TO_TIME(timeWorkSeconds) timeBusinessSexagesimal,
timeWorkSeconds / 3600 timeBusinessDecimal,
name type,
permissionRate,
hoursWeek,
discountRate,
isAllowedToWork
FROM(SELECT t.dated,
b.id businessFk,
w.id,
b.departmentFk,
IF(bs.started = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(bs.started,5) ORDER BY bs.started ASC SEPARATOR ' - ')) hourStart ,
IF(bs.started = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(bs.ended,5) ORDER BY bs.ended ASC SEPARATOR ' - ')) hourEnd,
IF(bs.started = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(bs.started,5), " - ", LEFT(bs.ended,5) ORDER BY bs.ended ASC SEPARATOR ' - ')) timeTable,
IF(bs.started = NULL, 0, IFNULL(SUM(TIME_TO_SEC(bs.ended)) - SUM(TIME_TO_SEC(bs.started)), 0)) timeWorkSeconds,
at2.name,
at2.permissionRate,
at2.discountRate,
ct.hoursWeek hoursWeek,
at2.isAllowedToWork
FROM time t
LEFT JOIN business b ON t.dated BETWEEN b.started AND IFNULL(b.ended, vDatedTo)
LEFT JOIN worker w ON w.id = b.workerFk
JOIN tmp.`user` u ON u.userFK = w.id
LEFT JOIN workCenter wc ON wc.id = b.workcenterFK
LEFT JOIN calendarType ct ON ct.id = b.calendarTypeFk
LEFT JOIN businessSchedule bs ON bs.businessFk = b.id AND bs.weekday = WEEKDAY(t.dated) + 1
LEFT JOIN calendar c ON c.businessFk = b.id AND c.dated = t.dated
LEFT JOIN absenceType at2 ON at2.id = c.dayOffTypeFk
WHERE t.dated BETWEEN vDatedFrom AND vDatedTo
GROUP BY w.id, t.dated
)sub;
UPDATE tmp.timeBusinessCalculate t
LEFT JOIN businessSchedule bs ON bs.businessFk = t.businessFk
SET t.timeWorkSeconds = t.hoursWeek / 5 * 3600,
t.timeWorkSexagesimal = SEC_TO_TIME( t.hoursWeek / 5 * 3600),
t.timeWorkDecimal = t.hoursWeek / 5,
t.timeBusinessSeconds = t.hoursWeek / 5 * 3600,
t.timeBusinessSexagesimal = SEC_TO_TIME( t.hoursWeek / 5 * 3600),
t.timeBusinessDecimal = t.hoursWeek / 5
WHERE DAYOFWEEK(t.dated) IN(2,3,4,5,6) AND bs.id IS NULL ;
UPDATE tmp.timeBusinessCalculate t
SET t.timeWorkSeconds = t.timeWorkSeconds - (t.timeWorkSeconds * permissionRate) ,
t.timeWorkSexagesimal = SEC_TO_TIME ((t.timeWorkDecimal - (t.timeWorkDecimal * permissionRate)) * 3600),
t.timeWorkDecimal = t.timeWorkDecimal - (t.timeWorkDecimal * permissionRate)
WHERE permissionRate <> 0;
UPDATE tmp.timeBusinessCalculate t
JOIN calendarHolidays ch ON ch.dated = t.dated
JOIN business b ON b.id = t.businessFk
AND b.workcenterFk = ch.workcenterFk
SET t.timeWorkSeconds = 0,
t.timeWorkSexagesimal = 0,
t.timeWorkDecimal = 0,
t.permissionrate = 1,
t.type = 'Festivo'
WHERE t.type 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `timeBusiness_calculateAll`(vDatedFrom DATETIME, vDatedTo DATETIME)
BEGIN
/**
* @param vDatedFrom Fecha desde
* @param vDatedTo Fecha hasta
*/
CREATE OR REPLACE TEMPORARY TABLE tmp.`user`
SELECT w.id userFk
FROM vn.worker w;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 b.workerFk userFk
FROM business AS b
WHERE (b.started BETWEEN vDatedFrom AND vDatedTo
OR IFNULL(b.ended, vDatedTo) BETWEEN vDatedFrom AND vDatedTo
OR (b.started <= vDatedFrom AND b.ended >= vDatedTo)
) AND b.departmentFk = vDepartmentFk
ORDER BY b.ended DESC;
CALL 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 account.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `timeBusiness_calculateByWorker`(vWorkerFk INT, vDatedFrom DATETIME, vDatedTo DATETIME)
BEGIN
/**
* @param vWorkerFk
* @param vDatedFrom Fecha desde
* @param vDatedTo Fecha hasta
*/
CREATE OR REPLACE TEMPORARY TABLE tmp.`user`
SELECT w.id userFk
FROM worker w
WHERE w.id = vWorkerFk;
CALL 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculate`(
vDatedFrom DATETIME,
vDatedTo DATETIME)
BEGIN
/*
* Agrupa por trabajador y día, el tiempo de trabajo y descanso retribuido(si tiene).
* Los registros horarios incorrectos (tmp.timeControlError) no se considerarán.
* Si un trabajador ha trabajado más de un cierto umbral de tiempo (vTimeToBreakTime)
* y no ha tenido descansos que superen un parámetro determinado(vMaxTimeToBreak),
* se le añadirá un tiempo de descanso (vBreakTime) a sus horas trabajadas.
* El tiempo de descanso solo se añade si el trabajador realmente disfrutó del descanso.
* Si disfrutó de menos tiempo de descanso, solo se añade el tiempo que disfrutó.
*
* @param vDatedFrom
* @param vDatedTo
*
* @return tmp.timeControlCalculate
* (workerFk, dated, timeWorkSeconds, timeWorkSexagesimal, timeWorkDecimal, timed)
*/
DECLARE vHourSeconds INTEGER;
DECLARE vDatedFromYesterday DATETIME;
DECLARE vDatedToTomorrow DATETIME;
DECLARE vTimeToBreakTime INT;
DECLARE vBreakTime INT;
DECLARE vMaxTimeToBreak INT;
SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY)
INTO vDatedFromYesterday, vDatedToTomorrow;
SELECT timeToBreakTime, breakTime, maxTimeToBreak, TIME_TO_SEC('01:00:00')
INTO vTimeToBreakTime, vBreakTime, vMaxTimeToBreak, vHourSeconds
FROM workerTimeControlConfig
LIMIT 1;
CALL timeControl_getError(vDatedFromYesterday, vDatedToTomorrow);
CREATE OR REPLACE TEMPORARY TABLE tmp.workerTimeControl
(INDEX(userFk, timed), INDEX(timed), INDEX(direction))
ENGINE = MEMORY
SELECT wtc.userFk,
wtc.timed,
DATE(wtc.timed) dated,
wtc.direction,
TRUE isReal
FROM workerTimeControl wtc
JOIN tmp.`user` u ON u.userFk = wtc.userFk
LEFT JOIN (
SELECT wtc.userFk, MIN(wtc.timed) firstIn
FROM workerTimeControl wtc
JOIN tmp.`user` u ON u.userFk = wtc.userFk
LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
AND wtc.direction = 'in'
AND tce.id IS NULL
GROUP BY userFk
) fi ON wtc.userFk = fi.userFk
LEFT JOIN (
SELECT wtc.userFk, MAX(wtc.timed) lastOut
FROM workerTimeControl wtc
JOIN tmp.`user` u ON u.userFk = wtc.userFk
LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
AND wtc.direction = 'out'
AND tce.id IS NULL
GROUP BY userFk
) lo ON wtc.userFk = lo.userFk
LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
WHERE wtc.timed BETWEEN fi.firstIn AND lo.lastOut
AND tce.id IS NULL
ORDER BY wtc.userFk, wtc.timed;
CREATE OR REPLACE TEMPORARY TABLE tmp.wtcToinsert
(INDEX(timed))
ENGINE = MEMORY
WITH wtc AS(
SELECT timed,
userFk,
dated,
direction,
LEAD(dated) OVER
(PARTITION BY userFk, dated ORDER BY timed) nextDay,
LEAD(userFk) OVER
(PARTITION BY userFk ORDER BY timed) nextUserFk,
ROW_NUMBER() OVER (ORDER BY userFk, timed) MOD 2 isOdd
FROM tmp.workerTimeControl
WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
ORDER BY userFk, timed
), wtcToinsert AS(
SELECT userFk,
dated,
IF(userFk = nextUserFk
AND nextDay IS NULL
AND isOdd
AND direction <> 'out', TRUE, FALSE) outNextDay,
IF(userFk = nextUserFk
AND nextDay IS NULL
AND NOT isOdd
AND direction <> 'out', TRUE, FALSE) outNextDayWhitBreak
FROM wtc
HAVING outNextDay OR outNextDayWhitBreak
)SELECT userFk, util.dayEnd(dated) timed, 'out' direction
FROM wtcToinsert
WHERE outNextDay
UNION ALL
SELECT userFk, dated + INTERVAL 1 DAY, 'in'
FROM wtcToinsert
WHERE outNextDay
UNION ALL
SELECT userFk, util.dayEnd(dated) - INTERVAL 1 SECOND, 'middle'
FROM wtcToinsert
WHERE outNextDayWhitBreak
UNION ALL
SELECT userFk, util.dayEnd(dated), 'out'
FROM wtcToinsert
WHERE outNextDayWhitBreak
UNION ALL
SELECT userFk, dated + INTERVAL 1 DAY, 'in'
FROM wtcToinsert
WHERE outNextDayWhitBreak
UNION ALL
SELECT userFk, dated + INTERVAL 1 DAY + INTERVAL 1 SECOND, 'middle'
FROM wtcToinsert
WHERE outNextDayWhitBreak;
INSERT INTO tmp.workerTimeControl (userFk, timed, dated, direction, isReal)
SELECT userFk, timed, DATE(timed), direction, FALSE
FROM tmp.wtcToinsert;
SET @accumulatedForBreakTime = 0;
SET @oldrealDay = NULL;
CREATE OR REPLACE TEMPORARY TABLE tmp.timeControlCalculate
WITH workerTimed AS (
SELECT
userFk,
dated,
timed,
(direction ='in' AND isReal) breakPoint,
SUM(CASE WHEN (direction ='in' AND isReal) THEN TRUE ELSE FALSE END)
OVER (ORDER BY userFk, timed) AS realDay,
TIMESTAMPDIFF(SECOND, LAG(timed)
OVER (PARTITION BY userFk, dated ORDER BY timed), timed) gapTime,
ROW_NUMBER()
OVER (PARTITION BY userFk, dated ORDER BY timed) MOD 2 isOdd
FROM tmp.workerTimeControl
WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
), accumulated AS (
SELECT SUM(IF(isOdd, 0, gapTime))
OVER (PARTITION BY userFk,dated ORDER BY userFk,timed) accumulatedWorkTime,
SUM(IF(NOT isOdd OR breakPoint OR gapTime >= vMaxTimeToBreak OR gapTime IS NULL, 0, gapTime))
OVER (PARTITION BY realDay ORDER BY realDay,timed) accumulatedBreakTime,
IF(realDay <> @oldrealDay OR (isOdd AND gapTime >= vMaxTimeToBreak),
@accumulatedForBreakTime := 0,
@accumulatedForBreakTime := @accumulatedForBreakTime +
IF(isOdd, 0, gapTime )) accumulatedForBreakTime,
@oldrealDay := realDay,
userFk,
dated,
realDay
FROM workerTimed
), totalWorked AS (
SELECT userFk,
dated,
MAX(accumulatedWorkTime) +
IF(MAX(accumulatedForBreakTime) + LEAST(vBreakTime, MAX(accumulatedBreakTime)) >= vTimeToBreakTime,
LEAST(vBreakTime, MAX(accumulatedBreakTime)),
0) timeWorkSeconds
FROM accumulated
GROUP BY userFk, dated
)SELECT tw.userFk,
tw.dated,
timeWorkSeconds,
SEC_TO_TIME(timeWorkSeconds) timeWorkSexagesimal,
timeWorkSeconds / vHourSeconds timeWorkDecimal,
sub.tableTimed
FROM totalWorked tw
JOIN (
SELECT userFk,
dated,
GROUP_CONCAT(DATE_FORMAT(timed, "%H:%i") ORDER BY timed ASC
SEPARATOR ' - ')tableTimed
FROM tmp.workerTimeControl
WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
AND isReal
GROUP BY userFk, dated
)sub ON sub.dated = tw.dated
AND sub.userFk = tw.userFk
WHERE tw.dated BETWEEN vDatedFrom AND vDatedTo;
DROP TEMPORARY TABLE tmp.timeControlError;
DROP TEMPORARY TABLE tmp.wtcToinsert;
DROP TEMPORARY TABLE tmp.workerTimeControl;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculateAll`(vDatedFrom DATETIME, vDatedTo DATETIME)
BEGIN
/**
* @param vDatedFrom Fecha desde
* @param vDatedTo Fecha hasta
*/
CREATE OR REPLACE TEMPORARY TABLE tmp.`user`
SELECT w.id userFk
FROM vn.worker w;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 b.workerFk userFk
FROM business AS b
WHERE (b.started BETWEEN vDatedFrom AND vDatedTo
OR IFNULL(b.ended, vDatedTo) BETWEEN vDatedFrom AND vDatedTo
OR (b.started <= vDatedFrom AND b.ended >= vDatedTo)
) AND b.departmentFk = vDepartmentFk
ORDER BY b.ended DESC;
CALL 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 account.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 account.user u
JOIN vn.worker w ON w.id = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `timeControl_getError` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_getError`(vDatedFrom DATETIME, vDatedTo DATETIME)
BEGIN
/*
* @param vDatedFrom
* @param vDatedTo
* @table tmp.`user`(userFk)
* Fichadas incorrectas de las cuales no se puede calcular horas trabajadas
* @return tmp.timeControlError (id)
*/
DECLARE vDayMaxTime INTEGER;
SET @journeyCounter := 0;
SET @lastUserFk := NULL;
SELECT dayMaxTime INTO vDayMaxTime
FROM workerTimeControlConfig LIMIT 1;
DROP TEMPORARY TABLE IF EXISTS tmp.timeControl;
CREATE TEMPORARY TABLE tmp.timeControl
(INDEX(id), INDEX(journeyCounter))
ENGINE = MEMORY
SELECT sub.id,
sub.direction,
sub.timed,
IF(sub.direction = 'in' OR @hasOut OR sub.userFk <> @lastUserFk, @journeyCounter := @journeyCounter + 1, @journeyCounter) journeyCounter,
@lastUserFk := sub.userFk workerFk,
IF(sub.direction = 'out', @hasOut:= TRUE, @hasOut:= FALSE)
FROM (
SELECT DISTINCT wtc.id,
wtc.direction,
wtc.timed,
wtc.userFk
FROM workerTimeControl wtc
JOIN tmp.`user` w ON w.userFk = wtc.userFk
WHERE wtc.timed BETWEEN DATE_SUB(vDatedFrom, INTERVAL 1 DAY) AND DATE_ADD(vDatedTo, INTERVAL 1 DAY)
ORDER BY wtc.userFk, wtc.timed
) sub;
DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux;
CREATE TEMPORARY TABLE tmp.timeControlAux
(INDEX(id), INDEX(journeyCounter))
ENGINE = MEMORY
SELECT * FROM tmp.timeControl;
DROP TEMPORARY TABLE IF EXISTS tmp.timeControlError;
CREATE TEMPORARY TABLE tmp.timeControlError
(INDEX(id))
ENGINE = MEMORY
SELECT id
FROM tmp.timeControlAux tca
JOIN (
SELECT journeyCounter,
UNIX_TIMESTAMP(MAX(timed)) - UNIX_TIMESTAMP(MIN(timed)) timeWork,
SUM(direction = 'in') totalIn,
SUM(direction = 'out') totalOut,
timed
FROM tmp.timeControl
GROUP BY journeyCounter
HAVING COUNT(*) MOD 2 = 1
OR totalIn <> 1
OR totalOut <> 1
OR timeWork >= vDayMaxTime
)sub ON sub.journeyCounter = tca.journeyCounter
WHERE sub.timed BETWEEN vDatedFrom AND vDatedTo;
DROP TEMPORARY TABLE IF EXISTS tmp.timeControl;
DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `tpvTransaction_checkStatus` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `tpvTransaction_checkStatus`()
BEGIN
/**
*
* Envia mail con los cobros web no
* trasladados a la ficha del cliente.
*
*/
INSERT INTO mail (receiver, replyTo, subject, body)
SELECT 'administracion@verdnatura.es, finanzas@verdnatura.es',
'noreply@verdnatura.es',
CONCAT('Cobro web no trasladado a la ficha del cliente ', clientFk),
CONCAT('Hay un importe de ', amount / 100, '€ del cliente ', clientFk, ' con fecha ', created,
', que no se ha trasladado a recibos. Si nos ha llegado el importe al banco confirme el pago en
https://salix.verdnatura.es/#!/client/', clientFk, '/web-payment')
FROM hedera.tpvTransaction
WHERE receiptFk IS NULL
AND status = 'ok'
AND created < (util.VN_NOW() - INTERVAL 2 DAY)
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travelVolume` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `travelVolume`(vTravelFk INT)
BEGIN
SELECT w1.name AS ORI,
w2.name AS DES,
tr.shipped shipment,
tr.landed landing,
a.name Agencia,
s.name Proveedor,
e.id Id_Entrada,
e.invoiceNumber Referencia,
CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) *
vn.item_getVolume(b.itemFk ,b.packagingFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) AS CC,
CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) *
vn.item_getVolume(b.itemFk ,b.packagingFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) AS espais
FROM vn.buy b
JOIN vn.entry e ON e.id = b.entryFk
JOIN vn.supplier s ON s.id = e.supplierFk
JOIN vn.travel tr ON tr.id = e.travelFk
JOIN vn.agencyMode a ON a.id = tr.agencyModeFk
JOIN vn.warehouse w1 ON w1.id = tr.warehouseInFk
JOIN vn.warehouse w2 ON w2.id = tr.warehouseOutFk
JOIN vn.volumeConfig vc
JOIN vn.item i ON i.id = b.itemFk
JOIN vn.itemType it ON it.id = i.typeFk
WHERE tr.id = vTravelFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travelVolume_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 = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `travelVolume_get`(vFromDated DATE, vToDated DATE, vWarehouseFk INT)
BEGIN
SELECT tr.landed Fecha,
a.name Agencia,
count(DISTINCT e.id) numEntradas,
FLOOR(sum(item_getVolume(b.itemFk, b.packagingFk) * b.stickers / 1000000 )) AS m3
FROM vn.travel tr
JOIN vn.agencyMode a ON a.id = tr.agencyModeFk
JOIN vn.entry e ON e.travelFk = tr.id
JOIN vn.buy b ON b.entryFk = e.id
WHERE tr.landed BETWEEN vFromDated AND vToDated
AND e.isRaid = FALSE
AND tr.warehouseInFk = vWarehouseFk
GROUP BY tr.landed , a.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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travel_checkDates` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travel_checkPackaging` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_checkPackaging`(vSelf INT)
BEGIN
DECLARE vDone BOOL;
DECLARE vEntryFk INT;
DECLARE cTravelEntries CURSOR FOR
SELECT id
FROM entry
WHERE entry.travelFk = vSelf;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
OPEN cTravelEntries;
l: LOOP
SET vDone = FALSE;
FETCH cTravelEntries INTO vEntryFk;
IF vDone THEN
LEAVE l;
END IF;
CALL entry_checkPackaging(vEntryFk);
END LOOP;
CLOSE cTravelEntries;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travel_checkWarehouseIsFeedStock` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_checkWarehouseIsFeedStock`(vWarehouseFk INT)
proc: BEGIN
/*
* Check that the warehouse is not Feed Stock
*
* @vWarehouseFk param warehouse id
*/
IF vWarehouseFk IS NULL THEN
LEAVE proc;
END IF;
IF (SELECT isFeedStock FROM warehouse WHERE id = vWarehouseFk) THEN
CALL util.throw('Cannot create a travel with a source warehouse marked isFeedStock');
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travel_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_clone`(vSelf INT, vDays INT, OUT vNewTravelFk INT)
BEGIN
/**
* Clona un travel el número de dias indicado y devuelve su id.
*
* @param vSelf Identificador de vn.travel
* @param vDays Número de dias a futuro
* @return vNewTravelFk Nuevo número de travel
*/
SELECT tr.id INTO vNewTravelFk
FROM vn.travel tr
JOIN vn.travel tr2 USING(shipped, warehouseInFk, warehouseOutFk, agencyModeFk, `ref`)
WHERE tr2.id = vSelf
AND tr.landed = TIMESTAMPADD(DAY, vDays, tr2.landed);
IF ISNULL(vNewTravelFk) THEN
START TRANSACTION;
INSERT INTO vn.travel( shipped,
shipmentHour,
landed,
landingHour,
warehouseInFk,
warehouseOutFk,
agencyModeFk,
`ref`,
cargoSupplierFk,
clonedFrom)
SELECT shipped,
shipmentHour,
TIMESTAMPADD(DAY, vDays, landed),
landingHour,
warehouseInFk,
warehouseOutFk,
agencyModeFk,
`ref`,
cargoSupplierFk,
vSelf
FROM vn.travel
WHERE id = vSelf;
SELECT LAST_INSERT_ID() INTO vNewTravelFk;
COMMIT;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travel_cloneWithEntries` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_cloneWithEntries`(
IN vTravelFk INT,
IN vDateStart DATE,
IN vDateEnd DATE,
IN vWarehouseOutFk INT,
IN vWarehouseInFk INT,
IN vRef VARCHAR(255),
IN vAgencyModeFk INT,
OUT vNewTravelFk INT)
BEGIN
/**
* Clona un travel junto con sus entradas y compras
* @param vTravelFk travel plantilla a clonar
* @param vDateStart fecha del shipment del nuevo travel
* @param vDateEnd fecha del landing del nuevo travel
* @param vWarehouseOutFk warehouse del salida del nuevo travel
* @param vWarehouseInFk warehouse de landing del nuevo travel
* @param vRef referencia del nuevo travel
* @param vAgencyModeFk del nuevo travel
* @param vNewTravelFk id del nuevo travel
*/
DECLARE vNewEntryFk INT;
DECLARE vEvaNotes VARCHAR(255);
DECLARE vDone BOOL;
DECLARE vAuxEntryFk INT;
DECLARE vTx BOOLEAN DEFAULT @@in_transaction;
DECLARE vRsEntry CURSOR FOR
SELECT e.id
FROM entry e
JOIN travel t ON t.id = e.travelFk
WHERE e.travelFk = vTravelFk;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
CALL util.tx_rollback(vTx);
RESIGNAL;
END;
CALL util.tx_start(vTx);
INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, `ref`, isDelivered, isReceived, m3, cargoSupplierFk, kg,clonedFrom)
SELECT vDateStart, vDateEnd, vWarehouseInFk, vWarehouseOutFk, vAgencyModeFk, vRef, isDelivered, isReceived, m3,cargoSupplierFk, kg,vTravelFk
FROM travel
WHERE id = vTravelFk;
SET vNewTravelFk = LAST_INSERT_ID();
SET vDone = FALSE;
SET @isModeInventory = TRUE;
OPEN vRsEntry;
l: LOOP
SET vDone = FALSE;
FETCH vRsEntry INTO vAuxEntryFk;
IF vDone THEN
LEAVE l;
END IF;
CALL entry_cloneHeader(vAuxEntryFk, vNewEntryFk, vNewTravelFk);
CALL entry_copyBuys(vAuxEntryFk, vNewEntryFk);
SELECT evaNotes INTO vEvaNotes
FROM entry
WHERE id = vAuxEntryFk;
UPDATE entry
SET evaNotes = vEvaNotes
WHERE id = vNewEntryFk;
END LOOP;
SET @isModeInventory = FALSE;
CLOSE vRsEntry;
CALL util.tx_commit(vTx);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travel_getDetailFromContinent` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_getDetailFromContinent`(
vContinentFk INT
)
BEGIN
/**
* Devuelve los detalles de los vuelos que tienen
* un almacén de salida de un continente.
*
* @param vContinentFk Id de continente
*/
DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL 12 WEEK;
SELECT IFNULL(CONCAT(" ", entryFk), travelFk) travelAndEntry,
sub.*
FROM (
SELECT tr.id travelFk,
NULL entryFk,
TRUE isTravel,
am.name agency,
tr.ref,
tr.shipped,
wOut.name originBoxes,
tr.landed,
wIn.name destination,
SUM(b.stickers) stickers,
NULL evaNotes,
tr.kg,
CAST(SUM(b.weight * b.stickers) AS INT) loadedkg,
CAST(
SUM(vc.aerealVolumetricDensity *
b.stickers *
IF(p.volume,
p.volume,
p.width * p.depth * p.height
) / 1000000
) AS INT
) volumeKg,
NULL loadPriority,
NULL invoiceAmount,
s.nickname freighter,
NULL reference
FROM travel tr
LEFT JOIN supplier s ON s.id = tr.cargoSupplierFk
LEFT JOIN entry e ON e.travelFk = tr.id
LEFT JOIN buy b ON b.entryFk = e.id
LEFT JOIN packaging p ON p.id = b.packagingFk
LEFT JOIN item i ON i.id = b.itemFk
LEFT JOIN itemType it ON it.id = i.typeFk
JOIN warehouse wIn ON wIn.id = tr.warehouseInFk
JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk
JOIN country co ON co.id = wOut.countryFk
JOIN agencyMode am ON am.id = tr.agencyModeFk
JOIN volumeConfig vc
WHERE tr.landed >= vDateFrom
AND co.continentFk = vContinentFk
GROUP BY tr.id
UNION ALL
SELECT e.travelFk,
e.id,
FALSE,
s.name,
e.invoiceNumber,
tr.shipped,
wOut.name,
tr.landed,
wIn.name,
SUM(b.stickers),
e.evaNotes,
NULL,
CAST(SUM(b.weight * b.stickers) AS INT),
CAST(
SUM(vc.aerealVolumetricDensity *
b.stickers *
IF(p.volume,
p.volume,
p.width * p.depth * p.height
) / 1000000
) AS INT
),
loadPriority,
e.invoiceAmount,
s2.nickname,
e.reference
FROM entry e
JOIN buy b ON b.entryFk = e.id
JOIN packaging p ON p.id = b.packagingFk
JOIN item i ON i.id = b.itemFk
JOIN itemType it ON it.id = i.typeFk
JOIN supplier s ON s.id = e.supplierFk
JOIN travel tr ON tr.id = e.travelFk
LEFT JOIN supplier s2 ON s2.id = tr.cargoSupplierFk
JOIN warehouse wIn ON wIn.id = tr.warehouseInFk
JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk
JOIN country co ON co.id = wOut.countryFk
JOIN volumeConfig vc
WHERE tr.landed >= vDateFrom
AND co.continentFk = vContinentFk
GROUP BY e.id
) sub
ORDER BY landed ASC,
shipped ASC,
travelFk,
isTravel DESC,
(loadPriority > 0) DESC,
loadPriority,
agency,
evaNotes;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travel_getEntriesMissingPackage` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb3 */ ;
/*!50003 SET character_set_results = utf8mb3 */ ;
/*!50003 SET collation_connection = utf8mb3_general_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_getEntriesMissingPackage`(vSelf INT)
BEGIN
DECLARE vpackageOrPackingNull INT;
DECLARE vTravelFk INT;
SELECT travelfk INTO vTravelFk
FROM entry
WHERE id = vSelf;
SELECT e.id entryFk
FROM travel t
JOIN entry e ON e.travelFk = t.id
JOIN buy b ON b.entryFk = e.id
WHERE t.id = vTravelFk
AND (b.packing IS NULL OR b.packagingFk 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travel_moveRaids` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_moveRaids`()
BEGIN
/*
* Desplaza al dia siguiente los travels que contengan redadas y avisa a los compradores
*
*/
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vWorkerName VARCHAR(50);
DECLARE vRaid TEXT;
DECLARE vWorker VARCHAR(50) DEFAULT '';
DECLARE vMailBody TEXT DEFAULT '';
DECLARE vCur CURSOR FOR
SELECT GROUP_CONCAT( DISTINCT CONCAT('https://salix.verdnatura.es/#!/travel/', ttr.id, '/summary ') ORDER BY ttr.id SEPARATOR '\n\r'),
u.name
FROM tmp.travel ttr
JOIN entry e ON e.travelFk = ttr.id
JOIN buy b ON b.entryFk = e.id
JOIN item i ON i.id = b.itemFk
JOIN itemType it ON it.id = i.typeFk
JOIN account.user u ON u.id = it.workerFk
GROUP BY u.name;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
DROP TEMPORARY TABLE IF EXISTS tmp.travel;
CREATE TEMPORARY TABLE tmp.travel
SELECT tr.id,tr.landed
FROM travel tr
JOIN entry e ON e.travelFk = tr.id
WHERE tr.landed = util.tomorrow()
AND e.isRaid
GROUP BY tr.id;
START TRANSACTION;
UPDATE travel tr
JOIN tmp.travel ttr ON ttr.id = tr.id
SET tr.landed = TIMESTAMPADD(DAY, 1, tr.landed);
OPEN vCur;
l: LOOP
SET vDone = FALSE;
FETCH vCur INTO vRaid, vWorkerName;
IF vDone THEN
LEAVE l;
END IF;
CALL `vn`.`mail_insert`(CONCAT(vWorkerName, '@verdnatura.es'),
'noreply@verdnatura.es',
'Cambio de fecha en Redadas',
CONCAT('Se ha movido las siguientes redadas: \n\r ', vRaid)
);
END LOOP;
CLOSE vCur;
COMMIT;
DROP TEMPORARY TABLE tmp.travel;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travel_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_recalc`(vSelf INT)
proc: BEGIN
/**
* Updates the number of entries assigned to the travel.
*
* @param vSelf The travel id
*/
UPDATE travel
SET totalEntries = (
SELECT COUNT(id)
FROM entry
WHERE travelFk = vSelf
)
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travel_upcomingArrivals` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_upcomingArrivals`(
vWarehouseFk INT,
vDate DATETIME
)
BEGIN
/**
* Procedure to track and organize the movement of items between warehouses,
* where 'warehouseINFk' is @vWarehouseFk.
* Uses temporary tables to process and store the travel data of the items.
*
* @params vWarehouseFk warehouse id
* @params vDate selected landed date
* @return tmp.itemTravel
*/
DECLARE vTravelFk INT;
DECLARE vWarehouseOutFk INT;
DECLARE vShipment DATETIME;
DECLARE vDateStart DATETIME;
CREATE OR REPLACE TEMPORARY TABLE tTravelTop
(PRIMARY KEY (wh_in,wh_out,landing,shipment))
ENGINE = MEMORY
SELECT 0 id,
vWarehouseFk wh_in,
vWarehouseFk wh_out,
FALSE ok,
vDate landing,
vDate shipment;
REPEAT
SET vTravelFk = NULL;
SELECT id,
wh_out,
shipment,
landing
INTO vTravelFk,
vWarehouseOutFk,
vShipment,
vDateStart
FROM tTravelTop
WHERE ok = FALSE LIMIT 1;
UPDATE tTravelTop
SET ok = TRUE
WHERE id = vTravelFk;
INSERT IGNORE INTO tTravelTop
SELECT id,
vWarehouseFk,
warehouseOutFk,
FALSE,
IF(vTravelFk, vDateStart, landed),
shipped shipment
FROM travel
WHERE warehouseOutFk = vWarehouseOutFk
AND IF(vTravelFk, landed <= vShipment, landed >= vShipment)
AND shipped >= util.VN_CURDATE()
AND NOT isDelivered;
UNTIL vTravelFk IS NULL END REPEAT;
DELETE FROM tTravelTop WHERE id = 0;
CREATE OR REPLACE TEMPORARY TABLE tmp.itemTravel
(KEY (wh))
ENGINE = MEMORY
SELECT *
FROM (
SELECT wh_out wh,
landing
FROM tTravelTop
WHERE wh_out <> vWarehouseFk
ORDER BY landing
LIMIT 10000000000000000000
) t
GROUP BY wh;
DROP TEMPORARY TABLE tTravelTop;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `travel_updatePacking` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_updatePacking`(vItemFk INT, vPacking INT)
BEGIN
/**
* Actualiza packing para los movimientos de almacén de la subasta al almacén central
*
* @param vItemFk id del item
* @param vPacking nuevo packing
*/
DECLARE vAuctionWarehouseFk INT;
DECLARE vMainWarehouseFk INT;
SELECT warehouseFk INTO vAuctionWarehouseFk
FROM auctionConfig;
SELECT mainWarehouseFk INTO vMainWarehouseFk
FROM config;
UPDATE entry e
JOIN travel t ON t.id = e.travelFk
JOIN buy b on b.entryFk = e.id
SET b.packing = vPacking
WHERE t.shipped >= util.dayEnd(CURDATE())
AND t.warehouseInFk = vMainWarehouseFk
AND t.warehouseOutFk = vAuctionWarehouseFk
AND b.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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_weeklyClone`(vSinceWeek INT, vToWeek INT)
BEGIN
/**
* Clona los traslados plantilla para las semanas pasadas por parámetros.
*
* @param vSinceWeek Número de semanas en el futuro para empezar a clonar
* @param vToWeek Número de semenas en el futuro hasta donde clonar
*/
DECLARE vCounter INT;
DECLARE vCurrentTravelFk INT;
DECLARE vShipped DATE;
DECLARE vLanded DATE;
DECLARE vWarehouseInFk INT;
DECLARE vWarehouseOutFk INT;
DECLARE vAgencyModeFk INT;
DECLARE vRef VARCHAR(255);
DECLARE vNewTravelFk INT;
DECLARE vDone BOOL;
DECLARE vRsTravel CURSOR FOR
SELECT travelFk,
@a := TIMESTAMPADD(DAY,vCounter * 7 - WEEKDAY(util.VN_CURDATE()) - 1 + weekDay, util.VN_CURDATE()),
@a := TIMESTAMPADD(DAY,duration,@a),
warehouseOutFk,
warehouseInFk,
`ref`,
agencyModeFk
FROM travelClonedWeekly
WHERE travelFk;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SET vCounter = vSinceWeek;
vWeekLoop :LOOP
INSERT IGNORE INTO travel (shipped, landed, warehouseOutFk, warehouseInFk, agencyModeFk, ref, cargoSupplierFk, kg)
SELECT @a := TIMESTAMPADD(DAY, vCounter * 7 - WEEKDAY(util.VN_CURDATE()) - 1 + weekDay, util.VN_CURDATE()),
@a := TIMESTAMPADD(DAY, duration, @a),
warehouseOutFk,
warehouseInFk,
agencyModeFk,
ref,
supplierFk,
kg
FROM travelClonedWeekly
WHERE travelFk IS NULL;
OPEN vRsTravel;
l: LOOP
SET vDone = FALSE;
FETCH vRsTravel INTO vCurrentTravelFk, vShipped, vLanded, vWarehouseOutFk, vWarehouseInFk, vRef, vAgencyModeFk;
IF vDone THEN
LEAVE l;
END IF;
BEGIN
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION RESIGNAL SQLSTATE '01000';
CALL travel_cloneWithEntries(vCurrentTravelFk, vShipped, vLanded, vWarehouseOutFk, vWarehouseInFk, vRef, vAgencyModeFk, vNewTravelFk);
END;
END LOOP;
CLOSE vRsTravel;
IF vCounter = vToWeek THEN
LEAVE vWeekLoop;
END IF;
SET vCounter = vCounter + 1;
END LOOP vWeekLoop;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `typeTagMake`(vTypeFk INT)
BEGIN
/*
* Plantilla para modificar reemplazar todos los tags
* por los valores que tienen los articulos
*
* @param vTypeFk tipo a modificar
*
*/
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `vehicle_checkNumberPlate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `vehicle_checkNumberPlate`(vNumberPlate VARCHAR(10), vCountryCodeFk VARCHAR(2))
BEGIN
/**
* Comprueba si la matricula pasada tiene el formato correcto dependiendo del pais del vehiculo
*/
DECLARE vRegex VARCHAR(45);
SELECT vp.regex INTO vRegex
FROM vehiclePlateRegex vp
WHERE vp.countryCodeFk = vCountryCodeFk;
IF NOT vNumberPlate REGEXP BINARY (vRegex)THEN
CALL util.throw(CONCAT('Error: la matricula ', vNumberPlate, ' no es valida para ',vCountryCodeFk));
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `vehicle_notifyEvents` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `vehicle_notifyEvents`()
proc:BEGIN
/**
* Query the vehicleEvent table to see if there are any events that need to be notified.
*
*/
DECLARE vEventEarlyDays INT;
DECLARE vHasEvents INT;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
SELECT eventEarlyDays INTO vEventEarlyDays
FROM vehicleConfig;
DROP TEMPORARY TABLE IF EXISTS tEvents;
CREATE TEMPORARY TABLE tEvents
SELECT e.id
FROM vehicleEvent e
JOIN vehicleState s ON e.vehicleStateFk = s.id
WHERE e.finished BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY, vEventEarlyDays, util.VN_CURDATE())
AND e.notified IS NULL
AND s.hasToNotify;
SELECT COUNT(id) INTO vHasEvents FROM tEvents;
IF NOT vHasEvents THEN
LEAVE proc;
END IF;
START TRANSACTION;
SELECT util.notification_send('vehicle-event-expired',
JSON_OBJECT('eventIds', JSON_ARRAYAGG(id)),
account.myUser_getId()
)
FROM tEvents;
UPDATE vehicleEvent e
JOIN tEvents s ON e.id = s.id
SET e.notified = util.VN_NOW()
WHERE e.id = s.id;
COMMIT;
DROP TEMPORARY TABLE IF EXISTS tEvents;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `visible_getMisfit` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `visible_getMisfit`(vSectorFk INT)
BEGIN
/* Devuelve una tabla temporal con los descuadres entre el visible teórico y lo ubicado en la práctica
*
* @param vSectorFk Identificador de vn.sector
*
* @return tmp.stockMisfit(itemFk, visible, parked)
*/
DECLARE vCalcVisibleFk INT;
DECLARE vWarehouseFk INT;
SELECT warehouseFk INTO vWarehouseFk
FROM vn.sector s
WHERE s.id = vSectorFk;
CALL cache.visible_refresh(vCalcVisibleFk, FALSE, vWarehouseFk);
DROP TEMPORARY TABLE IF EXISTS tmp.stockMisfit;
CREATE TEMPORARY TABLE tmp.stockMisfit(
itemFk INT PRIMARY KEY,
visible INT NOT NULL DEFAULT 0,
parked INT NOT NULL DEFAULT 0)
ENGINE = MEMORY;
INSERT INTO tmp.stockMisfit(itemFk, parked)
SELECT iss.itemFk , sum(iss.visible )
FROM vn.itemShelvingStock iss
JOIN vn.sector s ON s.id = iss.sectorFk
WHERE vSectorFk IN (s.id, s.sonFk)
GROUP BY iss.itemFk;
INSERT INTO tmp.stockMisfit(itemFk, visible)
SELECT v.item_id , v.visible
FROM cache.visible v
WHERE v.calc_id = vCalcVisibleFk
ON DUPLICATE KEY UPDATE visible = v.visible;
DELETE FROM tmp.stockMisfit
WHERE visible = parked;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerCalendar_calculateBusiness` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerCalendar_calculateBusiness`(vYear INT, vBusinessFk INT)
BEGIN
/**
* Calcula los días y horas de vacaciones en función de un contrato y año
*
* @param vYear
* @param vBusinessFk
* @return tmp.workerCalendarCalculateBusiness (days, hours, daysEnjoyed, hoursEnjoyed)
*/
DECLARE vStarted DATE;
DECLARE vEnded DATE;
DECLARE vDaysHoliday DECIMAL(5,2);
DECLARE vHoursWeek DECIMAL(5,2);
DECLARE vDaysToSubtract DECIMAL(5,2);
DECLARE vDaysHolidayEnjoyed DECIMAL(5,2);
DECLARE vPayedHolidays DECIMAL(5,2);
DECLARE vDifDays INT;
SELECT IF(b.started < CONCAT(vYear,"-01-01"), CONCAT(vYear,"-01-01"),b.started),
IF(b.ended IS NULL OR YEAR(b.ended)>vYear , CONCAT(vYear,"-12-31"), b.ended),
IF(wbt.hasHolidayEntitlement, w.days, 0),
c.hoursWeek,
IF(YEAR(b.ended) = vYear, b.payedHolidays, 0) payedHolidays
INTO vStarted,
vEnded,
vDaysHoliday,
vHoursWeek,
vPayedHolidays
FROM business b
JOIN workerBusinessType wbt ON wbt.id = b.workerBusinessTypeFk
JOIN workCenterHoliday w ON w.workcenterFk = b.workcenterFk
LEFT JOIN calendarType c ON c.id = b.calendarTypeFk
WHERE b.id = vBusinessFk
AND w.year = vYear;
DROP TEMPORARY TABLE IF EXISTS tmp.workerCalendarCalculateBusiness;
IF vStarted < vEnded THEN
SET vDifDays = DAYOFYEAR(vEnded) - DAYOFYEAR(vStarted) + 1;
SELECT IFNULL(SUM(a.holidayEntitlementRate), 0),
SUM(-(a.discountRate - 1)) + vPayedHolidays
INTO vDaysToSubtract,
vDaysHolidayEnjoyed
FROM calendar c
JOIN absenceType a ON a.id = c.dayOffTypeFk
JOIN business b ON b.id = c.businessFk
WHERE b.id = vBusinessFk
AND YEAR(c.dated) = vYear;
END IF;
CREATE TEMPORARY TABLE tmp.workerCalendarCalculateBusiness
ENGINE = MEMORY
SELECT @days := IFNULL(ROUND((vDaysHoliday * (vDifDays - vDaysToSubtract) / IF(util.isLeapYear(vYear) , 366, 365)), 1), 0) days,
@days * (vHoursWeek / 5) hours,
@daysEnjoyed := IFNULL(ROUND(vDaysHolidayEnjoyed, 1), 0) daysEnjoyed,
@daysEnjoyed * (vHoursWeek / 5) hoursEnjoyed;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerCalendar_calculateYear` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerCalendar_calculateYear`(vYear INT, vWorkerFk INT)
BEGIN
/**
* Calcula los días y horas de vacaciones en función de un trabajador y año
*
* @param vYear
* @param vWorkerFk
* @return tmp.workerCalendarCalculateYear (days, hours, daysEnjoyed, hoursEnjoyed)
*/
DECLARE vDone BOOL;
DECLARE vBusinessFk INT;
DECLARE cur CURSOR FOR
SELECT b.id
FROM business b
WHERE vYear BETWEEN YEAR(b.started) AND IFNULL(YEAR(b.ended), vYear)
AND b.workerFk = vWorkerFk;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET vDone = TRUE;
DROP TEMPORARY TABLE IF EXISTS tmp.workerCalendarCalculateYear;
CREATE TEMPORARY TABLE tmp.workerCalendarCalculateYear
(days DEC(5,2),
hours DEC(5,2),
daysEnjoyed DEC(5,2),
hoursEnjoyed DEC(5,2))
ENGINE = MEMORY;
INSERT INTO tmp.workerCalendarCalculateYear VALUES(0, 0, 0, 0);
OPEN cur;
l: LOOP
SET vDone = FALSE;
FETCH cur INTO vBusinessFk;
IF vDone THEN
LEAVE l;
END IF;
CALL workerCalendar_calculateBusiness(vYear, vBusinessFk);
UPDATE tmp.workerCalendarCalculateYear w
JOIN tmp.workerCalendarCalculateBusiness wc
SET w.days = w.days + wc.days,
w.hours = w.hours + wc.hours,
w.daysEnjoyed = w.daysEnjoyed + wc.daysEnjoyed,
w.hoursEnjoyed = w.hoursEnjoyed + wc.hoursEnjoyed;
DROP TEMPORARY TABLE tmp.workerCalendarCalculateBusiness;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 vSurnames VARCHAR(100);
INSERT INTO account.`user`(name, nickname, password, `role`, hasGrant)
SELECT vUser, vUser, MD5(vPassword), vRole, false;
SET vUserId = LAST_INSERT_ID();
IF vSurname2 IS NULL THEN
SET vSurnames = vSurname1;
ELSE
SET vSurnames = CONCAT(vSurname1, ' ', vSurname2);
END IF;
INSERT INTO worker(id, firstName, lastName, code, isFreelance)
SELECT vUserId, vFirstName, vSurnames, vWorkerCode, 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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerDepartmentByDate`(vDate DATE)
BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp.workerDepartmentByDate;
CREATE TEMPORARY TABLE tmp.workerDepartmentByDate
ENGINE = MEMORY
SELECT w.id userFk,
w.lastName name,
w.firstName firstname,
d.name department,
d.id departmentFk,
b.started,
d.isProduction,
CAST(12 * b.amount / ct.hoursWeek / 52 AS DECIMAL(10,2)) costeHora,
w.fi nif
FROM business b
JOIN calendarType ct ON ct.id = b.calendarTypeFk
JOIN department d ON d.id = b.departmentFk
JOIN worker w ON w.id = b.workerFk
WHERE b.started <= vDate
AND (b.ended > vDate OR b.ended 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerDisable`(vUserId int)
mainLabel:BEGIN
IF (SELECT COUNT(*) FROM workerDisableExcluded WHERE workerFk = vUserId AND (dated > util.VN_CURDATE() OR dated IS NULL)) > 0 THEN
LEAVE mainLabel;
END IF;
DELETE cp FROM clientProtected cp
JOIN client c ON c.id = cp.clientFk
WHERE c.salesPersonFk = vUserId;
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;
UPDATE `client` c
SET c.salesPersonFk = null
WHERE c.salesPersonFk = 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerDisableAll`()
BEGIN
DECLARE done BOOL DEFAULT FALSE;
DECLARE vUserFk INT;
DECLARE rs CURSOR FOR
SELECT b.workerFk
FROM business b
JOIN vn.worker w ON w.id = b.workerFk
JOIN account.account a ON a.id = b.workerFk
LEFT JOIN (SELECT b.workerFk
FROM business b
WHERE (ended IS NULL OR ended >=util.VN_CURDATE())
)sub ON sub.workerFk = a.id
LEFT JOIN vn.workerDisableExcluded wd ON wd.workerFk = b.workerFk
WHERE sub.workerFk IS NULL
AND wd.workerFk IS NULL
GROUP BY w.id;
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerJourney_replace`(
vDatedFrom DATE,
vDatedTo DATE,
vWorkerFk INT)
BEGIN
/**
* Actualiza la tabla workerJourney para que actue como caché permanente revisable
* de las jornadas laborales.
* @param vDatedFrom workerTimeControl
* @param vDatedTo workerTimeControl
* @param vWorkerFk, en caso de pasar 0 ó NULL se aplica a todos
*/
DECLARE vDatedTimeTo DATETIME;
DECLARE vMaxTimePerDay INT;
DECLARE vMinHoursToBreak DECIMAL(10,2);
DECLARE vBreakHours DECIMAL(10,2);
DECLARE vMonthByYear INT;
DECLARE vWeeksByYear INT DEFAULT 52;
DECLARE vMonthsByYear INT DEFAULT 12;
DECLARE vDaysByWeek INT DEFAULT 5;
DECLARE vDatedFromYesterday DATETIME;
DECLARE vDatedToTomorrow DATETIME;
SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY)
INTO vDatedFromYesterday, vDatedToTomorrow;
SET vDatedTimeTo = util.dayEnd(vDatedTo);
SELECT minHoursToBreak, breakHours, maxTimePerDay
INTO vMinHoursToBreak, vBreakHours, vMaxTimePerDay
FROM workerTimeControlConfig;
DELETE FROM workerJourney
WHERE dated BETWEEN vDatedFrom AND vDatedTo
AND NOT isPaid
AND NOT isUpdated
AND (vWorkerFk IS NULL OR userFK = vWorkerFk);
-- Se inserta todos los días del periodo por worker y business en el rango de fechas.
INSERT IGNORE INTO workerJourney(userFk, dated, businessFk)
SELECT b.workerFk, t.dated, b.id
FROM business b
JOIN time t ON t.dated BETWEEN b.started AND IFNULL(b.ended,util.VN_CURDATE())
WHERE t.dated BETWEEN vDatedFrom AND vDatedTo
AND (vWorkerFk IS NULL OR b.workerFk = vWorkerFk)
ORDER BY b.workerFk, t.dated, b.id;
DROP TEMPORARY TABLE IF EXISTS tmp.`user`;
IF vWorkerFk THEN
CALL timeControl_calculateByUser(vWorkerFk, vDatedFrom , vDatedTimeTo);
CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user`
SELECT vWorkerFk userFk;
ELSE
CALL timeControl_calculateAll(vDatedFrom, vDatedTimeTo);
CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user`
SELECT id userFk
FROM worker w;
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 >= vMinHoursToBreak,
t.timeWorkDecimal - vBreakHours,
t.timeWorkDecimal) AS DECIMAL (10,2)),
wj.lunch = IF(t.timeWorkDecimal >= vMinHoursToBreak , vBreakHours , 0)
WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo
AND NOT wj.isPaid
AND NOT wj.isUpdated
AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk);
-- NOCTURNIDAD
CALL timeControl_getError(vDatedFrom, vDatedTimeTo);
SET @vIsOdd := TRUE;
SET @vDated := NULL;
DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControl;
CREATE TEMPORARY TABLE tmp.workerTimeControl
(INDEX (userFk), INDEX (timed))
ENGINE = MEMORY
SELECT DISTINCT(wtc.id),
wtc.userFk,
wtc.timed,
wtc.direction
FROM workerTimeControl wtc
JOIN tmp.`user` w ON w.userFk = wtc.userFk
LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
WHERE wtc.timed BETWEEN vDatedFrom AND vDatedToTomorrow
AND tce.id IS NULL
AND (vWorkerFk IS NULL OR wtc.userFk = vWorkerFk)
ORDER BY wtc.userFk, wtc.timed ASC;
SELECT MAX(id) INTO @vCont
FROM tmp.workerTimeControl;
DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux;
CREATE TEMPORARY TABLE tmp.workerTimeControlAux (
`id` int(11) ,
`userFk` int(10) unsigned ,
`timed` datetime,
`direction` enum('in', 'out','middle')
) ENGINE=MEMORY;
SET @vIsOdd := TRUE;
SET @lastUserFk := NULL;
SET @lastDirection := NULL;
-- Cambio de dia en medio de un descanso
INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction)
SELECT @vCont:= @vCont + 1,
lastUserFk,
util.dayEnd(dated),
'middle'
FROM (SELECT IF(@lastUserFk <> userFk, @vIsOdd := TRUE, NULL),
DATE(@lastTimed) dated,
@lastUserFk lastUserFk,
IF(direction ='middle', @vIsOdd := NOT @vIsOdd, FALSE) isOdd,
IF(@vIsOdd
AND @lastDirection = 'middle'
AND (DATE(@lastTimed) <> date(timed)
OR @lastUserFk <> userFk), TRUE, FALSE) hasBreak,
@lastTimed := wtc.timed,
@lastUserFk := userFk,
@lastDirection := direction
FROM tmp.workerTimeControl wtc
ORDER BY wtc.userFk, wtc.timed)sub
WHERE hasBreak;
SET @vIsOdd := TRUE;
SET @lastUserFk := NULL;
SET @lastDirection := NULL;
INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction)
SELECT @vCont:= @vCont + 1,
lastUserFk,
DATE_ADD(sub.dated, INTERVAL 1 DAY),
'middle'
FROM (SELECT IF(@lastUserFk <> userFk, @vIsOdd := TRUE, NULL),
DATE(@lastTimed) dated,
@lastUserFk lastUserFk,
IF(direction ='middle', @vIsOdd := NOT @vIsOdd, FALSE) isOdd,
IF(@vIsOdd
AND @lastDirection = 'middle'
AND (DATE(@lastTimed)<>date(timed)
OR @lastUserFk<>userFk), TRUE, FALSE) hasBreak,
@lastTimed := wtc.timed,
@lastUserFk := userFk,
@lastDirection := direction
FROM tmp.workerTimeControl wtc
ORDER BY wtc.userFk, wtc.timed)sub
WHERE hasBreak;
-- Cambio de dia
INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction)
SELECT @vCont:= @vCont + 1,
wtc.userFk,
util.dayEnd(date(wtc.timed)),
'out'
FROM workerTimeControl wtc
JOIN tmp.`user` w ON w.userFk = wtc.userFk
LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
AND wtc.direction <> 'out'
GROUP BY wtc.userFk, DATE(wtc.timed);
INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction)
SELECT @vCont:= @vCont + 1,
wtc.userFk,
DATE_ADD(date(wtc.timed), INTERVAL 1 DAY),
'in'
FROM workerTimeControl wtc
JOIN tmp.`user` w ON w.userFk = wtc.userFk
LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow
AND wtc.direction <> 'out'
GROUP BY wtc.userFk, DATE(wtc.timed);
INSERT INTO tmp.workerTimeControl (id, userFk, timed, direction)
SELECT id, userFk, timed, direction
FROM tmp.workerTimeControlAux;
SET @lastUserFk := NULL;
SET @vIsOdd := TRUE;
SET @vDated := NULL;
SET @vLastTimed := NULL;
UPDATE workerJourney wj
JOIN (SELECT sub.dated, userFk, SUM(NigthlyHours) NigthlyHours
FROM(SELECT (@vIsOdd := NOT @vIsOdd) isOdd,
IF(direction='in', @vIsOdd := TRUE, @vIsOdd := @vIsOdd),
IF(@vIsOdd, @vLastTimed:=UNIX_TIMESTAMP(timed),@vLastTimed),
IF(direction='in', @vDated := DATE(wtc.timed), @vDated ) dated,
wtc.userFk,
IF(UNIX_TIMESTAMP(timed)- @vLastTimed < vMaxTimePerDay,
workerNigthlyHours_calculate(FROM_UNIXTIME(@vLastTimed), wtc.timed),
0) NigthlyHours,
@lastUserFk := userFk
FROM (SELECT DISTINCT(wtc.id), wtc.userFk, wtc.timed, wtc.direction
FROM tmp.workerTimeControl wtc
LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id
WHERE wtc.timed BETWEEN vDatedFrom AND util.dayEnd(vDatedToTomorrow)
AND tce.id IS NULL
ORDER BY userFk, timed ASC
LIMIT 10000000000000000000
) wtc
ORDER BY wtc.userFk, wtc.timed
)sub
WHERE sub.dated BETWEEN vDatedFrom AND vDatedTo
GROUP BY userFk, sub.dated
)night ON night.userFk = wj.userFk AND night.dated = wj.dated
SET wj.nocturn = night.NigthlyHours
WHERE NOT wj.isPaid
AND NOT isUpdated
AND night.NigthlyHours <> 0;
-- Horas téoricas y precio de la hora ordinaria
UPDATE workerJourney wj
JOIN business b ON b.id = wj.businessFk
JOIN calendarType ct ON ct.id = b.calendarTypeFk
SET wj.priceOrdinaryHour =
(vMonthsByYear * b.amount) /
(vWeeksByYear * ct.hoursWeek),
wj.contractJourney = ct.hoursWeek / vDaysByWeek
WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo
AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk)
AND NOT wj.isPaid
AND NOT isUpdated;
-- Precio Extras, Vacaciones y Nocturnas
UPDATE workerJourney wj
JOIN(SELECT MAX(w.dated), t.dated, w.holidayInc, w.nightInc, w.extraInc
FROM time t
JOIN workerHourPrice w ON w.dated <= t.dated
WHERE t.dated BETWEEN vDatedFrom AND vDatedTo
GROUP BY t.dated
) sub ON sub.dated = wj.dated
SET wj.priceHolidayHour = wj.priceOrdinaryHour * sub.holidayInc,
wj.priceNocturnHour = wj.priceOrdinaryHour * sub.nightInc,
wj.priceExtraHour = wj.priceOrdinaryHour * sub.extraInc
WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo
AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk)
AND NOT wj.isPaid
AND NOT wj.isUpdated;
-- Elimina el precio de las horas extras para los contratos parciales.
UPDATE workerJourney wj
JOIN business b ON b.id = wj.businessFk
JOIN calendarType ct ON ct.id = b.calendarTypeFk
SET wj.priceExtraHour = 0
WHERE ct.isPartial
AND wj.dated BETWEEN vDatedFrom AND vDatedTo
AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk)
AND NOT wj.isPaid
AND NOT wj.isUpdated;
-- Ausencias
UPDATE workerJourney wj
JOIN businessCalendar bc ON bc.businessFk = wj.businessFk
AND bc.dated = wj.dated
JOIN absenceType ab ON ab.id = bc.absenceTypeFk
SET wj.permission = ab.permissionRate * wj.contractJourney,
wj.contractJourney = IF(ab.permissionRate = 1, 0, ab.permissionRate) * wj.contractJourney
WHERE ab.permissionRate > 0
AND wj.dated BETWEEN vDatedFrom AND vDatedTo
AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk)
AND NOT wj.isPaid
AND NOT wj.isUpdated;
-- Sábados / Domingos
UPDATE workerJourney
SET holiday = IF(DAYNAME(dated)='sábado', 0, total),
contractJourney = 0
WHERE DAYNAME(dated) IN ('sábado', 'domingo')
AND dated BETWEEN vDatedFrom AND vDatedTo
AND (vWorkerFk IS NULL OR userFk = vWorkerFk)
AND NOT isPaid
AND NOT isUpdated;
-- Festivos por centro de trabajo
UPDATE workerJourney wj
JOIN calendarHolidays ch ON ch.dated = wj.dated
JOIN business b ON b.id = wj.businessFk
AND b.workcenterFk = ch.workcenterFk
SET wj.holiday = wj.total,
wj.permission = wj.contractJourney,
wj.contractJourney = 0
WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo
AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk)
AND NOT wj.isPaid
AND NOT wj.isUpdated;
-- Horas extras
UPDATE workerJourney
SET extra = lunch + total - contractJourney
WHERE dated BETWEEN vDatedFrom AND vDatedTo
AND (vWorkerFk IS NULL OR userFk = vWorkerFk)
AND NOT isPaid
AND NOT isUpdated;
DROP TEMPORARY TABLE tmp.timeControlCalculate;
DROP TEMPORARY TABLE tmp.`user`;
DROP TEMPORARY TABLE tmp.timeControlError;
DROP TEMPORARY TABLE tmp.workerTimeControlAux;
DROP TEMPORARY TABLE tmp.workerTimeControl;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerMistakeType_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerMistakeType_get`()
BEGIN
/**
* Obtiene los tipos de error para los trabajadores
*/
SELECT code, description
FROM workerMistakeType
ORDER BY 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerMistake_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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerMistake_add`(vWorkerFk INT, vWorkerMistakeTypeFk VARCHAR(10))
BEGIN
/**
* Añade error al trabajador
*
* @param vWorkerFk id del trabajador al cual se le va a añadir error
* @param vWorkerMistakeTypeFk code del tipo de error
*
*/
INSERT INTO vn.workerMistake(userFk, workerMistakeTypeFk)
VALUES(vWorkerFk, vWorkerMistakeTypeFk);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_calculateOddDays` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_calculateOddDays`()
BEGIN
/**
* Calculo de las fichadas impares por empleado y dia.
*
* @return tmp.workerTimeControlOddDays (userFk, dated)
*/
SET @cont := FALSE;
SET @lastUserFk:= NULL;
DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlOddDays;
CREATE TEMPORARY TABLE tmp.workerTimeControlOddDays
SELECT sub2.userFk workerFk, sub2.dated
FROM (
SELECT userFk,
dated,
COUNT(*) cont2
FROM (
SELECT DATE(wtc.timed) dated,
userFk,
IFNULL(@cont, @cont := TRUE ),
IF(direction = 'in' OR userFk <> @lastUserFk, @cont := @cont+1, TRUE),
@cont cont,
@lastUserFk := userFk
FROM workerTimeControl wtc
WHERE wtc.timed BETWEEN TIMESTAMPADD(YEAR,-1,util.VN_CURDATE()) AND util.dayEnd(util.VN_CURDATE())
ORDER BY userFk, timed
LIMIT 10000000000000000000)sub
GROUP BY cont
HAVING cont2 MOD 2 = 1
)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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 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 workerTimeControlParams;
SELECT MAX(timed) INTO vLastIn
FROM workerTimeControl
WHERE userFk = vUserFk
AND direction = 'in';
SELECT MAX(timed) INTO vLastOut
FROM workerTimeControl
WHERE userFk = vUserFk
AND direction = 'out';
SELECT CONCAT(u.name,'@verdnatura.es') INTO vTo
FROM account.user u
WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk);
SELECT CONCAT(firstName,' ',lastName) INTO vUserName
FROM worker w
WHERE w.id = vUserFk;
IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA
-- VERIFICAR DESCANSO DIARIO
IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN
SELECT "Descansos 12 h" AS problem;
-- ENVIAMOS CORREO AL BOSSFK
SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody;
CALL 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 workerTimeControl
WHERE userFk = vUserFk
AND timed >= vLastIn
) THEN
SELECT "Dias con fichadas impares" AS problem;
-- ENVIAMOS CORREO AL BOSSFK
SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody;
CALL mail_insert(vTo,vTo,'error al fichar',vBody);
LEAVE proc;
END IF;
-- VERIFICAR VACACIONES
SELECT at2.name INTO vCalendarStateType
FROM calendar c
JOIN business b ON b.id = c.businessFk
JOIN absenceType at2 ON at2.id = c.dayOffTypeFk
WHERE c.dated = util.VN_CURDATE()
AND at2.isAllowedToWork = FALSE
AND b.workerFk = vUserFk
LIMIT 1;
IF(LENGTH(vCalendarStateType)) THEN
SELECT vCalendarStateType AS problem;
-- ENVIAMOS CORREO AL BOSSFK
SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody;
CALL mail_insert(vTo,vTo,'error al fichar',vBody);
LEAVE proc;
END IF;
-- VERIFICAR CONTRATO EN VIGOR
IF (SELECT COUNT(*)
FROM business b
WHERE b.workerFk = vUserFk
AND b.started <= vDated
AND IFNULL(b.ended, vDated) >= vDated
) = 0 THEN
SELECT "No hay un contrato en vigor" AS problem;
-- ENVIAMOS CORREO AL BOSSFK
SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody;
CALL mail_insert(vTo,vTo,'error al fichar',vBody);
LEAVE proc;
END IF;
-- VERIFICAR DESCANSO SEMANAL
SET @vHasBreakWeek:= FALSE;
SET @vLastTimed:= UNIX_TIMESTAMP((util.VN_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>= (util.VN_NOW() - INTERVAL vWeekScope SECOND)
AND userFk= vUserFk
AND direction IN ('in','out')
ORDER BY timed ASC;
IF UNIX_TIMESTAMP(util.VN_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 ha podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody;
CALL 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(util.VN_NOW()), 0) INTO vTimedWorked
FROM 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 ha podido fichar por el siguiente problema: ',"Jornadas") INTO vBody;
CALL 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 workerTimeControlUserInfo wtcu
WHERE wtcu.userFk = vUserFk;
IF (SELECT COUNT(td.tabletFk)
FROM 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 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_checkBreak` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_checkBreak`(vStarted DATE)
BEGIN
/**
* Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas
* El sistema verificará el descanso corto en la siguiente semana
* o el largo en las 2 siguientes semanas a partir de la fecha dada
* @param vStarted día inicio de la semana en el que se quiere verificar
* @return tmp.workerWithoutWeekBreak (workerFk)
*/
DECLARE vShortEnded DATETIME;
DECLARE vLongEnded DATETIME;
DECLARE vShortWeekBreak INT;
DECLARE vLongWeekBreak INT;
SELECT util.dayEnd(DATE_ADD(vStarted, INTERVAL shortWeekDays DAY)),
util.dayEnd(DATE_ADD(vStarted, INTERVAL longWeekDays DAY)),
shortWeekBreak,
longWeekBreak
INTO vShortEnded, vLongEnded, vShortWeekBreak, vLongWeekBreak
FROM workerTimeControlConfig;
SET @previousTimed:= UNIX_TIMESTAMP(vStarted);
SET @lastUserFk := NULL;
-- Descanso corto en la semana
DROP TEMPORARY TABLE IF EXISTS tmp.worker;
CREATE TEMPORARY TABLE tmp.worker
(PRIMARY KEY(workerFk))
ENGINE = MEMORY
SELECT DISTINCT userFk workerFk
FROM workerTimeControl
WHERE timed BETWEEN vStarted AND vShortEnded
AND direction IN ('in', 'out');
DROP TEMPORARY TABLE IF EXISTS tmp.worker2;
CREATE TEMPORARY TABLE tmp.worker2
(PRIMARY KEY(workerFk))
ENGINE = MEMORY
SELECT workerFk
FROM tmp.worker;
DROP TEMPORARY TABLE IF EXISTS tmp.workerWithoutShortWeekBreak;
CREATE TEMPORARY TABLE tmp.workerWithoutShortWeekBreak
SELECT sub2.userFk workerFk
FROM(SELECT sub.userFk,
IF(sub.userFk <> @lastUserFk,
@previousTimed:= sub.timed,
FALSE),
IF(sub.timed - @previousTimed >= vShortWeekBreak,
TRUE,
FALSE) hasShortWeekBreak,
@previousTimed:= sub.timed,
@lastUserFk:= sub.userFk
FROM (
SELECT userFk, UNIX_TIMESTAMP(timed) timed
FROM workerTimeControl
WHERE timed BETWEEN vStarted AND vShortEnded
AND direction IN ('in', 'out')
UNION
SELECT w.workerFk,
UNIX_TIMESTAMP(IFNULL(
MIN(wtc.timed),
DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND)))
FROM tmp.worker w
LEFT JOIN workerTimeControl wtc
ON wtc.userFk = w.workerFk
AND wtc.timed BETWEEN vShortEnded
AND DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND)
GROUP BY w.workerFk
UNION
SELECT w.workerFk,
UNIX_TIMESTAMP(IFNULL(
MAX(wtc.timed),
DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND)))
FROM tmp.worker2 w
LEFT JOIN workerTimeControl wtc
ON wtc.userFk = w.workerFk
AND wtc.timed BETWEEN
DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND)
AND vStarted
GROUP BY w.workerFk
ORDER BY userFk, timed
LIMIT 10000000000000000000
)sub
)sub2
GROUP BY sub2.userFk
HAVING NOT SUM(hasShortWeekBreak);
-- Descanso largo en las 2 siguientes semanas
DROP TEMPORARY TABLE tmp.worker;
CREATE TEMPORARY TABLE tmp.worker
(PRIMARY KEY(workerFk))
ENGINE = MEMORY
SELECT workerFk
FROM tmp.workerWithoutShortWeekBreak;
DROP TEMPORARY TABLE tmp.worker2;
CREATE TEMPORARY TABLE tmp.worker2
(PRIMARY KEY(workerFk))
ENGINE = MEMORY
SELECT workerFk
FROM tmp.workerWithoutShortWeekBreak;
DROP TEMPORARY TABLE IF EXISTS tmp.workerWithoutWeekBreak;
CREATE TEMPORARY TABLE tmp.workerWithoutWeekBreak
(PRIMARY KEY(workerFk))
ENGINE = MEMORY
SELECT sub2.userFk workerFk
FROM(SELECT userFk,
IF(userFk <> @lastUserFk,
@previousTimed:= timed,
TRUE),
IF(timed - @previousTimed >= vLongWeekBreak,
TRUE,
FALSE) hasLongWeekBreak,
@previousTimed:= timed,
@lastUserFk:= userFk
FROM (SELECT userFk, UNIX_TIMESTAMP(timed) timed
FROM workerTimeControl wtc
JOIN tmp.workerWithoutShortWeekBreak wws ON wws.workerFk = wtc.userFk
WHERE timed BETWEEN vStarted AND vLongEnded
AND direction IN ('in', 'out')
UNION
SELECT w.workerFk,
UNIX_TIMESTAMP(IFNULL(MIN(wtc.timed),
DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND)))
FROM tmp.worker w
LEFT JOIN workerTimeControl wtc
ON wtc.userFk = w.workerFk
AND timed BETWEEN vLongEnded
AND DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND)
GROUP BY w.workerFk
UNION
SELECT w.workerFk,
UNIX_TIMESTAMP(IFNULL(MAX(wtc.timed),
DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND)))
FROM tmp.worker2 w
LEFT JOIN workerTimeControl wtc
ON wtc.userFk = w.workerFk
AND timed BETWEEN DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND)
AND vStarted
GROUP BY w.workerFk
ORDER BY userFk, timed
LIMIT 10000000000000000000
)sub
)sub2
GROUP BY userFk
HAVING NOT SUM(hasLongWeekBreak);
DROP TEMPORARY TABLE tmp.workerWithoutShortWeekBreak, tmp.worker, tmp.worker2;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_clockIn` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_clockIn`(
vWorkerFk INT,
vTimed DATETIME,
vDirection VARCHAR(10),
vDevice VARCHAR(255)
)
BEGIN
/**
* Verifica si el empleado puede fichar
* @param vWorkerFk Identificador del trabajador
* @param vTimed Balor de la fichada, IF vTimed IS NULL vTimed = NOW
* @param vDirection Solo se pueden pasa los valores del campo
* workerTimeControl.direction ENUM('in', 'out', 'middle')
* @param vDevice Dispositivo en el que se ha fichado
* @return Si todo es correcto, retorna el número de id la tabla workerTimeControl.
* Si hay algún problema, devuelve el mesaje que se debe mostrar al usuario
* Solo retorna el primer problema, en caso de no ocurrir ningún error se añadirá
* fichada a la tabla vn.workerTimeControl
*/
DECLARE vLastIn DATETIME;
DECLARE vLastOut DATETIME;
DECLARE vNextIn DATETIME;
DECLARE vNextOut DATETIME;
DECLARE vNextDirection ENUM('in', 'out');
DECLARE vLastDirection ENUM('in', 'out');
DECLARE vDayMaxTime INTEGER;
DECLARE vDayBreak INT;
DECLARE vShortWeekBreak INT;
DECLARE vLongWeekBreak INT;
DECLARE vWeekScope INT;
DECLARE vMailTo VARCHAR(50) DEFAULT NULL;
DECLARE vUserName VARCHAR(50) DEFAULT NULL;
DECLARE vIsError BOOLEAN DEFAULT FALSE;
DECLARE vErrorMessage VARCHAR(255) DEFAULT NULL;
DECLARE vErrorCode VARCHAR(50);
DECLARE vDated DATE;
DECLARE vIsAllowedToWork VARCHAR(50);
DECLARE vIsManual BOOLEAN DEFAULT TRUE;
DECLARE vMaxWorkShortCycle INT;
DECLARE vMaxWorkLongCycle INT;
DECLARE EXIT HANDLER FOR SQLSTATE '45000'
BEGIN
SELECT CONCAT(u.name, '@verdnatura.es'),
CONCAT(w.firstName, ' ', w.lastName)
INTO vMailTo, vUserName
FROM account.user u
JOIN worker w ON w.bossFk = u.id
WHERE w.id = vWorkerFk;
SELECT `description` INTO vErrorMessage
FROM workerTimeControlError
WHERE `code` = vErrorCode;
IF vErrorMessage IS NULL THEN
SET vErrorMessage = 'Error sin definir';
END IF;
SELECT vErrorMessage `error`;
SELECT CONCAT(vUserName,
' no ha podido fichar por el siguiente problema: ',
vErrorMessage)
INTO vErrorMessage;
CALL mail_insert( vMailTo, vMailTo, 'Error al fichar', vErrorMessage);
END;
IF (vTimed IS NULL) THEN
SET vTimed = util.VN_NOW();
SET vIsManual = FALSE;
END IF;
SET vDated = DATE(vTimed);
SELECT IF(pc.code = 'driverCE',
wc.dayBreakDriver,
wc.dayBreak),
wc.shortWeekBreak,
wc.longWeekBreak,
wc.weekScope,
wc.dayMaxTime,
wc.maxWorkShortCycle,
wc.maxWorkLongCycle
INTO vDayBreak,
vShortWeekBreak,
vLongWeekBreak,
vWeekScope,
vDayMaxTime,
vMaxWorkShortCycle,
vMaxWorkLongCycle
FROM business b
JOIN professionalCategory pc
ON pc.id = b.workerBusinessProfessionalCategoryFk
JOIN workerTimeControlConfig wc
WHERE b.workerFk = vWorkerFk
AND vDated BETWEEN b.started AND IFNULL(b.ended, vDated);
-- CONTRATO EN VIGOR
IF vDayBreak IS NULL THEN
SET vErrorCode = 'INACTIVE_BUSINESS';
CALL util.throw(vErrorCode);
END IF;
-- FICHADAS A FUTURO
IF vTimed > util.VN_NOW() + INTERVAL 1 MINUTE THEN
SET vErrorCode = 'IS_NOT_ALLOWED_FUTURE';
CALL util.throw(vErrorCode);
END IF;
-- VERIFICAR SI ESTÁ PERMITIDO TRABAJAR
CALL timeBusiness_calculateByWorker(vWorkerFk, vDated, vDated);
SELECT isAllowedToWork INTO vIsAllowedToWork
FROM tmp.timeBusinessCalculate;
DROP TEMPORARY TABLE tmp.timeBusinessCalculate;
IF NOT vIsAllowedToWork THEN
SET vErrorCode = 'IS_NOT_ALLOWED_WORK';
CALL util.throw(vErrorCode);
END IF;
-- DIRECCION CORRECTA
CALL workerTimeControl_direction(vWorkerFk, vTimed);
IF (SELECT
IF((IF(option1 IN ('inMiddle', 'outMiddle'),
'middle',
option1) <> vDirection
AND IF(option2 IN ('inMiddle', 'outMiddle'),
'middle',
IFNULL(option2, '')) <> vDirection)
OR (option1 IS NULL AND option2 IS NULL),
TRUE ,
FALSE)
FROM tmp.workerTimeControlDirection
) THEN
SET vIsError = TRUE;
END IF;
IF vIsError THEN
SET vErrorCode = 'WRONG_DIRECTION';
IF(SELECT option1 IS NULL AND option2 IS NULL
FROM tmp.workerTimeControlDirection) THEN
SET vErrorCode = 'DAY_MAX_TIME';
END IF;
CALL util.throw(vErrorCode);
END IF;
DROP TEMPORARY TABLE tmp.workerTimeControlDirection;
-- FICHADAS IMPARES
SELECT timed INTO vLastIn
FROM workerTimeControl
WHERE userFk = vWorkerFk
AND direction = 'in'
AND timed < vTimed
ORDER BY timed DESC
LIMIT 1;
IF (SELECT IF(vDirection = 'in',
MOD(COUNT(*), 2) ,
IF (vDirection = 'out', NOT MOD(COUNT(*), 2), FALSE))
FROM workerTimeControl
WHERE userFk = vWorkerFk
AND timed BETWEEN vLastIn AND vTimed
) THEN
SET vErrorCode = 'ODD_WORKERTIMECONTROL';
CALL util.throw(vErrorCode);
END IF;
-- DESCANSO DIARIO
SELECT timed INTO vLastOut
FROM workerTimeControl
WHERE userFk = vWorkerFk
AND direction = 'out'
AND timed < vTimed
ORDER BY timed DESC
LIMIT 1;
SELECT timed INTO vNextIn
FROM workerTimeControl
WHERE userFk = vWorkerFk
AND direction = 'in'
AND timed > vTimed
ORDER BY timed ASC
LIMIT 1;
CASE vDirection
WHEN 'in' THEN
IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastOut) <= vDayBreak THEN
SET vIsError = TRUE;
END IF;
WHEN 'out' THEN
IF UNIX_TIMESTAMP(vNextIn) - UNIX_TIMESTAMP(vTimed) <= vDayBreak THEN
SET vIsError = TRUE;
END IF;
ELSE BEGIN END;
END CASE;
IF vIsError THEN
SET vErrorCode = 'BREAK_DAY';
CALL util.throw(vErrorCode);
END IF;
IF (vDirection IN('in', 'out')) THEN
-- VERIFICA MAXIMO TIEMPO DESDE ENTRADA HASTA LA SALIDA
SELECT timed INTO vNextOut
FROM workerTimeControl
WHERE userFk = vWorkerFk
AND direction = 'out'
AND timed > vTimed
ORDER BY timed ASC
LIMIT 1;
SELECT direction INTO vNextDirection
FROM workerTimeControl
WHERE userFk = vWorkerFk
AND direction IN('in','out')
AND timed > vTimed
ORDER BY timed ASC
LIMIT 1;
SELECT direction INTO vLastDirection
FROM workerTimeControl
WHERE userFk = vWorkerFk
AND direction IN('in', 'out')
AND timed < vTimed
ORDER BY timed ASC
LIMIT 1;
IF (vDirection ='in'
AND vNextDirection = 'out'
AND UNIX_TIMESTAMP(vNextOut) - UNIX_TIMESTAMP(vTimed) > vDayMaxTime) OR
(vDirection ='out'
AND vLastDirection = 'in'
AND UNIX_TIMESTAMP(vTimed) -UNIX_TIMESTAMP(vLastIn) > vDayMaxTime) THEN
SET vErrorCode = 'DAY_MAX_TIME';
CALL util.throw(vErrorCode);
END IF;
-- VERIFICA DESCANSO SEMANAL
WITH wtc AS(
(SELECT timed
FROM vn.workerTimeControl
WHERE userFk = vWorkerFk
AND direction IN ('in', 'out')
AND timed BETWEEN vTimed - INTERVAL (vWeekScope * 2) SECOND
AND vTimed + INTERVAL (vWeekScope * 2) SECOND )
UNION
(SELECT vTimed)
), wtcGap AS(
SELECT timed,
TIMESTAMPDIFF(SECOND, LAG(timed) OVER (ORDER BY timed), timed) gap
FROM wtc
ORDER BY timed
), wtcBreak AS(
SELECT timed,
IF(IFNULL(gap, 0) > vShortWeekBreak, TRUE, FALSE) hasShortBreak,
IF(IFNULL(gap, 0) > vLongWeekBreak, TRUE, FALSE) hasLongBreak
FROM wtcGap
ORDER BY timed
), wtcBreakCounter AS(
SELECT timed,
SUM(hasShortBreak) OVER (ORDER BY timed) breakCounter ,
LEAD(hasLongBreak) OVER (ORDER BY timed) nextHasLongBreak
FROM wtcBreak
)SELECT TIMESTAMPDIFF(SECOND, MIN(timed), MAX(timed)) > vMaxWorkLongCycle OR
(TIMESTAMPDIFF(SECOND, MIN(timed), MAX(timed))> vMaxWorkShortCycle
AND NOT SUM(IFNULL(nextHasLongBreak, 1)))
hasError INTO vIsError
FROM wtcBreakCounter
GROUP BY breakCounter
HAVING hasError
LIMIT 1;
IF vIsError THEN
SET vErrorCode = 'BREAK_WEEK';
CALL util.throw(vErrorCode);
END IF;
END IF;
-- Se permite fichar
INSERT INTO workerTimeControl(userFk, timed, direction, device, `manual`)
VALUES(vWorkerFk, vTimed, vDirection, vDevice, vIsManual);
SELECT LAST_INSERT_ID() id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_direction` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_direction`(vWorkerFk VARCHAR(10), vTimed DATETIME)
BEGIN
/**
* Devuelve que direcciones de fichadas son lógicas a partir de la anterior fichada
* @param vWorkerFk Identificador del trabajador
* @return (option1, option2)
* Los valores posibles de retorno son ('in', 'inMiddle', 'outMiddle', 'out')
*/
DECLARE vLastIn DATETIME ;
DECLARE vIsMiddleOdd BOOLEAN ;
IF (vTimed IS NULL) THEN
SET vTimed = util.VN_NOW();
END IF;
SELECT timed INTO vLastIn
FROM workerTimeControl
WHERE userFk = vWorkerFk
AND direction = 'in'
AND timed < vTimed
ORDER BY timed DESC
LIMIT 1;
SELECT (COUNT(*)mod 2 = 1) INTO vIsMiddleOdd
FROM workerTimeControl
WHERE userFk = vWorkerFk
AND direction = 'middle'
AND timed BETWEEN vLastIn AND vTimed;
DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlDirection;
CREATE TEMPORARY TABLE tmp.workerTimeControlDirection
SELECT IF(isCorrect, option1, NULL) option1,
IF(isCorrect, option2, NULL) option2
FROM( SELECT IF(w.direction <> 'out' AND (UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(w.timed) > wc.dayBreak), FALSE, TRUE) isCorrect,
CASE WHEN w.direction ='in' THEN 'inMiddle'
WHEN w.direction = 'out' THEN 'in'
WHEN w.direction = 'middle' AND vIsMiddleOdd THEN 'outMiddle'
WHEN w.direction IS NULL THEN 'in'
ELSE 'inMiddle'
END option1,
CASE WHEN w.direction ='in' THEN 'out'
WHEN w.direction = 'out' THEN NULL
WHEN w.direction = 'middle' AND vIsMiddleOdd THEN NULL
WHEN w.direction IS NULL THEN NULL
ELSE 'out'
END option2
FROM workerTimeControl w
JOIN workerTimeControlConfig wc ON TRUE
WHERE w.timed <= vTimed
AND w.userFk = vWorkerFk
ORDER BY w.timed DESC
LIMIT 1)sub;
IF (SELECT IF(COUNT(*)=0, TRUE, FALSE) FROM tmp.workerTimeControlDirection ) THEN
INSERT INTO tmp.workerTimeControlDirection (option1, option2)
VALUES('in', 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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_getClockIn` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_getClockIn`(
vUserFk INT,
vDated DATE)
BEGIN
/**
* Muestra una tabla con los 7 días inmediatamente anteriores a la fecha proporcionada
* y las fichadas de cada día, en columnas por día
* @param vUserFk Identificador del trabajador
* @param vDated Fecha proporcionada
*/
CALL timeControl_calculateByWorker(
vUserFk,
DATE_SUB(vDated, INTERVAL 6 DAY), util.dayEnd(vDated));
SET @position := 0;
SET @lastDated := NULL;
SELECT *
FROM( SELECT MAX(6daysAgo) 6daysAgo,
MAX(6daysAgoDirection) 6daysAgoDirection,
MAX(5daysAgo) 5daysAgo,
MAX(5daysAgoDirection) 5daysAgoDirection,
MAX(4daysAgo) 4daysAgo,
MAX(4daysAgoDirection) 4daysAgoDirection,
MAX(3daysAgo) 3daysAgo,
MAX(3daysAgoDirection) 3daysAgoDirection,
MAX(2daysAgo) 2daysAgo,
MAX(2daysAgoDirection) 2daysAgoDirection,
MAX(1daysAgo) 1daysAgo,
MAX(1daysAgoDirection) 1daysAgoDirection,
MAX(0daysAgo) 0daysAgo,
MAX(0daysAgoDirection) 0daysAgoDirection
FROM(SELECT IF(daysAgo = 6, timed, '') 6daysAgo,
IF(daysAgo = 5, timed, '') 5daysAgo,
IF(daysAgo = 4, timed, '') 4daysAgo,
IF(daysAgo = 3, timed, '') 3daysAgo,
IF(daysAgo = 2, timed, '') 2daysAgo,
IF(daysAgo = 1, timed, '') 1daysAgo,
IF(daysAgo = 0, timed, '') 0daysAgo,
IF(daysAgo = 6, direction, '') 6daysAgoDirection,
IF(daysAgo = 5, direction, '') 5daysAgoDirection,
IF(daysAgo = 4, direction, '') 4daysAgoDirection,
IF(daysAgo = 3, direction, '') 3daysAgoDirection,
IF(daysAgo = 2, direction, '') 2daysAgoDirection,
IF(daysAgo = 1, direction, '') 1daysAgoDirection,
IF(daysAgo = 0, direction, '') 0daysAgoDirection,
direction,
position
FROM(SELECT DATEDIFF(vDated, timed) daysAgo,
TIME_FORMAT(timed,'%H:%i') timed,
IF(DATE(timed) <> @lastDated, @position := 0, NULL),
@position := @position+1 position,
@lastDated := DATE(timed),
direction
FROM workerTimeControl wtc
WHERE wtc.userFk = vUserFk
AND wtc.timed >= TIMESTAMPADD(DAY, -6,vDated)
ORDER BY wtc.timed
LIMIT 10000000000000000000
)sub
)sub2
GROUP BY position) sub3
JOIN (SELECT MAX(IF(daysAgo = 6, timeWorkSeconds, 0)) 6daysAgoTotal,
MAX(IF(daysAgo = 5, timeWorkSeconds, 0)) 5daysAgoTotal,
MAX(IF(daysAgo = 4, timeWorkSeconds, 0)) 4daysAgoTotal,
MAX(IF(daysAgo = 3, timeWorkSeconds, 0)) 3daysAgoTotal,
MAX(IF(daysAgo = 2, timeWorkSeconds, 0)) 2daysAgoTotal,
MAX(IF(daysAgo = 1, timeWorkSeconds, 0)) 1daysAgoTotal,
MAX(IF(daysAgo = 0, timeWorkSeconds, 0)) 0daysAgoTotal
FROM (SELECT DATEDIFF(vDated, dated) daysAgo,
timeWorkSeconds
FROM tmp.timeControlCalculate) sub4)sub5 ON TRUE;
DROP TEMPORARY TABLE tmp.timeControlCalculate;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_login` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_login`(vWorkerFk VARCHAR(10))
BEGIN
/**
* Consulta la información del usuario y los botones que tiene que activar en la tablet tras hacer login
* Solo retornará 1 ó 2 opciones de las 4 posibles
* @param vWorkerFk Identificador del trabajador
* @return (name, surname, userFk, departmentFk, button1, button2)
* Los valores posibles para button son ('in', 'inMiddle', 'outMiddle', 'out')
*/
CALL vn.workerTimeControl_direction(vWorkerFk, util.VN_NOW());
SELECT wi.name,
wi.surname,
wi.userFk,
wi.departmentFk,
w.option1 button1,
w.option2 button2
FROM workerTimeControlUserInfo wi
JOIN tmp.workerTimeControlDirection w
WHERE wi.userFk = vWorkerFk
LIMIT 1;
DROP TEMPORARY TABLE tmp.workerTimeControlDirection;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_sendMailByDepartment` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_sendMailByDepartment`(IN vDatedFrom DATETIME, IN vDatedTo DATETIME, IN vWorkerFk INT)
BEGIN
/**
* Inserta el registro de horario semanalmente de PRODUCCION, CAMARA, REPARTO, TALLER NATURAL y TALLER ARTIFICIAL en vn.mail.
*
* @param vDatedFrom
* @param vDatedTo
* @param vWorkerFk -> En el caso de querer generarlo para todos los empleados deberá de pasarse = NULL
*/
SET session group_concat_max_len = 15000;
DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate;
DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate;
DROP TEMPORARY TABLE IF EXISTS tmp.reportHours;
IF vWorkerFk IS NULL THEN
CALL timeControl_calculateAll(vDatedFrom,vDatedTo);
CALL timeBusiness_calculateAll(vDatedFrom,vDatedTo);
ELSE
CALL timeControl_calculateByUser(vWorkerFk,vDatedFrom,vDatedTo);
CALL timeBusiness_calculateByUser(vWorkerFk,vDatedFrom,vDatedTo);
END IF;
CREATE TEMPORARY TABLE tmp.reportHours
SELECT t.dated,
IF (tm.hoursWeek IS NULL,'', GROUP_CONCAT(DATE_FORMAT(wtc.timed,'%H:%i') ORDER BY wtc.timed ASC SEPARATOR ' ') ) timeWorkDay,
SEC_TO_TIME(IFNULL(tm.timeWorkSeconds, 0)) tm,
SEC_TO_TIME(IFNULL(tc.timeWorkSeconds, 0)) tc,
SEC_TO_TIME(IFNULL(tc.timeWorkSeconds, 0) - IFNULL(tm.timeWorkSeconds, 0)) balance,
w.lastName,
w.firstname,
c.fi,
w.id userFk,
MONTHNAME(t.dated) mes,
YEAR(t.dated) año,
w.id,
tm.hoursWeek,
tm.type,
b.started,
b.ended,
d.name,
tm.businessFk
FROM time t
LEFT JOIN tmp.timeBusinessCalculate tm ON tm.dated = t.dated
LEFT JOIN tmp.timeControlCalculate tc ON tc.dated = tm.dated AND tc.userFk = tm.userFk
LEFT JOIN vn.workerTimeControl wtc ON wtc.userFk = tm.userFk AND DATE(wtc.timed) = t.dated
LEFT JOIN business b ON b.workerFk = tm.userFk AND b.id = tm.businessFk
LEFT JOIN workCenter wc ON wc.id = b.workcenterFk
LEFT JOIN department d ON d.id = b.departmentFk
LEFT JOIN worker w ON w.id = tm.userFk
LEFT JOIN client c ON c.id = w.id
WHERE wc.name NOT IN ('VNH')
AND d.hasToSendMail
AND w.businessFk
GROUP BY tm.userFk,t.dated
ORDER BY tm.userFk,t.dated;
INSERT INTO vn.mail (receiver, replyTo, subject, body)
SELECT eu.email, 'laboral@verdnatura.es', CONCAT('Registro de horas semana ', WEEK(vDatedFrom), ' año ', YEAR(vDatedFrom)) ,
CONCAT('
REGISTRO DE LA JORNADA DE LOS TRABAJADORES
Según la información recogida en el sistema, adjuntamos la tabla con los registros. Cualquier incidencia rogamos la comunique a laboral@verdnatura.es.
De no recibir incidencia por su parte, se entenderá que el registro es correcto.
|
Empresa: Verdnatura Levante SL |
Trabajador: ',rh.firstname,' ',rh.lastName, ' |
NIF: ',rh.fi, ' |
AÑO: ',rh.año, ' |
MES: ',UPPER(rh.mes), ' |
Calendario Laboral: ',rh.hoursWeek,' horas semanales |
Fecha: |
Día: |
Fichadas: |
Horas a trabajar: |
Horas trabajadas: |
Balance: |
',
GROUP_CONCAT(DISTINCT ' ', DATE_FORMAT( rh.dated, '%d-%m-%y'),
' | ', CONCAT(UCASE(LEFT(DAYNAME(rh.dated), 1)), SUBSTRING(DAYNAME(rh.dated), 2)),
' | ', IFNULL(rh.timeWorkDay,' '),' ', IFNULL(rh.type,' '),
' | ', rh.tm,
' | ', SUBSTRING_INDEX(rh.tc, '.', 1),
' | ', SUBSTRING_INDEX(rh.balance, '.', 1), ' |
' ORDER BY rh.dated SEPARATOR ''),
' |
|
|
Total horas trabajadas: |
', SUBSTRING_INDEX(SEC_TO_TIME(SUM(TIME_TO_SEC(rh.tc))), '.', 1),' |
', SUBSTRING_INDEX(SEC_TO_TIME(SUM(TIME_TO_SEC(rh.balance))), '.', 1),' |
')
FROM tmp.reportHours rh
JOIN account.emailUser eu ON rh.id = eu.userFk
GROUP BY rh.id;
DROP TEMPORARY TABLE tmp.timeControlCalculate;
DROP TEMPORARY TABLE tmp.timeBusinessCalculate;
DROP TEMPORARY TABLE tmp.reportHours;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_sendMailByDepartmentLauncher` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_sendMailByDepartmentLauncher`()
BEGIN
DECLARE vDatedFrom, vDatedTo DATETIME;
IF (DAYNAME(util.VN_CURDATE()) = 'miércoles') THEN
SELECT DATE_SUB(util.VN_CURDATE(), INTERVAL 9 DAY), CONCAT(DATE_SUB(util.VN_CURDATE(), INTERVAL 3 DAY), ' 23:59:59') INTO vDatedFrom, vDatedTo;
CALL vn.workerTimeControl_sendMailByDepartment(vDatedFrom, vDatedTo, 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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_weekCheckBreak` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_weekCheckBreak`(vStarted DATE, vEnded DATE)
BEGIN
/**
* Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas
* El sistema verificará el descanso corto en la siguiente semana
* o el largo en las 2 siguientes semanas a partir de las fechas dadas
* @param vStarted día inicio para verificar
* @param vEnded día final para verificar
* @return tmp.workerWithoutWeekBreak (workerFk)
*/
DECLARE vDone INT DEFAULT FALSE;
IF(vStarted > vEnded) then
CALL util.throw ('Date end can not be greater then start');
END IF;
DROP TEMPORARY TABLE IF EXISTS tmp.workerWithoutWeekBreakInWeek;
CREATE TEMPORARY TABLE tmp.workerWithoutWeekBreakInWeek
(workerFk INT,
PRIMARY KEY(workerFk))
ENGINE = MEMORY;
WHILE vStarted <= vEnded DO
CALL workerTimeControl_checkBreak(vStarted);
INSERT IGNORE INTO tmp.workerWithoutWeekBreakInWeek
SELECT workerFk
FROM tmp.workerWithoutWeekBreak;
DROP TEMPORARY TABLE IF EXISTS tmp.workerWithoutWeekBreak;
SET vStarted = DATE_ADD(vStarted, 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 workerTimeControl WHERE timed >= vDated AND userFk = vUserFk;
SET @day := 0;
SET @lastTimed := util.VN_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, util.VN_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', util.VN_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 at2.name INTO vCantWork
FROM calendar c
JOIN business b ON b.id = c.businessFk
JOIN absenceType at2 ON at2.id = c.dayOffTypeFk
WHERE c.dated = util.VN_CURDATE()
AND at2.isAllowedToWork = FALSE
AND b.workerFk = vUserFk
LIMIT 1;
-- Contrato en vigor
SELECT IF(COUNT(*),vCantWork,'Sin contrato') INTO vCantWork
FROM business b
WHERE b.workerFk = vUserFk
AND b.started <= vDated
AND IFNULL(b.ended, 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 workerTimeControlUserInfo wtcu
WHERE wtcu.userFk = vUserFk;
-- 2 Comprobar si la tablet pertenece al departamento
SELECT COUNT(td.tabletFk) INTO isEnabled
FROM 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `worker_getFromHasMistake` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_getFromHasMistake`(vDepartmentFk INT)
BEGIN
/**
* Obtiene los trabajadores de los departamentos que se les puede poner error
* @param vDepartmentFk id del departamento
*
*/
SELECT w.id,w.firstName, w.lastName,d.name
FROM worker w
JOIN workerDepartment wd ON wd.workerFk = w.id
JOIN department d ON d.id = wd.departmentFk
WHERE d.id = vDepartmentFk
ORDER BY 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_getHierarchy`(vUserFk INT)
BEGIN
/**
* Retorna una tabla temporal con los trabajadores que tiene
* el usuario por debajo en la jerarquía de la empresa.
*
* @param vUserFk Id de usuario.
* @return tmp.workerHierarchyList
*/
CREATE OR REPLACE TEMPORARY TABLE tmp.workerHierarchyList
(PRIMARY KEY (workerFk))
ENGINE = MEMORY
WITH RECURSIVE workerHierarchy AS (
SELECT id workerFk, bossFk, 0 depth
FROM vn.worker
WHERE id = vUserFk
UNION ALL
SELECT w.id, w.bossFk, wh.depth + 1
FROM vn.worker w
JOIN workerHierarchy wh ON w.bossFk = wh.workerFk
)
SELECT *
FROM workerHierarchy
ORDER BY depth, 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `worker_getSector` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_getSector`()
BEGIN
/**
* Obtiene el sector del usuario conectado
*/
SELECT s.id,s.description,s.warehouseFk
FROM sector s
JOIN operator o ON o.sectorFk = s.id
WHERE o.workerFk = account.myUser_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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `worker_updateBalance` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_updateBalance`(vSelfFk INT(11), vCredit DECIMAL(10,2), vDebit DECIMAL(10,2))
BEGIN
/**
* Actualiza la columna balance de worker.
*
* @param selfFk, credit, debit
*/
UPDATE worker
SET balance = IFNULL(balance, 0) + IFNULL(vCredit, 0) - IFNULL(vDebit, 0)
WHERE id = vSelfFk;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `worker_updateBusiness` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_updateBusiness`(vSelf INT)
BEGIN
/**
* Activates an account and configures its email settings.
*
* @param vSelf account id.
*/
DECLARE vOldBusinessFk INT;
DECLARE vNewBusinessFk INT;
SELECT businessFk INTO vOldBusinessFk FROM worker WHERE id = vSelf;
SELECT id INTO vNewBusinessFk
FROM business
WHERE workerFk = vSelf
AND util.VN_CURDATE() BETWEEN started AND IFNULL(ended, util.VN_CURDATE())
LIMIT 1;
UPDATE worker
SET businessFk = vNewBusinessFk
WHERE id = vSelf;
IF vOldBusinessFk IS NULL THEN
CALL account.account_enable(vSelf);
UPDATE client c
JOIN payMethod pm ON pm.code = 'bankDraft'
SET c.payMethodFk = pm.id
WHERE c.id = vSelf
AND c.iban;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `worker_updateChangedBusiness` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_updateChangedBusiness`()
BEGIN
/**
* Actualiza el contrato actual de todos los trabajadores cuyo contracto ha
* empezado/vencido.
*/
DECLARE vBusinessUpdated DATE;
DECLARE vCurdate DATE DEFAULT util.VN_CURDATE();
DECLARE vWorkerFk INT;
DECLARE vDone BOOL;
DECLARE vCursor CURSOR FOR
SELECT DISTINCT b.workerFk
FROM business b
WHERE b.started > vBusinessUpdated AND b.started <= vCurdate
OR b.ended >= vBusinessUpdated AND b.ended < vCurdate;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SELECT businessUpdated INTO vBusinessUpdated
FROM workerConfig;
OPEN vCursor;
l: LOOP
SET vDone = FALSE;
FETCH vCursor INTO vWorkerFk;
IF vDone THEN
LEAVE l;
END IF;
CALL worker_updateBusiness(vWorkerFk);
END LOOP;
UPDATE workerConfig SET businessUpdated = vCurdate;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workingHours` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workingHoursTimeIn` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workingHoursTimeIn`(vUserId INT(11))
BEGIN
INSERT INTO vn.workingHours (timeIn, userId)
VALUES (util.VN_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 */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workingHoursTimeOut` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workingHoursTimeOut`(vUserId INT(11))
BEGIN
UPDATE vn.workingHours
SET timeOut = util.VN_NOW()
WHERE userId = vUserId
AND DATE(timeIn) = util.VN_CURDATE();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `XDiario_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `XDiario_check`()
BEGIN
/**
* Realiza la revisión diaria de los asientos contables,
* identificando y notificando los asientos descuadrados
* y ajustando los saldos en caso necesario.
*/
INSERT INTO mail (receiver, subject, body)
SELECT 'cau@verdnatura.es',
'Asientos descuadrados',
GROUP_CONCAT(CONCAT(' Asiento: ', ASIEN, ' - Importe:', recon) SEPARATOR ' | \n')
FROM (
SELECT ASIEN,
SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) recon
FROM XDiario
WHERE NOT enlazado
GROUP BY ASIEN
HAVING ABS(SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0))) > 0.01
) sub
HAVING COUNT(*);
UPDATE XDiario xd
JOIN (
SELECT xd.id, SUBCTA, recon
FROM XDiario xd
JOIN (
SELECT ASIEN,
SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) recon
FROM XDiario
WHERE NOT enlazado
GROUP BY ASIEN
HAVING recon
) sub ON sub.ASIEN = xd.ASIEN
WHERE xd.SUBCTA > '5999999999'
GROUP BY xd.ASIEN
) sub ON sub.id = xd.id
SET xd.Eurohaber = IF(IFNULL(xd.Eurohaber, 0) = 0, xd.Eurohaber, xd.Eurohaber + sub.recon),
xd.Eurodebe = IF(IFNULL(xd.Eurodebe, 0) = 0, xd.Eurodebe, xd.Eurodebe - sub.recon);
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `XDiario_checkDate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `XDiario_checkDate`(vDate DATE)
proc: BEGIN
/**
* Comprueba si la fecha pasada esta en el rango
* de fecha de contabilidad
*
* @param vDate Fecha para comparar
*/
DECLARE vIsInvalid BOOL;
IF vDate IS NULL THEN
LEAVE proc;
END IF;
SELECT COUNT(*) = 0 INTO vIsInvalid
FROM accountingConfig
WHERE vDate BETWEEN minDate AND maxDate;
IF vIsInvalid THEN
CALL util.throw ('Fecha fuera de rango');
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zoneClosure_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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `zoneClosure_recalc`()
proc: BEGIN
/**
* Recalculates the delivery time (hour) for every zone in days + scope in future
*/
DECLARE vScope INT;
DECLARE vCounter INT DEFAULT 0;
DECLARE vShipped DATE DEFAULT util.VN_CURDATE();
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
DO RELEASE_LOCK('vn.zoneClosure_recalc');
RESIGNAL;
END;
IF NOT GET_LOCK('vn.zoneClosure_recalc', 0) THEN
LEAVE proc;
END IF;
SELECT scope INTO vScope
FROM zoneConfig;
DROP TEMPORARY TABLE IF EXISTS tmp.zone;
CREATE TEMPORARY TABLE tmp.zone
(INDEX (id))
ENGINE = MEMORY
SELECT id FROM zone;
TRUNCATE TABLE zoneClosure;
WHILE vCounter <= vScope DO
CALL zone_getOptionsForShipment(vShipped, TRUE);
REPLACE zoneClosure(zoneFk, dated, `hour`)
SELECT zoneFk, vShipped, `hour`
FROM tmp.zoneOption;
SET vCounter = vCounter + 1;
SET vShipped = TIMESTAMPADD(DAY, 1, vShipped);
END WHILE;
-- DROP TEMPORARY TABLE tmp.zone;
DO RELEASE_LOCK('vn.zoneClosure_recalc');
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_excludeFromGeo` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_excludeFromGeo`(vZoneGeo INT)
BEGIN
/**
* Excluye zonas a partir un geoFk.
*
* @table tmp.zoneOption(zoneFk, hour, travelingDays, price, bonus, landed, shipped) The computed options
* @param vZoneGeo The zone geo
* @return tmp.zoneOption The computed options
*/
DELETE t
FROM tmp.zoneOption t
JOIN zoneExclusion e ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed
LEFT JOIN zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id
JOIN zoneGeo zg1 ON zg1.id = eg.geoFk
JOIN zoneGeo zg2 ON zg2.id = vZoneGeo
WHERE zg2.`path` LIKE CONCAT(zg1.`path`, zg1.id,'/%')
OR zg2.id = zg1.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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_getAddresses` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getAddresses`(
vSelf INT,
vLanded DATE
)
BEGIN
/**
* Devuelve un listado de todos los clientes activos
* con consignatarios a los que se les puede
* vender producto para esa zona y no tiene un ticket
* para ese día.
*
* @param vSelf Id de zona
* @param vDated Fecha de entrega
* @return Un select
*/
CALL zone_getPostalCode(vSelf);
WITH notHasTicket AS (
SELECT id
FROM vn.client
WHERE id NOT IN (
SELECT clientFk
FROM vn.ticket
WHERE landed BETWEEN vLanded AND util.dayEnd(vLanded)
)
)
SELECT c.id clientFk,
c.name,
c.phone,
bt.description,
c.salesPersonFk,
u.name username,
aai.invoiced,
cnb.lastShipped
FROM vn.client c
JOIN notHasTicket ON notHasTicket.id = c.id
LEFT JOIN account.`user` u ON u.id = c.salesPersonFk
JOIN vn.`address` a ON a.clientFk = c.id
JOIN vn.postCode pc ON pc.code = a.postalCode
JOIN vn.town t ON t.id = pc.townFk AND t.provinceFk = a.provinceFk
JOIN vn.zoneGeo zg ON zg.name = a.postalCode
JOIN tmp.zoneNodes zn ON zn.geoFk = pc.geoFk
LEFT JOIN bs.clientNewBorn cnb ON cnb.clientFk = c.id
LEFT JOIN vn.annualAverageInvoiced aai ON aai.clientFk = c.id
JOIN vn.clientType ct ON ct.code = c.typeFk
JOIN vn.businessType bt ON bt.code = c.businessTypeFk
WHERE a.isActive
AND c.isActive
AND ct.code = 'normal'
AND bt.code <> 'worker'
GROUP BY c.id;
DROP TEMPORARY TABLE tmp.zoneNodes;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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
* @return tmp.zoneGetAgency Listado de agencias disponibles
*/
CALL zone_getFromGeo(address_getGeo(vAddress));
CALL zone_getOptionsForLanding(vLanded, FALSE);
CALL vn.zone_excludeFromGeo(address_getGeo(vAddress));
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,
am.web AS isVisible
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getAvailable`(vAddress INT, vLanded DATE)
BEGIN
CALL zone_getFromGeo(address_getGeo(vAddress));
CALL zone_getOptionsForLanding(vLanded, FALSE);
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_getClosed` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getClosed`()
proc:BEGIN
/**
* Devuelve una tabla con las zonas cerradas para hoy
*
* @table tmp.closedZones(zoneFk, warehouseFk);
*/
DROP TEMPORARY TABLE IF EXISTS tmp.closedZones;
CREATE TEMPORARY TABLE tmp.closedZones (
`zoneFk` int(11) NOT NULL,
`warehouseFk` smallint(6) unsigned NOT NULL,
PRIMARY KEY `zoneFk` (`zoneFk`,`warehouseFk`),
KEY `warehouseFk` (`warehouseFk`))
ENGINE=MEMORY DEFAULT CHARSET=utf8;
INSERT INTO tmp.closedZones(zoneFk, warehouseFk)
SELECT zoneFk, warehouseFk
FROM (
SELECT t.zoneFk, t.warehouseFk, count(DISTINCT t.id) numTickets, pc.minTicketsToCloseZone
FROM vn.ticket t
JOIN vn.expedition e ON e.ticketFk = t.id
JOIN vn.`zone`z on z.id = t.zoneFk
JOIN vn.agencyMode am ON am.id = z.agencyModeFk
JOIN vn.agency a ON a.id = am.agencyFk
JOIN vn.productionConfig pc
WHERE a.isOwn
AND pc.isZoneClosedByExpeditionActivated
AND e.created >= util.VN_CURDATE()
GROUP BY t.zoneFk, t.warehouseFk
HAVING numTickets >= minTicketsToCloseZone) 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_getCollisions` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getCollisions`()
BEGIN
/**
* Calcula si para un mismo codigo postal y dia
* hay mas de una zona configurada y manda correo
*
*/
DECLARE vGeoFk INT DEFAULT NULL;
DECLARE vZoneFk INT;
DECLARE vIsDone INT DEFAULT FALSE;
DECLARE vTableCollisions TEXT;
DECLARE json_data JSON;
DECLARE cur1 CURSOR FOR SELECT zoneFk from tmp.zoneOption;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE;
DROP TEMPORARY TABLE IF EXISTS tmp.zone;
CREATE TEMPORARY TABLE tmp.zone
SELECT z.id
FROM zone z
JOIN agencyMode am ON am.id = z.agencyModeFk
JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
WHERE dm.code IN ('AGENCY','DELIVERY');
CALL zone_getOptionsForShipment(util.VN_CURDATE(),FALSE);
DROP TEMPORARY TABLE IF EXISTS tmp.zoneNodes;
CREATE TEMPORARY TABLE tmp.zoneNodes (
geoFk INT,
name VARCHAR(100),
parentFk INT,
sons INT,
isChecked BOOL DEFAULT 0,
zoneFk INT,
PRIMARY KEY zoneFkk (zoneFk, geoFk),
INDEX(geoFk))
ENGINE = MyISAM;
OPEN cur1;
cur1Loop: LOOP
SET vIsDone = FALSE;
FETCH cur1 INTO vZoneFk;
IF vIsDone THEN
LEAVE cur1Loop;
END IF;
CALL zone_getLeaves(vZoneFk, NULL, NULL, TRUE);
myLoop: LOOP
SET vGeoFk = NULL;
SELECT geoFk INTO vGeoFk
FROM tmp.zoneNodes zn
WHERE NOT isChecked
LIMIT 1;
IF vGeoFk IS NULL THEN
LEAVE myLoop;
END IF;
CALL zone_getLeaves(vZoneFk, vGeoFk, NULL, TRUE);
UPDATE tmp.zoneNodes
SET isChecked = TRUE
WHERE geoFk = vGeoFk;
END LOOP;
END LOOP;
CLOSE cur1;
DELETE FROM tmp.zoneNodes
WHERE sons > 0;
DROP TEMPORARY TABLE IF EXISTS geoCollision;
CREATE TEMPORARY TABLE geoCollision
SELECT z.agencyModeFk, zn.geoFk, zw.warehouseFk
FROM tmp.zoneNodes zn
JOIN zone z ON z.id = zn.zoneFk
JOIN zoneWarehouse zw ON z.id = zw.zoneFk
GROUP BY z.agencyModeFk, zn.geoFk, zw.warehouseFk
HAVING count(*) > 1;
-- Recojo los datos de la zona que ha dado conflicto
SELECT JSON_ARRAYAGG(
JSON_OBJECT(
'zoneFk', zoneFk,
'zn', JSON_OBJECT('name', zn.name),
'z', JSON_OBJECT('name', z.name,'price', z.price),
'w', JSON_OBJECT('name', w.name)
)
) FROM tmp.zoneNodes zn
JOIN zone z ON z.id = zn.zoneFk
JOIN geoCollision gc ON gc.agencyModeFk = z.agencyModeFk AND zn.geoFk = gc.geoFk
JOIN warehouse w ON w.id = gc.warehouseFk
INTO json_data;
-- Creo un registro de la notificacion 'zone-included' para reportar via email
SELECT util.notification_send(
'zone-included',
JSON_OBJECT('zoneCollisions',json_data),
account.myUser_getId()
);
DROP TEMPORARY TABLE
geoCollision,
tmp.zone,
tmp.zoneNodes;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getEvents`(
vGeoFk INT,
vAgencyModeFk INT)
BEGIN
/**
* Returns available events for the passed province/postcode and agency.
*
* @param vGeoFk The geo id
* @param vAgencyModeFk The agency mode id
*/
DECLARE vDeliveryMethodFk VARCHAR(255);
DROP TEMPORARY TABLE IF EXISTS tZone;
CREATE TEMPORARY TABLE tZone
(id INT PRIMARY KEY)
ENGINE = MEMORY;
SELECT dm.`code` INTO vDeliveryMethodFk
FROM agencyMode am
JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
WHERE am.id = vAgencyModeFk;
IF vDeliveryMethodFk = 'PICKUP' THEN
INSERT INTO tZone
SELECT id
FROM zone
WHERE agencyModeFk = vAgencyModeFk;
ELSE
CALL zone_getFromGeo(vGeoFk);
IF vAgencyModeFk IS NOT NULL THEN
INSERT INTO tZone
SELECT t.id
FROM tmp.zone t
JOIN zone z ON z.id = t.id
WHERE z.agencyModeFk = vAgencyModeFk;
ELSE
INSERT INTO tZone
SELECT t.id
FROM tmp.zone t
JOIN zone z ON z.id = t.id
JOIN agencyMode am ON am.id = z.agencyModeFk
JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
WHERE dm.`code` IN ('AGENCY', 'DELIVERY');
END IF;
DROP TEMPORARY TABLE tmp.zone;
END IF;
SELECT e.zoneFk, e.`type`, e.dated, e.`started`, e.`ended`, e.weekDays
FROM tZone t
JOIN zoneEvent e ON e.zoneFk = t.id;
SELECT e.zoneFk, e.dated
FROM tZone t
JOIN zoneExclusion e ON e.zoneFk = t.id
LEFT JOIN zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id
LEFT JOIN zoneGeo zg1 ON zg1.id = eg.geoFk
JOIN zoneGeo zg2 ON zg2.id = vGeoFk
WHERE eg.zoneExclusionFk IS NULL OR zg2.`path` LIKE CONCAT(zg1.`path`,'%');
DROP TEMPORARY TABLE tZone;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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`
LIMIT 10000000000000000000
) 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLanded`(vShipped DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT, vShowExpiredZones BOOLEAN)
BEGIN
/**
* Devuelve una tabla temporal con el dia de recepcion para vShipped.
* Excluye las que tengan cajas preparadas
*
* @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
*/
DECLARE vZoneGeo INT;
SELECT address_getGeo(vAddressFk) INTO vZoneGeo;
CALL vn.zone_getFromGeo(vZoneGeo);
CALL vn.zone_getOptionsForShipment(vShipped, vShowExpiredZones);
CALL vn.zone_excludeFromGeo(vZoneGeo);
CALL vn.zone_getClosed();
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 vn.`zone` z ON z.id = zo.zoneFk
JOIN vn.zoneWarehouse zw ON zw.zoneFk = z.id
LEFT JOIN tmp.closedZones cz
ON cz.warehouseFk = zw.warehouseFk
AND cz.zoneFk = zw.zoneFk
AND zo.shipped = util.VN_CURDATE()
WHERE z.agencyModeFk = vAgencyModeFk
AND zw.warehouseFk = vWarehouseFk
AND (ISNULL(cz.zoneFk) OR vShowExpiredZones)
ORDER BY z.price DESC, zo.zoneFk
LIMIT 1;
DROP TEMPORARY TABLE
tmp.`zone`,
tmp.zoneOption,
tmp.closedZones;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves`(
vSelf INT,
vParentFk INT,
vSearch VARCHAR(255),
vHasInsert BOOL
)
BEGIN
/**
* Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk.
* @param vSelf Id de la zona
* @param vParentFk Id del geo a calcular
* @param vSearch Cadena a buscar
* @param vHasInsert Indica si inserta en tmp.zoneNodes
* Optional @table tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk)
*/
DECLARE vIsNumber BOOL;
DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch <> '';
CREATE OR REPLACE 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
CREATE OR REPLACE TEMPORARY TABLE tChilds
(INDEX(id))
ENGINE = MEMORY
SELECT id FROM tNodes;
CREATE OR REPLACE TEMPORARY TABLE tParents
(INDEX(id))
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 NOT ROW_COUNT() 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 NOT vIsSearch THEN
INSERT IGNORE INTO tNodes
SELECT id
FROM zoneGeo
WHERE parentFk <=> vParentFk;
END IF;
CREATE OR REPLACE TEMPORARY TABLE tZones
SELECT g.id,
g.name,
g.parentFk,
g.sons,
NOT g.sons OR `type` = 'country' isChecked,
i.isIncluded selected,
g.`depth`,
vSelf
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 g.`depth`, selected DESC, g.name;
IF vHasInsert THEN
INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk)
SELECT id,
name,
parentFk,
sons,
isChecked,
vSelf
FROM tZones
WHERE selected
OR (selected IS NULL AND vParentFk IS NOT NULL);
ELSE
SELECT id,
name,
parentFk,
sons,
selected
FROM tZones
ORDER BY `depth`, selected DESC, name;
END IF;
DROP TEMPORARY TABLE tNodes, tZones;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getOptionsForLanding`(vLanded DATE, vShowExpiredZones BOOLEAN)
BEGIN
/**
* Gets computed options for the passed zones and delivery date.
*
* @table tmp.zone(id) The zones ids
* @param vLanded The delivery date
* @return tmp.zoneOption The computed options
*/
DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption;
CREATE TEMPORARY TABLE tmp.zoneOption
ENGINE = MEMORY
SELECT
zoneFk,
`hour`,
travelingDays,
price,
bonus,
vLanded landed,
TIMESTAMPADD(DAY, -travelingDays, vLanded) shipped
FROM (
SELECT t.id zoneFk,
TIME(IFNULL(e.`hour`, z.`hour`)) `hour`,
IFNULL(e.travelingDays, z.travelingDays) travelingDays,
IFNULL(e.price, z.price) price,
IFNULL(e.bonus, z.bonus) bonus
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`)
)
ORDER BY
zoneFk,
CASE
WHEN e.`type` = 'day'
THEN 1
WHEN e.`type` = 'range'
THEN 2
ELSE 3
END
LIMIT 10000000000000000000
) t
GROUP BY zoneFk;
DELETE t FROM tmp.zoneOption t
JOIN zoneExclusion e ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed
LEFT JOIN zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id
WHERE eg.zoneExclusionFk IS NULL;
IF NOT vShowExpiredZones THEN
DELETE FROM tmp.zoneOption
WHERE shipped < util.VN_CURDATE()
OR (shipped = util.VN_CURDATE() AND util.VN_CURTIME() > `hour`);
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getOptionsForShipment`(vShipped DATE, vShowExpiredZones BOOLEAN)
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
*/
DECLARE vHour TIME DEFAULT TIME(util.VN_NOW());
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 tmp.zoneOption;
CREATE TEMPORARY TABLE tmp.zoneOption
ENGINE = MEMORY
SELECT *
FROM (
SELECT t.id zoneFk,
TIME(IFNULL(e.`hour`, z.`hour`)) `hour`,
l.travelingDays,
IFNULL(e.price, z.price) price,
IFNULL(e.bonus, z.bonus) bonus,
l.landed,
vShipped shipped
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`)
)
ORDER BY
zoneFk,
CASE
WHEN e.`type` = 'day'
THEN 1
WHEN e.`type` = 'range'
THEN 2
ELSE 3
END
LIMIT 10000000000000000000
) t
GROUP BY zoneFk;
DROP TEMPORARY TABLE tLandings;
DELETE t FROM tmp.zoneOption t
JOIN zoneExclusion e ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed
LEFT JOIN zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id
WHERE eg.zoneExclusionFk IS NULL;
IF NOT vShowExpiredZones THEN
DELETE FROM tmp.zoneOption
WHERE vShipped < util.VN_CURDATE()
OR (vShipped = util.VN_CURDATE() AND util.VN_CURTIME() > `hour`);
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_getPostalCode` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getPostalCode`(vSelf INT)
BEGIN
/**
* Devuelve los códigos postales incluidos en una zona
*/
DECLARE vGeoFk INT DEFAULT NULL;
CREATE OR REPLACE TEMPORARY TABLE tmp.zoneNodes (
geoFk INT,
name VARCHAR(100),
parentFk INT,
sons INT,
isChecked BOOL DEFAULT 0,
zoneFk INT,
PRIMARY KEY zoneNodesPk (zoneFk, geoFk),
INDEX(geoFk))
ENGINE = MEMORY;
CALL zone_getLeaves(vSelf, NULL , NULL, TRUE);
UPDATE tmp.zoneNodes
SET isChecked = 0
WHERE parentFk IS NULL;
myLoop: LOOP
SET vGeoFk = NULL;
SELECT geoFk INTO vGeoFk
FROM tmp.zoneNodes
WHERE NOT isChecked
LIMIT 1;
CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE);
UPDATE tmp.zoneNodes
SET isChecked = TRUE
WHERE geoFk = vGeoFk;
IF vGeoFk IS NULL THEN
LEAVE myLoop;
END IF;
END LOOP;
DELETE FROM tmp.zoneNodes
WHERE sons > 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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_getShipped` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getShipped`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT, vShowExpiredZones BOOLEAN)
BEGIN
/**
* Devuelve la mínima fecha de envío para cada warehouse
* Excluye aquellas zonas que ya tienen cajas preparadas en ese almacén
*
* @param vLanded La fecha de recepcion
* @param vAddressFk Id del consignatario
* @param vAgencyModeFk Id de la agencia
* @return tmp.zoneGetShipped
*/
DECLARE vZoneGeo INT;
SELECT address_getGeo(vAddressFk) INTO vZoneGeo;
CALL vn.zone_getFromGeo(vZoneGeo);
CALL vn.zone_getOptionsForLanding(vLanded, vShowExpiredZones);
CALL vn.zone_excludeFromGeo(vZoneGeo);
CALL vn.zone_getClosed();
DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped;
CREATE TEMPORARY TABLE tmp.zoneGetShipped
ENGINE = MEMORY
SELECT * FROM (
SELECT zo.zoneFk,
zo.shipped,
zo.`hour`,
zw.warehouseFk,
z.agencyModeFk,
zo.price,
zo.bonus
FROM tmp.zoneOption zo
JOIN vn.zoneWarehouse zw ON zw.zoneFk = zo.zoneFk
JOIN vn.`zone` z ON z.id = zo.zoneFk
LEFT JOIN tmp.closedZones cz
ON cz.warehouseFk = zw.warehouseFk
AND cz.zoneFk = zw.zoneFk
AND zo.shipped = util.VN_CURDATE()
WHERE z.agencyModeFk = vAgencyModeFk
AND (ISNULL(cz.zoneFk) OR vShowExpiredZones)
ORDER BY shipped
LIMIT 10000000000000000000) t
GROUP BY warehouseFk;
DROP TEMPORARY TABLE
tmp.`zone`,
tmp.zoneOption,
tmp.closedZones;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!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_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_getState` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getState`(vDated DATE)
BEGIN
/**
* Devuelve las zonas y el estado para la fecha solicitada
*
* @param vDated Fecha en cuestión
*/
DROP TEMPORARY TABLE IF EXISTS tmp.zone;
CREATE TEMPORARY TABLE tmp.zone (
id INT PRIMARY KEY)
ENGINE=MEMORY;
INSERT INTO tmp.zone(id)
SELECT id
FROM vn.zone;
CALL vn.zone_getOptionsForShipment(vDated, TRUE);
CALL vn.zone_getClosed();
SELECT zo.zoneFk,
zo.`hour`etd,
(zo.`hour` <= TIME(util.VN_NOW())) isLate,
!ISNULL(cz.zoneFk) isFull,
zw.warehouseFk,
zo.landed
FROM tmp.zoneOption zo
JOIN vn.zone z ON z.id = zo.zoneFk
JOIN vn.zoneWarehouse zw ON zw.zoneFk = z.id
LEFT JOIN tmp.closedZones cz
ON cz.warehouseFk = zw.warehouseFk
AND cz.zoneFk = zo.zoneFk;
DROP TEMPORARY TABLE
tmp.closedZones,
tmp.zoneOption,
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 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!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 = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` 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, FALSE);
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 = vWarehouse
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 */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `zone_upcomingDeliveries` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!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 */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_upcomingDeliveries`()
BEGIN
DECLARE vForwardDays INT;
SELECT forwardDays INTO vForwardDays FROM zoneConfig;
CALL util.time_generate(util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL vForwardDays DAY));
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, ti.dated) landed,
ti.dated shipped
FROM zone z
JOIN zoneEvent e ON e.zoneFk = z.id
JOIN tmp.time ti ON ti.dated BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY, vForwardDays, util.VN_CURDATE());
DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption;
CREATE TEMPORARY TABLE tmp.zoneOption
ENGINE = MEMORY
SELECT *
FROM (
SELECT z.id zoneFk,
TIME(IFNULL(e.`hour`, z.`hour`)) `hour`,
l.travelingDays,
IFNULL(e.price, z.price) price,
IFNULL(e.bonus, z.bonus) bonus,
l.landed,
l.shipped
FROM zone z
JOIN zoneEvent e ON e.zoneFk = z.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`)
)
ORDER BY
zoneFk,
CASE
WHEN e.`type` = 'day'
THEN 1
WHEN e.`type` = 'range'
THEN 2
ELSE 3
END
LIMIT 10000000000000000000
) t
GROUP BY zoneFk, landed;
DELETE t FROM tmp.zoneOption t
JOIN zoneExclusion e ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed
LEFT JOIN zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id
WHERE eg.zoneExclusionFk IS NULL;
SELECT MAX(zo.`hour`) `hour`, zg.`name`, zo.shipped, zo.zoneFk
FROM tmp.zoneOption zo
JOIN `zone` z ON z.id = zo.zoneFk
JOIN agencyMode am ON am.id = z.agencyModeFk
JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
JOIN zoneIncluded zi ON zi.zoneFk = z.id
JOIN zoneGeo zg ON zg.id = zi.geoFk AND zg.type = 'province'
WHERE dm.code = 'DELIVERY'
GROUP BY shipped, zg.`name`
ORDER BY shipped, zg.`name`;
DROP TEMPORARY TABLE tmp.time, 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 */ ;
--
-- Current Database: `vn2008`
--
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vn2008` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */;
USE `vn2008`;
--
-- Temporary table structure for view `Agencias`
--
DROP TABLE IF EXISTS `Agencias`;
/*!50001 DROP VIEW IF EXISTS `Agencias`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Agencias` AS SELECT
1 AS `Id_Agencia`,
1 AS `Agencia`,
1 AS `description`,
1 AS `Vista`,
1 AS `m3`,
1 AS `web`,
1 AS `agency_id`,
1 AS `inflacion`,
1 AS `is_volumetric`,
1 AS `send_mail`,
1 AS `tpv`,
1 AS `code`,
1 AS `show_AgencyName`,
1 AS `isRiskFree` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Agencias_province__`
--
DROP TABLE IF EXISTS `Agencias_province__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Agencias_province__` (
`province_id` smallint(6) unsigned NOT NULL,
`agency_id` smallint(5) unsigned NOT NULL,
`zona` tinyint(4) NOT NULL,
`warehouse_id` smallint(6) unsigned NOT NULL,
`route` tinyint(4) NOT NULL COMMENT 'Etiqueta zeleris',
`isVolumetric` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`province_id`,`agency_id`,`warehouse_id`),
KEY `warehouse_id` (`warehouse_id`),
KEY `agency_id` (`agency_id`),
CONSTRAINT `Agencias_province___ibfk_1` FOREIGN KEY (`province_id`) REFERENCES `vn`.`province` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `Agencias_province___ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `Agencias_province___ibfk_3` FOREIGN KEY (`agency_id`) REFERENCES `vn`.`agency` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Articles`
--
DROP TABLE IF EXISTS `Articles`;
/*!50001 DROP VIEW IF EXISTS `Articles`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Articles` AS SELECT
1 AS `Id_Article`,
1 AS `Article`,
1 AS `tipo_id`,
1 AS `Medida`,
1 AS `Color`,
1 AS `Categoria`,
1 AS `Tallos`,
1 AS `id_origen`,
1 AS `description`,
1 AS `producer_id`,
1 AS `Codintrastat`,
1 AS `caja`,
1 AS `expenseFk`,
1 AS `comments`,
1 AS `relevancy`,
1 AS `Foto`,
1 AS `generic`,
1 AS `density`,
1 AS `PVP`,
1 AS `Min`,
1 AS `isActive`,
1 AS `longName`,
1 AS `subName`,
1 AS `tag5`,
1 AS `value5`,
1 AS `tag6`,
1 AS `value6`,
1 AS `tag7`,
1 AS `value7`,
1 AS `tag8`,
1 AS `value8`,
1 AS `tag9`,
1 AS `value9`,
1 AS `tag10`,
1 AS `value10`,
1 AS `minimum`,
1 AS `upToDown`,
1 AS `hasKgPrice`,
1 AS `Equivalente`,
1 AS `Imprimir`,
1 AS `Familia__`,
1 AS `do_photo`,
1 AS `odbc_date`,
1 AS `isFloramondo`,
1 AS `supplyResponseFk`,
1 AS `stemMultiplier`,
1 AS `itemPackingTypeFk`,
1 AS `packingOut` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Baldas__`
--
DROP TABLE IF EXISTS `Baldas__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Baldas__` (
`Id_Estanterias` int(11) NOT NULL,
`Id_Baldas` int(11) NOT NULL,
`h` int(11) NOT NULL,
PRIMARY KEY (`Id_Estanterias`,`Id_Baldas`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Bancos`
--
DROP TABLE IF EXISTS `Bancos`;
/*!50001 DROP VIEW IF EXISTS `Bancos`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Bancos` AS SELECT
1 AS `Id_Banco`,
1 AS `Banco`,
1 AS `Cuenta`,
1 AS `cash`,
1 AS `entity_id`,
1 AS `activo`,
1 AS `currencyFk` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Bancos_poliza`
--
DROP TABLE IF EXISTS `Bancos_poliza`;
/*!50001 DROP VIEW IF EXISTS `Bancos_poliza`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Bancos_poliza` AS SELECT
1 AS `poliza_id`,
1 AS `referencia`,
1 AS `importe`,
1 AS `com_dispuesto`,
1 AS `com_no_dispuesto`,
1 AS `com_anual`,
1 AS `apertura`,
1 AS `cierre`,
1 AS `Id_Banco`,
1 AS `empresa_id`,
1 AS `supplierFk`,
1 AS `description`,
1 AS `hasGuarantee`,
1 AS `dmsFk`,
1 AS `notaryFk`,
1 AS `currencyFk`,
1 AS `amortizationTypeFk`,
1 AS `periodicityTypeFk`,
1 AS `insuranceExpired` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Brasa__`
--
DROP TABLE IF EXISTS `Brasa__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Brasa__` (
`Id_Cliente` int(10) unsigned NOT NULL DEFAULT 0,
`Cliente` varchar(50) NOT NULL,
`Vista` int(10) unsigned NOT NULL DEFAULT 0,
`Reg` bigint(21) unsigned NOT NULL DEFAULT 0,
`Consumo` double NOT NULL,
`Grupo` int(10) unsigned NOT NULL,
PRIMARY KEY (`Id_Cliente`),
KEY `Index_1` (`Id_Cliente`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Cajas`
--
DROP TABLE IF EXISTS `Cajas`;
/*!50001 DROP VIEW IF EXISTS `Cajas`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Cajas` AS SELECT
1 AS `Id_Caja`,
1 AS `Cajafecha`,
1 AS `Serie`,
1 AS `Concepto`,
1 AS `Entrada`,
1 AS `Salida`,
1 AS `Id_Banco`,
1 AS `empresa_id`,
1 AS `Partida`,
1 AS `InForeignValue`,
1 AS `OutForeignValue`,
1 AS `Id_Trabajador`,
1 AS `id_calculated`,
1 AS `Numero`,
1 AS `linked`,
1 AS `odbc_date`,
1 AS `ok`,
1 AS `warehouse_id`,
1 AS `conciliado`,
1 AS `Proveedores_account_Id` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Clases__`
--
DROP TABLE IF EXISTS `Clases__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Clases__` (
`Id_Clase` int(11) NOT NULL DEFAULT 0,
`Clase` varchar(50) DEFAULT NULL,
PRIMARY KEY (`Id_Clase`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Clientes`
--
DROP TABLE IF EXISTS `Clientes`;
/*!50001 DROP VIEW IF EXISTS `Clientes`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Clientes` AS SELECT
1 AS `id_cliente`,
1 AS `cliente`,
1 AS `if`,
1 AS `razonSocial`,
1 AS `contacto`,
1 AS `domicilio`,
1 AS `poblacion`,
1 AS `codPostal`,
1 AS `telefono`,
1 AS `movil`,
1 AS `real`,
1 AS `e-mail`,
1 AS `iban`,
1 AS `vencimiento`,
1 AS `Cuenta`,
1 AS `RE`,
1 AS `province_id`,
1 AS `invoice`,
1 AS `credito`,
1 AS `Id_Pais`,
1 AS `activo`,
1 AS `gestdoc_id`,
1 AS `calidad`,
1 AS `pay_met_id`,
1 AS `created`,
1 AS `mail`,
1 AS `chanel_id`,
1 AS `sepaVnl`,
1 AS `coreVnl`,
1 AS `coreVnh`,
1 AS `hasLcr`,
1 AS `default_address`,
1 AS `risk_calculated`,
1 AS `invoiceByAddress`,
1 AS `contabilizado`,
1 AS `congelado`,
1 AS `creditInsurance`,
1 AS `isCreatedAsServed`,
1 AS `hasInvoiceSimplified`,
1 AS `Id_Trabajador`,
1 AS `vies`,
1 AS `bankEntityFk`,
1 AS `typeFk` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Clientes_dits__`
--
DROP TABLE IF EXISTS `Clientes_dits__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Clientes_dits__` (
`idClientes_dits` int(11) NOT NULL AUTO_INCREMENT,
`idaccion_dits` int(11) NOT NULL,
`ODBC_DATE` timestamp NOT NULL DEFAULT current_timestamp(),
`Id_Ticket` int(11) NOT NULL,
`Id_Trabajador` int(11) NOT NULL,
`value_old` varchar(100) DEFAULT NULL,
`value_new` varchar(100) DEFAULT NULL,
PRIMARY KEY (`idClientes_dits`),
KEY `idaccion_dits` (`idaccion_dits`),
CONSTRAINT `Clientes_dits___ibfk_1` FOREIGN KEY (`idaccion_dits`) REFERENCES `accion_dits__` (`idaccion_dits`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `Clientes_empresa__`
--
DROP TABLE IF EXISTS `Clientes_empresa__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Clientes_empresa__` (
`Id_Clientes_empresa` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`Id_Cliente` int(11) NOT NULL,
`empresa_id` int(10) unsigned NOT NULL,
`fecha_ini` date NOT NULL,
`fecha_fin` date NOT NULL,
PRIMARY KEY (`Id_Clientes_empresa`),
KEY `empresa_id_idx` (`empresa_id`),
CONSTRAINT `Clientes_empresaCompany_Fk` FOREIGN KEY (`empresa_id`) REFERENCES `vn`.`company` (`id`) ON DELETE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `Clientes_event__`
--
DROP TABLE IF EXISTS `Clientes_event__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Clientes_event__` (
`Id_Cliente` int(11) NOT NULL,
`quantity` tinyint(3) unsigned NOT NULL,
`odbc_date` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`Id_Cliente`),
CONSTRAINT `Clientes_event___ibfk_1` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `Clientes_potenciales__`
--
DROP TABLE IF EXISTS `Clientes_potenciales__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Clientes_potenciales__` (
`id` int(11) NOT NULL,
`PAIS` varchar(12) DEFAULT NULL,
`ACTIVIDAD` varchar(10) DEFAULT NULL,
`NOMBRE` varchar(45) NOT NULL DEFAULT '',
`PROVINCIA` varchar(25) DEFAULT NULL,
`POBLACION` varchar(45) NOT NULL DEFAULT '',
`CP` varchar(10) DEFAULT NULL,
`DIR_POSTAL` varchar(45) NOT NULL DEFAULT '',
`TELEFONO` varchar(12) NOT NULL DEFAULT '',
`TELEFONO2` varchar(12) NOT NULL DEFAULT '',
`FAX` varchar(12) NOT NULL DEFAULT '',
`E-MAIL` varchar(45) DEFAULT NULL,
`pagweb` varchar(45) DEFAULT NULL,
`SERVICIOS` varchar(45) DEFAULT NULL,
`state_id` smallint(6) DEFAULT 0 COMMENT '0 no se ha hecho nada\n1 ya existe el cliente\n2 cliente conseguido\n3 desestimado',
`Id_Trabajador` smallint(6) DEFAULT NULL,
`Notas` varchar(255) DEFAULT NULL,
`odbc_date` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`NOMBRE`,`POBLACION`,`DIR_POSTAL`,`TELEFONO`,`TELEFONO2`,`FAX`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Comparativa`
--
DROP TABLE IF EXISTS `Comparativa`;
/*!50001 DROP VIEW IF EXISTS `Comparativa`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Comparativa` AS SELECT
1 AS `Periodo`,
1 AS `Id_Article`,
1 AS `warehouse_id`,
1 AS `Cantidad`,
1 AS `price`,
1 AS `countryFk` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Compres`
--
DROP TABLE IF EXISTS `Compres`;
/*!50001 DROP VIEW IF EXISTS `Compres`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Compres` AS SELECT
1 AS `Id_Compra`,
1 AS `Id_Entrada`,
1 AS `Id_Article`,
1 AS `Costefijo`,
1 AS `Cantidad`,
1 AS `Id_Cubo`,
1 AS `Etiquetas`,
1 AS `Portefijo`,
1 AS `Embalajefijo`,
1 AS `Comisionfija`,
1 AS `Packing`,
1 AS `grouping`,
1 AS `caja`,
1 AS `Nicho`,
1 AS `Tarifa1`,
1 AS `Tarifa2`,
1 AS `Tarifa3`,
1 AS `PVP`,
1 AS `Vida`,
1 AS `punteo`,
1 AS `buy_edi_id`,
1 AS `odbc_date`,
1 AS `Novincular`,
1 AS `isPickedOff`,
1 AS `Id_Trabajador`,
1 AS `weight`,
1 AS `dispatched`,
1 AS `container_id`,
1 AS `itemOriginalFk` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Compres_mark`
--
DROP TABLE IF EXISTS `Compres_mark`;
/*!50001 DROP VIEW IF EXISTS `Compres_mark`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Compres_mark` AS SELECT
1 AS `Id_Compra`,
1 AS `comment`,
1 AS `mark`,
1 AS `odbc_date` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Compres_ok__`
--
DROP TABLE IF EXISTS `Compres_ok__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Compres_ok__` (
`Id_Compra` int(11) NOT NULL,
`valor` tinyint(3) unsigned NOT NULL DEFAULT 0,
`odbc_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`original_quantity` double DEFAULT NULL,
`Id_Trabajador` int(10) unsigned NOT NULL,
`Id_Accion` varchar(45) NOT NULL,
`Id_Compra_ok` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`Id_Compra_ok`),
KEY `Id_Movimiento` (`Id_Compra`),
KEY `Id_Accion` (`Id_Accion`),
KEY `Compres_ok_Id_Trabajador_idx` (`Id_Trabajador`),
CONSTRAINT `Compres_ok_Id_Trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`),
CONSTRAINT `Compres_ok___ibfk_1` FOREIGN KEY (`Id_Compra`) REFERENCES `vn`.`buy` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Consignatarios`
--
DROP TABLE IF EXISTS `Consignatarios`;
/*!50001 DROP VIEW IF EXISTS `Consignatarios`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Consignatarios` AS SELECT
1 AS `id_consigna`,
1 AS `Id_cliente`,
1 AS `domicilio`,
1 AS `poblacion`,
1 AS `codPostal`,
1 AS `province_id`,
1 AS `telefono`,
1 AS `movil`,
1 AS `consignatario`,
1 AS `predeterminada`,
1 AS `longitude`,
1 AS `latitude`,
1 AS `Id_Agencia`,
1 AS `isEqualizated`,
1 AS `active` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Consignatarios_devices__`
--
DROP TABLE IF EXISTS `Consignatarios_devices__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Consignatarios_devices__` (
`Id_Consigna` int(11) NOT NULL,
`serialNumber` varchar(45) NOT NULL,
`notas` varchar(45) DEFAULT NULL,
PRIMARY KEY (`Id_Consigna`,`serialNumber`),
CONSTRAINT `Condigna_devices` FOREIGN KEY (`Id_Consigna`) REFERENCES `vn`.`address` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `Conteo__`
--
DROP TABLE IF EXISTS `Conteo__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Conteo__` (
`Id_Conteo` int(11) NOT NULL AUTO_INCREMENT,
`Id_Article` int(11) NOT NULL,
`Fecha` timestamp NOT NULL DEFAULT current_timestamp(),
`dispositivo` varchar(15) DEFAULT NULL,
`warehouse_id` int(10) unsigned NOT NULL DEFAULT 1,
PRIMARY KEY (`Id_Conteo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Cubos`
--
DROP TABLE IF EXISTS `Cubos`;
/*!50001 DROP VIEW IF EXISTS `Cubos`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Cubos` AS SELECT
1 AS `Id_Cubo`,
1 AS `Volumen`,
1 AS `X`,
1 AS `Y`,
1 AS `Z`,
1 AS `Retornable`,
1 AS `odbc_date`,
1 AS `item_id`,
1 AS `pvp`,
1 AS `bultoCubico`,
1 AS `Valor`,
1 AS `idCubos_Retorno`,
1 AS `Bajan`,
1 AS `Suben`,
1 AS `Base`,
1 AS `box`,
1 AS `costeRetorno` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Cubos_Retorno`
--
DROP TABLE IF EXISTS `Cubos_Retorno`;
/*!50001 DROP VIEW IF EXISTS `Cubos_Retorno`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Cubos_Retorno` AS SELECT
1 AS `idCubos_Retorno`,
1 AS `Soporte`,
1 AS `Vacio`,
1 AS `Lleno` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Entradas`
--
DROP TABLE IF EXISTS `Entradas`;
/*!50001 DROP VIEW IF EXISTS `Entradas`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Entradas` AS SELECT
1 AS `Id_Entrada`,
1 AS `Id_Proveedor`,
1 AS `Referencia`,
1 AS `reference`,
1 AS `Inventario`,
1 AS `Confirmada`,
1 AS `Pedida`,
1 AS `Redada`,
1 AS `comision`,
1 AS `odbc_date`,
1 AS `Notas_Eva`,
1 AS `travel_id`,
1 AS `Id_Moneda`,
1 AS `empresa_id`,
1 AS `gestdoc_id`,
1 AS `recibida_id`,
1 AS `Fecha`,
1 AS `Anotadoencaja`,
1 AS `loadPriority`,
1 AS `sub`,
1 AS `kop`,
1 AS `pro`,
1 AS `invoiceAmount`,
1 AS `buyerFk`,
1 AS `typeFk` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Entradas_Auto`
--
DROP TABLE IF EXISTS `Entradas_Auto`;
/*!50001 DROP VIEW IF EXISTS `Entradas_Auto`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Entradas_Auto` AS SELECT
1 AS `Id_Entrada` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Entradas_kop__`
--
DROP TABLE IF EXISTS `Entradas_kop__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Entradas_kop__` (
`Id_Entradas_kop` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`Id_Entrada` int(11) NOT NULL,
`kop` int(11) DEFAULT NULL,
`sub` mediumint(8) unsigned DEFAULT NULL,
PRIMARY KEY (`Id_Entradas_kop`),
KEY `entradas_entradas_kop_idx` (`Id_Entrada`),
CONSTRAINT `entradas_entradas_kop` FOREIGN KEY (`Id_Entrada`) REFERENCES `vn`.`entry` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Entradas_orden`
--
DROP TABLE IF EXISTS `Entradas_orden`;
/*!50001 DROP VIEW IF EXISTS `Entradas_orden`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Entradas_orden` AS SELECT
1 AS `Id_Entrada`,
1 AS `orden` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Espionajes__`
--
DROP TABLE IF EXISTS `Espionajes__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Espionajes__` (
`idEspionaje` int(11) NOT NULL AUTO_INCREMENT,
`Id_Trabajador` varchar(45) DEFAULT NULL,
`Fecha` date DEFAULT NULL,
`HoraEntrada` time DEFAULT NULL,
`HoraSalida` time DEFAULT NULL,
`Id_Equipo` int(11) DEFAULT NULL,
PRIMARY KEY (`idEspionaje`),
KEY `index` (`Id_Trabajador`,`Fecha`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `Estados__`
--
DROP TABLE IF EXISTS `Estados__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Estados__` (
`Id_Estado` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
`Estado` varchar(50) DEFAULT NULL,
PRIMARY KEY (`Id_Estado`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `Familias__`
--
DROP TABLE IF EXISTS `Familias__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Familias__` (
`Familia` varchar(3) NOT NULL,
`Subcuenta` varchar(10) DEFAULT NULL,
`Descripcion` varchar(50) DEFAULT NULL,
PRIMARY KEY (`Familia`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `Forms__`
--
DROP TABLE IF EXISTS `Forms__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Forms__` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`titulo` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `Grupos__`
--
DROP TABLE IF EXISTS `Grupos__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Grupos__` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`Grupo` varchar(45) NOT NULL,
`observation_type_id` tinyint(3) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Impresoras`
--
DROP TABLE IF EXISTS `Impresoras`;
/*!50001 DROP VIEW IF EXISTS `Impresoras`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Impresoras` AS SELECT
1 AS `Id_impresora`,
1 AS `Ruta`,
1 AS `Impresora`,
1 AS `referencia`,
1 AS `isLabeler` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Informes__`
--
DROP TABLE IF EXISTS `Informes__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Informes__` (
`Id_Informe` tinyint(3) unsigned NOT NULL,
`Informe` varchar(50) DEFAULT NULL,
PRIMARY KEY (`Id_Informe`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `Jefes__`
--
DROP TABLE IF EXISTS `Jefes__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Jefes__` (
`Id_Trabajador` int(10) unsigned NOT NULL,
`Id_Jefe` int(10) unsigned NOT NULL,
`Departamento` varchar(45) NOT NULL,
PRIMARY KEY (`Id_Trabajador`,`Id_Jefe`),
KEY `trabajador_jefe_idx` (`Id_Jefe`),
CONSTRAINT `trabajador_jefe` FOREIGN KEY (`Id_Jefe`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `trabajador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Deprecated 27-02-2023';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Monedas`
--
DROP TABLE IF EXISTS `Monedas`;
/*!50001 DROP VIEW IF EXISTS `Monedas`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Monedas` AS SELECT
1 AS `Id_Moneda`,
1 AS `Moneda`,
1 AS `Descripcion`,
1 AS `Cambio` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Monitoring__`
--
DROP TABLE IF EXISTS `Monitoring__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Monitoring__` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`equipo_id` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`form_id` int(11) NOT NULL,
`cliente_id` int(11) NOT NULL,
`ticket_id` int(11) NOT NULL,
`ODBC_TIME` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `equipo_id` (`equipo_id`,`user_id`,`form_id`,`cliente_id`,`ticket_id`),
KEY `user_id` (`user_id`),
KEY `form_id` (`form_id`),
KEY `cliente_id` (`cliente_id`),
KEY `ticket_id` (`ticket_id`),
CONSTRAINT `Monitoring_FK` FOREIGN KEY (`equipo_id`) REFERENCES `vn`.`host` (`code`) ON UPDATE CASCADE,
CONSTRAINT `Monitoring___ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `vn`.`worker` (`id`),
CONSTRAINT `Monitoring___ibfk_3` FOREIGN KEY (`form_id`) REFERENCES `Forms__` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Movimientos`
--
DROP TABLE IF EXISTS `Movimientos`;
/*!50001 DROP VIEW IF EXISTS `Movimientos`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Movimientos` AS SELECT
1 AS `Id_Movimiento`,
1 AS `Id_Article`,
1 AS `Id_Ticket`,
1 AS `Concepte`,
1 AS `Cantidad`,
1 AS `Preu`,
1 AS `Descuento`,
1 AS `Reservado`,
1 AS `OK`,
1 AS `odbc_date`,
1 AS `CostFixat`,
1 AS `PrecioFijado`,
1 AS `quantity`,
1 AS `isAdded` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Movimientos_avisar__`
--
DROP TABLE IF EXISTS `Movimientos_avisar__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Movimientos_avisar__` (
`Id_Movimiento` int(11) NOT NULL,
`Id_Remitente` int(11) DEFAULT NULL,
PRIMARY KEY (`Id_Movimiento`),
KEY `Movimiento` (`Id_Movimiento`),
KEY `Remitente` (`Id_Remitente`),
CONSTRAINT `Id_Movimientos_avisar_fk` FOREIGN KEY (`Id_Movimiento`) REFERENCES `vn`.`sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Movimientos_componentes`
--
DROP TABLE IF EXISTS `Movimientos_componentes`;
/*!50001 DROP VIEW IF EXISTS `Movimientos_componentes`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Movimientos_componentes` AS SELECT
1 AS `Id_Movimiento`,
1 AS `Id_Componente`,
1 AS `Valor`,
1 AS `created`,
1 AS `greuge` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Movimientos_mark`
--
DROP TABLE IF EXISTS `Movimientos_mark`;
/*!50001 DROP VIEW IF EXISTS `Movimientos_mark`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Movimientos_mark` AS SELECT
1 AS `Id_Movimiento`,
1 AS `valor`,
1 AS `odbc_date`,
1 AS `original_quantity`,
1 AS `Id_Trabajador`,
1 AS `Id_Movimiento_mark`,
1 AS `stateFk` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Movimientos_revisar__`
--
DROP TABLE IF EXISTS `Movimientos_revisar__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Movimientos_revisar__` (
`Id_Movimiento` int(11) NOT NULL,
`Comentario` varchar(255) DEFAULT NULL,
`Revisado` tinyint(1) NOT NULL DEFAULT 0,
`Id_Remitente` int(11) DEFAULT NULL,
`Id_Destinatario` int(11) DEFAULT NULL,
PRIMARY KEY (`Id_Movimiento`),
KEY `Remitente` (`Id_Remitente`),
KEY `Destinatario` (`Id_Destinatario`),
CONSTRAINT `Movimientos_revisar___ibfk_1` FOREIGN KEY (`Id_Movimiento`) REFERENCES `vn`.`sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `Objetivos__`
--
DROP TABLE IF EXISTS `Objetivos__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Objetivos__` (
`Periodo` int(11) NOT NULL,
`Objetivo` double NOT NULL,
PRIMARY KEY (`Periodo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Deprecated 27-02-2023';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Ordenes`
--
DROP TABLE IF EXISTS `Ordenes`;
/*!50001 DROP VIEW IF EXISTS `Ordenes`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Ordenes` AS SELECT
1 AS `Id_ORDEN`,
1 AS `ORDEN`,
1 AS `requesterFk`,
1 AS `attenderFk`,
1 AS `CANTIDAD`,
1 AS `Id_ARTICLE`,
1 AS `PRECIOMAX`,
1 AS `isOk`,
1 AS `Id_Movimiento`,
1 AS `ticketFk`,
1 AS `COMENTARIO`,
1 AS `odbc_date`,
1 AS `datORDEN`,
1 AS `datTICKET`,
1 AS `CodVENDEDOR`,
1 AS `Id_CLIENTE`,
1 AS `TOTAL`,
1 AS `datCOMPRA` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Origen`
--
DROP TABLE IF EXISTS `Origen`;
/*!50001 DROP VIEW IF EXISTS `Origen`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Origen` AS SELECT
1 AS `id`,
1 AS `Abreviatura`,
1 AS `Origen`,
1 AS `Id_Paises`,
1 AS `warehouse_id` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Pagares`
--
DROP TABLE IF EXISTS `Pagares`;
/*!50001 DROP VIEW IF EXISTS `Pagares`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Pagares` AS SELECT
1 AS `Id_Pagare`,
1 AS `Fechaemision`,
1 AS `Concepto`,
1 AS `pago_id` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Paises`
--
DROP TABLE IF EXISTS `Paises`;
/*!50001 DROP VIEW IF EXISTS `Paises`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Paises` AS SELECT
1 AS `Id`,
1 AS `Pais`,
1 AS `CEE`,
1 AS `isUeeMember`,
1 AS `Codigo`,
1 AS `Id_Moneda`,
1 AS `geoFk`,
1 AS `ibanLength`,
1 AS `hasDailyInvoice` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Permisos__`
--
DROP TABLE IF EXISTS `Permisos__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Permisos__` (
`Id_Grupo` int(10) unsigned NOT NULL,
`Id_Trabajador` int(10) unsigned NOT NULL,
`empresa_id` int(10) unsigned NOT NULL DEFAULT 442,
PRIMARY KEY (`Id_Grupo`,`Id_Trabajador`),
KEY `empresa_id` (`empresa_id`),
KEY `Permisos_ibfk_3_idx` (`Id_Trabajador`),
CONSTRAINT `PermisosCompany_Fk` FOREIGN KEY (`empresa_id`) REFERENCES `vn`.`company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `Permisos___ibfk_2` FOREIGN KEY (`Id_Grupo`) REFERENCES `Grupos__` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `Permisos___ibfk_3` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `PreciosEspeciales`
--
DROP TABLE IF EXISTS `PreciosEspeciales`;
/*!50001 DROP VIEW IF EXISTS `PreciosEspeciales`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `PreciosEspeciales` AS SELECT
1 AS `Id_PrecioEspecial`,
1 AS `Id_Cliente`,
1 AS `Id_Article`,
1 AS `PrecioEspecial` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Proveedores`
--
DROP TABLE IF EXISTS `Proveedores`;
/*!50001 DROP VIEW IF EXISTS `Proveedores`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Proveedores` AS SELECT
1 AS `Id_Proveedor`,
1 AS `Proveedor`,
1 AS `cuenta`,
1 AS `pais_id`,
1 AS `NIF`,
1 AS `Agricola`,
1 AS `Telefono`,
1 AS `cuentaret`,
1 AS `ComisionProveedor`,
1 AS `odbc_time`,
1 AS `postcode_id`,
1 AS `active`,
1 AS `Domicilio`,
1 AS `Localidad`,
1 AS `province_id`,
1 AS `codpos`,
1 AS `pay_met_id`,
1 AS `pay_dem_id`,
1 AS `Alias`,
1 AS `oficial`,
1 AS `workerFk`,
1 AS `pay_day`,
1 AS `serious`,
1 AS `notas`,
1 AS `taxTypeSageFk`,
1 AS `withholdingSageFk`,
1 AS `isTrucker`,
1 AS `transactionTypeSageFk`,
1 AS `supplierActivityFk`,
1 AS `healthRegister`,
1 AS `isPayMethodChecked` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Proveedores_cargueras`
--
DROP TABLE IF EXISTS `Proveedores_cargueras`;
/*!50001 DROP VIEW IF EXISTS `Proveedores_cargueras`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Proveedores_cargueras` AS SELECT
1 AS `Id_Proveedor` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Proveedores_comunicados__`
--
DROP TABLE IF EXISTS `Proveedores_comunicados__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Proveedores_comunicados__` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Id_Proveedor` int(10) unsigned NOT NULL,
`escrito_id` int(11) NOT NULL,
`fecha` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `Proveedor` (`Id_Proveedor`),
KEY `Escrito` (`escrito_id`),
CONSTRAINT `Proveedores_comunicados___ibfk_4` FOREIGN KEY (`escrito_id`) REFERENCES `Proveedores_escritos__` (`id`) ON UPDATE CASCADE,
CONSTRAINT `Proveedores_comunicados_supplierFk` FOREIGN KEY (`Id_Proveedor`) REFERENCES `vn`.`supplier` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `Proveedores_escritos__`
--
DROP TABLE IF EXISTS `Proveedores_escritos__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Proveedores_escritos__` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`escrito` varchar(45) NOT NULL,
`informe` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Proveedores_gestdoc`
--
DROP TABLE IF EXISTS `Proveedores_gestdoc`;
/*!50001 DROP VIEW IF EXISTS `Proveedores_gestdoc`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Proveedores_gestdoc` AS SELECT
1 AS `Id_Proveedor`,
1 AS `gestdoc_id` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Recibos`
--
DROP TABLE IF EXISTS `Recibos`;
/*!50001 DROP VIEW IF EXISTS `Recibos`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Recibos` AS SELECT
1 AS `Id`,
1 AS `Id_Factura`,
1 AS `Entregado`,
1 AS `Fechacobro`,
1 AS `Id_Trabajador`,
1 AS `Id_Banco`,
1 AS `Id_Cliente`,
1 AS `odbc_date`,
1 AS `empresa_id`,
1 AS `conciliado` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Recibos_recorded__`
--
DROP TABLE IF EXISTS `Recibos_recorded__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Recibos_recorded__` (
`Id_Recibos` int(11) NOT NULL,
`recorded` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'Marcado si se ha contabilizado',
PRIMARY KEY (`Id_Recibos`),
CONSTRAINT `Recibos_recorded___ibfk_1` FOREIGN KEY (`Id_Recibos`) REFERENCES `vn`.`receipt` (`Id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Deprecated 27-02-2023';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Remesas`
--
DROP TABLE IF EXISTS `Remesas`;
/*!50001 DROP VIEW IF EXISTS `Remesas`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Remesas` AS SELECT
1 AS `Id_Remesa`,
1 AS `Fecha Remesa`,
1 AS `Banco`,
1 AS `empresa_id` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Reservas__`
--
DROP TABLE IF EXISTS `Reservas__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Reservas__` (
`Id_Reserva` int(11) NOT NULL AUTO_INCREMENT,
`Id_Ticket` int(11) DEFAULT 0,
`Fecha` datetime DEFAULT NULL,
`Alias` varchar(50) DEFAULT NULL,
`article` varchar(50) DEFAULT NULL,
`medida` varchar(50) DEFAULT NULL,
`categoria` varchar(50) DEFAULT NULL,
`color` varchar(50) DEFAULT NULL,
`origen` varchar(50) DEFAULT NULL,
`cantidad` int(11) DEFAULT 0,
`Id_Article` double DEFAULT 0,
`buyFk` int(11) NOT NULL,
`grouping` int(11) DEFAULT NULL,
`packing` int(11) DEFAULT NULL,
PRIMARY KEY (`Id_Reserva`),
KEY `Id_1` (`Id_Ticket`),
KEY `Id_Article` (`Id_Article`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Deprecated 27-02-2023';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Rutas`
--
DROP TABLE IF EXISTS `Rutas`;
/*!50001 DROP VIEW IF EXISTS `Rutas`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Rutas` AS SELECT
1 AS `Id_Ruta`,
1 AS `Id_Trabajador`,
1 AS `Fecha`,
1 AS `Id_Vehiculo`,
1 AS `Id_Agencia`,
1 AS `Hora`,
1 AS `ok`,
1 AS `km_start`,
1 AS `km_end`,
1 AS `date_start`,
1 AS `date_end`,
1 AS `gestdoc_id`,
1 AS `cost`,
1 AS `m3`,
1 AS `description` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Saldos_Prevision`
--
DROP TABLE IF EXISTS `Saldos_Prevision`;
/*!50001 DROP VIEW IF EXISTS `Saldos_Prevision`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Saldos_Prevision` AS SELECT
1 AS `Saldos_Prevision_id`,
1 AS `Descripcion`,
1 AS `Importe`,
1 AS `Fecha`,
1 AS `Id_Banco`,
1 AS `empresa_id` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Series__`
--
DROP TABLE IF EXISTS `Series__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Series__` (
`Id_Serie` varchar(2) NOT NULL,
`Serie` varchar(30) DEFAULT NULL,
`Cuenta` varchar(10) DEFAULT NULL,
PRIMARY KEY (`Id_Serie`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Split_lines`
--
DROP TABLE IF EXISTS `Split_lines`;
/*!50001 DROP VIEW IF EXISTS `Split_lines`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Split_lines` AS SELECT
1 AS `Id_Split_lines`,
1 AS `Id_Split`,
1 AS `Id_Article`,
1 AS `Id_Compra` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Splits`
--
DROP TABLE IF EXISTS `Splits`;
/*!50001 DROP VIEW IF EXISTS `Splits`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Splits` AS SELECT
1 AS `Id_Split`,
1 AS `Id_Ticket`,
1 AS `Id_Entrada`,
1 AS `Fecha`,
1 AS `Notas` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Tickets`
--
DROP TABLE IF EXISTS `Tickets`;
/*!50001 DROP VIEW IF EXISTS `Tickets`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Tickets` AS SELECT
1 AS `Id_Ticket`,
1 AS `Id_Cliente`,
1 AS `warehouse_id`,
1 AS `Fecha`,
1 AS `landing`,
1 AS `Alias`,
1 AS `Factura`,
1 AS `Id_Consigna`,
1 AS `Localizacion`,
1 AS `Solucion`,
1 AS `Id_Ruta`,
1 AS `empresa_id`,
1 AS `Id_Agencia`,
1 AS `Prioridad`,
1 AS `Bultos`,
1 AS `isDeleted`,
1 AS `odbc_date`,
1 AS `Id_Trabajador`,
1 AS `Observaciones`,
1 AS `Firmado`,
1 AS `Etiquetasemitidas`,
1 AS `PedidoImpreso`,
1 AS `Hora`,
1 AS `blocked`,
1 AS `priority`,
1 AS `boxed`,
1 AS `zoneFk`,
1 AS `totalWithVat`,
1 AS `totalWithoutVat` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Tickets_stack__`
--
DROP TABLE IF EXISTS `Tickets_stack__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Tickets_stack__` (
`Id_Ticket` int(11) NOT NULL,
`orden` smallint(5) unsigned NOT NULL,
`label_number` smallint(6) DEFAULT 0,
`preparado` tinyint(4) DEFAULT 0,
PRIMARY KEY (`Id_Ticket`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Tickets_state`
--
DROP TABLE IF EXISTS `Tickets_state`;
/*!50001 DROP VIEW IF EXISTS `Tickets_state`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Tickets_state` AS SELECT
1 AS `Id_Ticket`,
1 AS `inter_id`,
1 AS `state_name` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Tickets_turno`
--
DROP TABLE IF EXISTS `Tickets_turno`;
/*!50001 DROP VIEW IF EXISTS `Tickets_turno`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Tickets_turno` AS SELECT
1 AS `Id_Ticket`,
1 AS `weekDay` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Tintas`
--
DROP TABLE IF EXISTS `Tintas`;
/*!50001 DROP VIEW IF EXISTS `Tintas`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Tintas` AS SELECT
1 AS `Id_Tinta`,
1 AS `name`,
1 AS `Tinta`,
1 AS `Orden`,
1 AS `ball`,
1 AS `cargex`,
1 AS `colorHex` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Tipos`
--
DROP TABLE IF EXISTS `Tipos`;
/*!50001 DROP VIEW IF EXISTS `Tipos`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Tipos` AS SELECT
1 AS `tipo_id`,
1 AS `Id_Tipo`,
1 AS `Tipo`,
1 AS `Orden`,
1 AS `reino_id`,
1 AS `Id_Trabajador`,
1 AS `life`,
1 AS `isPackaging`,
1 AS `density`,
1 AS `inventory`,
1 AS `odbc_date`,
1 AS `confeccion`,
1 AS `Temperatura`,
1 AS `promo`,
1 AS `maneuver`,
1 AS `target`,
1 AS `top_margin`,
1 AS `profit` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Tipos_f11__`
--
DROP TABLE IF EXISTS `Tipos_f11__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Tipos_f11__` (
`f11_id` tinyint(4) NOT NULL AUTO_INCREMENT,
`description` varchar(15) NOT NULL,
PRIMARY KEY (`f11_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `Trabajadores`
--
DROP TABLE IF EXISTS `Trabajadores`;
/*!50001 DROP VIEW IF EXISTS `Trabajadores`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Trabajadores` AS SELECT
1 AS `Id_Trabajador`,
1 AS `Nombre`,
1 AS `user_id`,
1 AS `phone`,
1 AS `boss`,
1 AS `Foto`,
1 AS `DniExpiration`,
1 AS `CodigoTrabajador`,
1 AS `Apellidos`,
1 AS `hasMachineryAuthorized`,
1 AS `sub`,
1 AS `marital_status` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Tramos`
--
DROP TABLE IF EXISTS `Tramos`;
/*!50001 DROP VIEW IF EXISTS `Tramos`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Tramos` AS SELECT
1 AS `id`,
1 AS `Tramo` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `V_edi_item_track`
--
DROP TABLE IF EXISTS `V_edi_item_track`;
/*!50001 DROP VIEW IF EXISTS `V_edi_item_track`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `V_edi_item_track` AS SELECT
1 AS `item_id`,
1 AS `s1`,
1 AS `s2`,
1 AS `s3`,
1 AS `s4`,
1 AS `s5`,
1 AS `s6`,
1 AS `kop`,
1 AS `pac`,
1 AS `cat`,
1 AS `ori`,
1 AS `pro`,
1 AS `sub`,
1 AS `package`,
1 AS `item` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `Vehiculos_consumo`
--
DROP TABLE IF EXISTS `Vehiculos_consumo`;
/*!50001 DROP VIEW IF EXISTS `Vehiculos_consumo`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Vehiculos_consumo` AS SELECT
1 AS `Vehiculos_consumo_id`,
1 AS `Id_Vehiculo`,
1 AS `fecha`,
1 AS `km`,
1 AS `litros`,
1 AS `precio`,
1 AS `adblue`,
1 AS `peajes`,
1 AS `descuento`,
1 AS `silla`,
1 AS `odbc_date`,
1 AS `otros`,
1 AS `fuelTypeFk`,
1 AS `proveedoresFk`,
1 AS `liters100km`,
1 AS `gasoline` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `accion_dits__`
--
DROP TABLE IF EXISTS `accion_dits__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `accion_dits__` (
`idaccion_dits` int(11) NOT NULL AUTO_INCREMENT,
`accion` varchar(255) DEFAULT NULL,
PRIMARY KEY (`idaccion_dits`),
UNIQUE KEY `accion_UNIQUE` (`accion`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `account_conciliacion`
--
DROP TABLE IF EXISTS `account_conciliacion`;
/*!50001 DROP VIEW IF EXISTS `account_conciliacion`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `account_conciliacion` AS SELECT
1 AS `idaccount_conciliacion`,
1 AS `Id_Proveedores_account`,
1 AS `Fechaoperacion`,
1 AS `FechaValor`,
1 AS `importe`,
1 AS `Concepto`,
1 AS `DebeHaber`,
1 AS `id_calculated`,
1 AS `odbc_date` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `account_detail`
--
DROP TABLE IF EXISTS `account_detail`;
/*!50001 DROP VIEW IF EXISTS `account_detail`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `account_detail` AS SELECT
1 AS `account_detail_id`,
1 AS `value`,
1 AS `account_detail_type_id`,
1 AS `Id_Proveedores_account` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `account_detail_type`
--
DROP TABLE IF EXISTS `account_detail_type`;
/*!50001 DROP VIEW IF EXISTS `account_detail_type`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `account_detail_type` AS SELECT
1 AS `account_detail_type_id`,
1 AS `description` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `agencia_descuadre__`
--
DROP TABLE IF EXISTS `agencia_descuadre__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agencia_descuadre__` (
`agencia_descuadre_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Id_Ticket` int(11) NOT NULL,
`date` date NOT NULL,
`price` double(7,2) NOT NULL,
`Consignatario` varchar(50) NOT NULL,
`Tipo` varchar(30) NOT NULL,
PRIMARY KEY (`agencia_descuadre_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `agency`
--
DROP TABLE IF EXISTS `agency`;
/*!50001 DROP VIEW IF EXISTS `agency`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `agency` AS SELECT
1 AS `agency_id`,
1 AS `name`,
1 AS `warehouse_id`,
1 AS `propios`,
1 AS `workCenterFk` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `agency_hour__`
--
DROP TABLE IF EXISTS `agency_hour__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agency_hour__` (
`agency_hour_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`week_day` tinyint(3) unsigned DEFAULT NULL COMMENT 'funcion de mysql Lunes = 0, Domingo = 6',
`agency_id` smallint(5) unsigned DEFAULT NULL,
`warehouse_id` smallint(5) unsigned DEFAULT NULL,
`province_id` smallint(5) unsigned DEFAULT NULL,
`subtract_day` tinyint(10) unsigned NOT NULL COMMENT 'dias a restar de la Fecha de entrega',
`max_hour` tinyint(3) unsigned NOT NULL COMMENT 'maxima hora hasta la cual se pueden hacer pedidos',
PRIMARY KEY (`agency_hour_id`),
UNIQUE KEY `week_day` (`week_day`,`agency_id`,`warehouse_id`,`province_id`,`max_hour`),
KEY `agency_id` (`agency_id`),
KEY `warehouse_id` (`warehouse_id`),
KEY `province_id` (`province_id`),
CONSTRAINT `agency_hour___ibfk_1` FOREIGN KEY (`agency_id`) REFERENCES `vn`.`agency` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `agency_hour___ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `agency_hour___ibfk_3` FOREIGN KEY (`province_id`) REFERENCES `vn`.`province` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `agency_warehouse__`
--
DROP TABLE IF EXISTS `agency_warehouse__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agency_warehouse__` (
`agency_id` smallint(5) unsigned NOT NULL,
`warehouse_id` smallint(5) unsigned NOT NULL DEFAULT 1,
`Vista` tinyint(3) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`agency_id`,`warehouse_id`),
KEY `warehouse_id` (`warehouse_id`),
CONSTRAINT `agency_warehouse___ibfk_1` FOREIGN KEY (`agency_id`) REFERENCES `vn`.`agency` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `agency_warehouse___ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `airline`
--
DROP TABLE IF EXISTS `airline`;
/*!50001 DROP VIEW IF EXISTS `airline`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `airline` AS SELECT
1 AS `airline_id`,
1 AS `name` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `airport`
--
DROP TABLE IF EXISTS `airport`;
/*!50001 DROP VIEW IF EXISTS `airport`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `airport` AS SELECT
1 AS `airport_id`,
1 AS `name` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `albaran`
--
DROP TABLE IF EXISTS `albaran`;
/*!50001 DROP VIEW IF EXISTS `albaran`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `albaran` AS SELECT
1 AS `albaran_id`,
1 AS `ref`,
1 AS `note`,
1 AS `fecha`,
1 AS `fecha_entrega`,
1 AS `valor`,
1 AS `Id_Proveedor`,
1 AS `empresa_id`,
1 AS `warehouse_id`,
1 AS `albaran_state_id`,
1 AS `Id_Trabajador`,
1 AS `Id_Responsable`,
1 AS `department_id`,
1 AS `recibida_id`,
1 AS `farmingFk` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `albaran_gestdoc`
--
DROP TABLE IF EXISTS `albaran_gestdoc`;
/*!50001 DROP VIEW IF EXISTS `albaran_gestdoc`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `albaran_gestdoc` AS SELECT
1 AS `gestdoc_id`,
1 AS `albaran_id` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `albaran_state`
--
DROP TABLE IF EXISTS `albaran_state`;
/*!50001 DROP VIEW IF EXISTS `albaran_state`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `albaran_state` AS SELECT
1 AS `albaran_state_id`,
1 AS `state` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `awb`
--
DROP TABLE IF EXISTS `awb`;
/*!50001 DROP VIEW IF EXISTS `awb`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `awb` AS SELECT
1 AS `id`,
1 AS `codigo`,
1 AS `bultos`,
1 AS `peso`,
1 AS `MYSQL_TIME`,
1 AS `transitario_id`,
1 AS `iva_id`,
1 AS `duakk`,
1 AS `gestdoc_id`,
1 AS `importe`,
1 AS `carguera_id`,
1 AS `m3`,
1 AS `stems`,
1 AS `flight_id`,
1 AS `volume_weight`,
1 AS `hb`,
1 AS `rate`,
1 AS `booked`,
1 AS `issued`,
1 AS `operated`,
1 AS `bookEntried`,
1 AS `invoiceInFk`,
1 AS `isChecked`,
1 AS `isTransitoryChecked`,
1 AS `year`,
1 AS `invoiceInPaletizedFk`,
1 AS `observation`,
1 AS `hasFreightPrepaid`,
1 AS `propertyNumber` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `awb_component`
--
DROP TABLE IF EXISTS `awb_component`;
/*!50001 DROP VIEW IF EXISTS `awb_component`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `awb_component` AS SELECT
1 AS `id`,
1 AS `awb_id`,
1 AS `Id_Proveedor`,
1 AS `awb_component_type_id`,
1 AS `awb_role_id`,
1 AS `awb_unit_id`,
1 AS `value`,
1 AS `Id_Moneda`,
1 AS `recibida_id` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `awb_component_template`
--
DROP TABLE IF EXISTS `awb_component_template`;
/*!50001 DROP VIEW IF EXISTS `awb_component_template`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `awb_component_template` AS SELECT
1 AS `awb_component_template_id`,
1 AS `carguera_id`,
1 AS `airport_in`,
1 AS `airport_out`,
1 AS `airline_id`,
1 AS `awb_component_type_id`,
1 AS `Fecha`,
1 AS `awb_role_id`,
1 AS `awb_unit_id`,
1 AS `value`,
1 AS `max_value`,
1 AS `min_value`,
1 AS `Id_Moneda`,
1 AS `days` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `awb_component_type`
--
DROP TABLE IF EXISTS `awb_component_type`;
/*!50001 DROP VIEW IF EXISTS `awb_component_type`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `awb_component_type` AS SELECT
1 AS `awb_component_type_id`,
1 AS `description`,
1 AS `hasStems` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `awb_gestdoc`
--
DROP TABLE IF EXISTS `awb_gestdoc`;
/*!50001 DROP VIEW IF EXISTS `awb_gestdoc`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `awb_gestdoc` AS SELECT
1 AS `awb_gestdoc_id`,
1 AS `awb_id`,
1 AS `gestdoc_id` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `awb_recibida`
--
DROP TABLE IF EXISTS `awb_recibida`;
/*!50001 DROP VIEW IF EXISTS `awb_recibida`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `awb_recibida` AS SELECT
1 AS `awb_id`,
1 AS `recibida_id`,
1 AS `dua` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `awb_role`
--
DROP TABLE IF EXISTS `awb_role`;
/*!50001 DROP VIEW IF EXISTS `awb_role`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `awb_role` AS SELECT
1 AS `awb_role_id`,
1 AS `name` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `awb_unit`
--
DROP TABLE IF EXISTS `awb_unit`;
/*!50001 DROP VIEW IF EXISTS `awb_unit`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `awb_unit` AS SELECT
1 AS `awb_unit_id`,
1 AS `operation` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `balance_nest_tree`
--
DROP TABLE IF EXISTS `balance_nest_tree`;
/*!50001 DROP VIEW IF EXISTS `balance_nest_tree`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `balance_nest_tree` AS SELECT
1 AS `lft`,
1 AS `rgt`,
1 AS `name`,
1 AS `id`,
1 AS `Id_Gasto`,
1 AS `isSelected` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `barcodes`
--
DROP TABLE IF EXISTS `barcodes`;
/*!50001 DROP VIEW IF EXISTS `barcodes`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `barcodes` AS SELECT
1 AS `id`,
1 AS `Id_Article`,
1 AS `code` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `buySource`
--
DROP TABLE IF EXISTS `buySource`;
/*!50001 DROP VIEW IF EXISTS `buySource`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `buySource` AS SELECT
1 AS `Id_Entrada`,
1 AS `isPickedOff`,
1 AS `tarifa0`,
1 AS `kop`,
1 AS `Id_Compra`,
1 AS `tipo_id`,
1 AS `Id_Article`,
1 AS `Medida`,
1 AS `Tallos`,
1 AS `Etiquetas`,
1 AS `Id_Cubo`,
1 AS `Costefijo`,
1 AS `Packing`,
1 AS `Grouping`,
1 AS `Cantidad`,
1 AS `Tarifa2`,
1 AS `Tarifa3`,
1 AS `Punteo`,
1 AS `Caja`,
1 AS `Imprimir`,
1 AS `Article`,
1 AS `Tinta`,
1 AS `id_origen`,
1 AS `PVP`,
1 AS `Id_Accion`,
1 AS `pro`,
1 AS `Min`,
1 AS `Novincular`,
1 AS `Portefijo`,
1 AS `Importe`,
1 AS `Vida`,
1 AS `reference`,
1 AS `Id_Trabajador`,
1 AS `S1`,
1 AS `S2`,
1 AS `S3`,
1 AS `S4`,
1 AS `S5`,
1 AS `S6`,
1 AS `price_fixed`,
1 AS `producer_id`,
1 AS `tag1`,
1 AS `tag2`,
1 AS `tag3`,
1 AS `tag4`,
1 AS `tag5`,
1 AS `tag6`,
1 AS `tag7`,
1 AS `company_name`,
1 AS `weightPacking`,
1 AS `packingOut`,
1 AS `itemOriginalFk`,
1 AS `itemOriginalName`,
1 AS `gramsMax`,
1 AS `minQuantity` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `buy_edi`
--
DROP TABLE IF EXISTS `buy_edi`;
/*!50001 DROP VIEW IF EXISTS `buy_edi`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `buy_edi` AS SELECT
1 AS `id`,
1 AS `barcode`,
1 AS `entry_year`,
1 AS `delivery_number`,
1 AS `fec`,
1 AS `hor`,
1 AS `now`,
1 AS `ptj`,
1 AS `ref`,
1 AS `item`,
1 AS `pac`,
1 AS `qty`,
1 AS `ori`,
1 AS `cat`,
1 AS `agj`,
1 AS `kop`,
1 AS `ptd`,
1 AS `sub`,
1 AS `pro`,
1 AS `pri`,
1 AS `package`,
1 AS `auction`,
1 AS `klo`,
1 AS `k01`,
1 AS `k02`,
1 AS `k03`,
1 AS `k04`,
1 AS `s1`,
1 AS `s2`,
1 AS `s3`,
1 AS `s4`,
1 AS `s5`,
1 AS `s6`,
1 AS `ok`,
1 AS `trolley_id`,
1 AS `putOrderFk`,
1 AS `scanned` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `buy_edi_k012`
--
DROP TABLE IF EXISTS `buy_edi_k012`;
/*!50001 DROP VIEW IF EXISTS `buy_edi_k012`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `buy_edi_k012` AS SELECT
1 AS `buy_edi_k012_id`,
1 AS `description` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `buy_edi_k03`
--
DROP TABLE IF EXISTS `buy_edi_k03`;
/*!50001 DROP VIEW IF EXISTS `buy_edi_k03`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `buy_edi_k03` AS SELECT
1 AS `buy_edi_k03_id`,
1 AS `description` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `buy_edi_k04`
--
DROP TABLE IF EXISTS `buy_edi_k04`;
/*!50001 DROP VIEW IF EXISTS `buy_edi_k04`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `buy_edi_k04` AS SELECT
1 AS `buy_edi_k04_id`,
1 AS `description` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `call_information__`
--
DROP TABLE IF EXISTS `call_information__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `call_information__` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`Descripcio` text NOT NULL,
`Conclusio` tinyint(3) unsigned NOT NULL,
`Id_Cliente` int(11) NOT NULL,
`fecha` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `call_option__`
--
DROP TABLE IF EXISTS `call_option__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `call_option__` (
`id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
`descripcion` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `cdr`
--
DROP TABLE IF EXISTS `cdr`;
/*!50001 DROP VIEW IF EXISTS `cdr`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `cdr` AS SELECT
1 AS `calldate`,
1 AS `clid`,
1 AS `src`,
1 AS `dst`,
1 AS `dcontext`,
1 AS `channel`,
1 AS `dstchannel`,
1 AS `lastapp`,
1 AS `lastdata`,
1 AS `duration`,
1 AS `billsec`,
1 AS `disposition`,
1 AS `amaflags`,
1 AS `accountcode`,
1 AS `uniqueid`,
1 AS `userfield` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `chanel`
--
DROP TABLE IF EXISTS `chanel`;
/*!50001 DROP VIEW IF EXISTS `chanel`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `chanel` AS SELECT
1 AS `chanel_id`,
1 AS `name` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `cl_act`
--
DROP TABLE IF EXISTS `cl_act`;
/*!50001 DROP VIEW IF EXISTS `cl_act`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `cl_act` AS SELECT
1 AS `id`,
1 AS `Id_Movimiento`,
1 AS `cl_main_id`,
1 AS `Id_Trabajador`,
1 AS `cl_sol_id`,
1 AS `greuge` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `cl_cau`
--
DROP TABLE IF EXISTS `cl_cau`;
/*!50001 DROP VIEW IF EXISTS `cl_cau`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `cl_cau` AS SELECT
1 AS `id`,
1 AS `cl_main_id`,
1 AS `cl_res_id`,
1 AS `Id_Trabajador`,
1 AS `cl_mot_id`,
1 AS `cl_con_id`,
1 AS `cl_dev`,
1 AS `cl_sol` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `cl_con`
--
DROP TABLE IF EXISTS `cl_con`;
/*!50001 DROP VIEW IF EXISTS `cl_con`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `cl_con` AS SELECT
1 AS `id`,
1 AS `consecuencia` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `cl_dep__`
--
DROP TABLE IF EXISTS `cl_dep__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cl_dep__` (
`id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
`departamento` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `cl_det`
--
DROP TABLE IF EXISTS `cl_det`;
/*!50001 DROP VIEW IF EXISTS `cl_det`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `cl_det` AS SELECT
1 AS `id`,
1 AS `cl_main_id`,
1 AS `Id_Movimiento`,
1 AS `numero` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `cl_main`
--
DROP TABLE IF EXISTS `cl_main`;
/*!50001 DROP VIEW IF EXISTS `cl_main`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `cl_main` AS SELECT
1 AS `id`,
1 AS `Fecha`,
1 AS `cl_est_id`,
1 AS `notas`,
1 AS `Id_Cliente`,
1 AS `Id_Trabajador`,
1 AS `sensib`,
1 AS `mana`,
1 AS `ticketFk`,
1 AS `odbc_date` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `cl_mot`
--
DROP TABLE IF EXISTS `cl_mot`;
/*!50001 DROP VIEW IF EXISTS `cl_mot`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `cl_mot` AS SELECT
1 AS `id`,
1 AS `motivo` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `cl_pet__`
--
DROP TABLE IF EXISTS `cl_pet__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cl_pet__` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`peticion` varchar(15) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `cl_que__`
--
DROP TABLE IF EXISTS `cl_que__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cl_que__` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`queja` varchar(25) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `cl_res`
--
DROP TABLE IF EXISTS `cl_res`;
/*!50001 DROP VIEW IF EXISTS `cl_res`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `cl_res` AS SELECT
1 AS `id`,
1 AS `responsable`,
1 AS `sensibility` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `cl_sol`
--
DROP TABLE IF EXISTS `cl_sol`;
/*!50001 DROP VIEW IF EXISTS `cl_sol`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `cl_sol` AS SELECT
1 AS `id`,
1 AS `solucion`,
1 AS `addressFk` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `commission__`
--
DROP TABLE IF EXISTS `commission__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `commission__` (
`commisision_id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
`percentage` tinyint(3) unsigned NOT NULL,
`value` float unsigned NOT NULL,
PRIMARY KEY (`commisision_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `config__`
--
DROP TABLE IF EXISTS `config__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `config__` (
`id` int(11) NOT NULL,
`generic_item` int(11) NOT NULL COMMENT 'Id del artículo genérico',
`edi_entry` int(11) NOT NULL COMMENT 'Entrada usada para los EKTs',
`lastMana` int(11) NOT NULL DEFAULT 0,
`lastNicho` varchar(10) DEFAULT NULL,
`lastReserve` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `config_host`
--
DROP TABLE IF EXISTS `config_host`;
/*!50001 DROP VIEW IF EXISTS `config_host`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `config_host` AS SELECT
1 AS `config_host_id`,
1 AS `warehouse`,
1 AS `empresaId`,
1 AS `caja`,
1 AS `Id_Impresora`,
1 AS `route_days_before`,
1 AS `route_days_after` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `config_host_forms__`
--
DROP TABLE IF EXISTS `config_host_forms__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `config_host_forms__` (
`config_host_id` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`formname` varchar(56) NOT NULL,
`x` int(8) NOT NULL,
`y` int(8) NOT NULL,
`h` int(8) NOT NULL,
`l` int(8) NOT NULL,
`odbc_date` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`config_host_id`,`formname`),
CONSTRAINT `config_host_forms_FK` FOREIGN KEY (`config_host_id`) REFERENCES `vn`.`host` (`code`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `consignatarios_observation`
--
DROP TABLE IF EXISTS `consignatarios_observation`;
/*!50001 DROP VIEW IF EXISTS `consignatarios_observation`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `consignatarios_observation` AS SELECT
1 AS `consignatarios_observation_id`,
1 AS `Id_Consigna`,
1 AS `observation_type_id`,
1 AS `text` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `container__`
--
DROP TABLE IF EXISTS `container__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `container__` (
`container_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`Continente` varchar(10) DEFAULT NULL,
PRIMARY KEY (`container_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `cooler_path__`
--
DROP TABLE IF EXISTS `cooler_path__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cooler_path__` (
`cooler_path_id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(45) DEFAULT NULL,
PRIMARY KEY (`cooler_path_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `cp__`
--
DROP TABLE IF EXISTS `cp__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cp__` (
`cp_id` int(11) NOT NULL AUTO_INCREMENT,
`cpd` int(11) NOT NULL,
`cph` int(11) NOT NULL,
`zone_id` smallint(6) DEFAULT NULL,
`town` varchar(45) NOT NULL,
PRIMARY KEY (`cp_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `credit`
--
DROP TABLE IF EXISTS `credit`;
/*!50001 DROP VIEW IF EXISTS `credit`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `credit` AS SELECT
1 AS `id`,
1 AS `Id_Cliente`,
1 AS `Id_Trabajador`,
1 AS `amount`,
1 AS `odbc_date` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `credit_card__`
--
DROP TABLE IF EXISTS `credit_card__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `credit_card__` (
`credit_card_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`Id_Cliente` int(10) NOT NULL,
`number` varchar(20) NOT NULL,
`expiration_month` tinyint(2) unsigned zerofill NOT NULL,
`expiration_year` tinyint(2) unsigned zerofill NOT NULL,
`priority` tinyint(3) unsigned NOT NULL DEFAULT 1,
`obs` varchar(45) DEFAULT NULL,
PRIMARY KEY (`credit_card_id`),
KEY `Id_Cliente` (`Id_Cliente`),
CONSTRAINT `credit_card___ibfk_1` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `cyc__`
--
DROP TABLE IF EXISTS `cyc__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cyc__` (
`Id_Cliente` int(11) NOT NULL,
`Riesgo` double DEFAULT NULL,
`Fecha` timestamp NOT NULL DEFAULT current_timestamp(),
`cyc_id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`cyc_id`),
KEY `Cliente` (`Id_Cliente`),
CONSTRAINT `Cliente` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `cyc_declaration__`
--
DROP TABLE IF EXISTS `cyc_declaration__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cyc_declaration__` (
`factura_id` int(10) unsigned NOT NULL,
`Riesgo` double DEFAULT NULL,
`Fecha` date NOT NULL,
`Vencimiento` int(10) NOT NULL DEFAULT 0,
PRIMARY KEY (`factura_id`),
CONSTRAINT `Factura` FOREIGN KEY (`factura_id`) REFERENCES `vn`.`invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `definitivo`
--
DROP TABLE IF EXISTS `definitivo`;
/*!50001 DROP VIEW IF EXISTS `definitivo`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `definitivo` AS SELECT
1 AS `definitivo_id`,
1 AS `empresa_id`,
1 AS `desde`,
1 AS `hasta`,
1 AS `fecha` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `dock__`
--
DROP TABLE IF EXISTS `dock__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dock__` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(5) NOT NULL,
`xPos` int(11) DEFAULT NULL,
`yPos` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code_UNIQUE` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-03-05';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `duaDismissed__`
--
DROP TABLE IF EXISTS `duaDismissed__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `duaDismissed__` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ticketFk` varchar(45) NOT NULL,
PRIMARY KEY (`id`,`ticketFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `edi_article`
--
DROP TABLE IF EXISTS `edi_article`;
/*!50001 DROP VIEW IF EXISTS `edi_article`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `edi_article` AS SELECT
1 AS `id`,
1 AS `product_name`,
1 AS `name`,
1 AS `plant_id`,
1 AS `group_id`,
1 AS `entry_date`,
1 AS `expiry_date`,
1 AS `change_date_time` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `edi_bucket`
--
DROP TABLE IF EXISTS `edi_bucket`;
/*!50001 DROP VIEW IF EXISTS `edi_bucket`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `edi_bucket` AS SELECT
1 AS `bucket_id`,
1 AS `bucket_type_id`,
1 AS `description`,
1 AS `x_size`,
1 AS `y_size`,
1 AS `z_size`,
1 AS `entry_date`,
1 AS `expiry_date`,
1 AS `change_date_time` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `edi_bucket_type`
--
DROP TABLE IF EXISTS `edi_bucket_type`;
/*!50001 DROP VIEW IF EXISTS `edi_bucket_type`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `edi_bucket_type` AS SELECT
1 AS `bucket_type_id`,
1 AS `description`,
1 AS `entry_date`,
1 AS `expiry_date`,
1 AS `change_date_time` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `edi_specie`
--
DROP TABLE IF EXISTS `edi_specie`;
/*!50001 DROP VIEW IF EXISTS `edi_specie`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `edi_specie` AS SELECT
1 AS `specie_id`,
1 AS `genus_id`,
1 AS `latin_species_name`,
1 AS `entry_date`,
1 AS `expiry_date`,
1 AS `change_date_time` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `edi_supplier`
--
DROP TABLE IF EXISTS `edi_supplier`;
/*!50001 DROP VIEW IF EXISTS `edi_supplier`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `edi_supplier` AS SELECT
1 AS `supplier_id`,
1 AS `company_name` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `edi_testigos__`
--
DROP TABLE IF EXISTS `edi_testigos__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `edi_testigos__` (
`id` smallint(6) NOT NULL AUTO_INCREMENT,
`table` varchar(25) NOT NULL,
`field` varchar(32) NOT NULL,
`testigo` varchar(5) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `emp_day_pay__`
--
DROP TABLE IF EXISTS `emp_day_pay__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `emp_day_pay__` (
`id` smallint(5) unsigned NOT NULL,
`emp_day_pay` tinyint(3) unsigned NOT NULL,
PRIMARY KEY (`id`,`emp_day_pay`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `empresa`
--
DROP TABLE IF EXISTS `empresa`;
/*!50001 DROP VIEW IF EXISTS `empresa`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `empresa` AS SELECT
1 AS `id`,
1 AS `abbreviation`,
1 AS `Id_Proveedores_account`,
1 AS `gerente_id`,
1 AS `phytosanitary`,
1 AS `CodigoEmpresa`,
1 AS `empresa_grupo`,
1 AS `morosidad`,
1 AS `baja`,
1 AS `registro`,
1 AS `alta`,
1 AS `logo`,
1 AS `oficial`,
1 AS `cyc`,
1 AS `rgb`,
1 AS `mail`,
1 AS `cuno`,
1 AS `ODBC_DATE`,
1 AS `Id_Cliente` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `empresa_grupo`
--
DROP TABLE IF EXISTS `empresa_grupo`;
/*!50001 DROP VIEW IF EXISTS `empresa_grupo`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `empresa_grupo` AS SELECT
1 AS `empresa_grupo_id`,
1 AS `grupo` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `entrySource`
--
DROP TABLE IF EXISTS `entrySource`;
/*!50001 DROP VIEW IF EXISTS `entrySource`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `entrySource` AS SELECT
1 AS `gestdoc_id`,
1 AS `Id_Entrada`,
1 AS `invoiceNumber`,
1 AS `reference`,
1 AS `Inventario`,
1 AS `Confirmada`,
1 AS `Pedida`,
1 AS `Redada`,
1 AS `notas`,
1 AS `Id_Proveedor`,
1 AS `shipment`,
1 AS `landing`,
1 AS `wh_in`,
1 AS `wh_out`,
1 AS `Agencia`,
1 AS `comision`,
1 AS `warehouse_id`,
1 AS `warehouse_id_out`,
1 AS `anotadoencaja`,
1 AS `invoiceInFk`,
1 AS `empresa_id`,
1 AS `Id_Moneda`,
1 AS `TravelFk`,
1 AS `sub`,
1 AS `kop`,
1 AS `pro`,
1 AS `invoiceAmount`,
1 AS `buyerCode`,
1 AS `typeFk`,
1 AS `observationWorkerCode` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `expeditions_deleted__`
--
DROP TABLE IF EXISTS `expeditions_deleted__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expeditions_deleted__` (
`expeditions_id` int(11) NOT NULL AUTO_INCREMENT,
`agency_id` int(11) NOT NULL,
`ticket_id` int(10) NOT NULL,
`EsBulto` int(11) DEFAULT 1,
`odbc_date` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`reembolso` bit(1) DEFAULT b'0',
`recogida` bit(1) DEFAULT b'0',
`Id_Article` int(11) DEFAULT NULL,
`counter` smallint(5) unsigned NOT NULL,
`checked` tinyint(4) NOT NULL DEFAULT 0,
`completed` tinyint(4) DEFAULT 0,
`expedicion` varchar(45) DEFAULT NULL,
`Id_Trabajador` int(11) DEFAULT NULL,
PRIMARY KEY (`expeditions_id`),
KEY `index1` (`agency_id`),
KEY `index2` (`EsBulto`),
KEY `index3` (`odbc_date`),
KEY `index4` (`ticket_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `expeditions_pictures__`
--
DROP TABLE IF EXISTS `expeditions_pictures__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expeditions_pictures__` (
`Id_Article` int(11) NOT NULL,
`NoImprimirEtiqueta` bit(1) DEFAULT b'0',
PRIMARY KEY (`Id_Article`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `filtros__`
--
DROP TABLE IF EXISTS `filtros__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `filtros__` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`sql` varchar(255) NOT NULL,
`Estanteria` tinyint(1) DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-21;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `financialProductType`
--
DROP TABLE IF EXISTS `financialProductType`;
/*!50001 DROP VIEW IF EXISTS `financialProductType`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `financialProductType` AS SELECT
1 AS `id`,
1 AS `description`,
1 AS `isAcumulattor` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `flight`
--
DROP TABLE IF EXISTS `flight`;
/*!50001 DROP VIEW IF EXISTS `flight`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `flight` AS SELECT
1 AS `flight_id`,
1 AS `duration`,
1 AS `route`,
1 AS `days`,
1 AS `airline_id`,
1 AS `airport_out`,
1 AS `airport_in` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `form_query__`
--
DROP TABLE IF EXISTS `form_query__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `form_query__` (
`form_query_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`query` varchar(50) NOT NULL,
`response1` varchar(10) NOT NULL,
`response2` varchar(10) NOT NULL,
`type_id` enum('gest_doc') NOT NULL,
PRIMARY KEY (`form_query_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-21;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `gastos_resumen`
--
DROP TABLE IF EXISTS `gastos_resumen`;
/*!50001 DROP VIEW IF EXISTS `gastos_resumen`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `gastos_resumen` AS SELECT
1 AS `id`,
1 AS `Id_Gasto`,
1 AS `year`,
1 AS `month`,
1 AS `importe`,
1 AS `empresa_id` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `guillen__`
--
DROP TABLE IF EXISTS `guillen__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `guillen__` (
`bulto` tinyint(3) unsigned NOT NULL,
`1` float unsigned NOT NULL,
`2` float unsigned NOT NULL,
`re_exp` float unsigned NOT NULL,
PRIMARY KEY (`bulto`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `guillen_carry__`
--
DROP TABLE IF EXISTS `guillen_carry__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `guillen_carry__` (
`carry` tinyint(3) unsigned NOT NULL,
`1` float unsigned NOT NULL,
`2` float unsigned NOT NULL,
`re_exp` float unsigned NOT NULL,
PRIMARY KEY (`carry`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `integra2`
--
DROP TABLE IF EXISTS `integra2`;
/*!50001 DROP VIEW IF EXISTS `integra2`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `integra2` AS SELECT
1 AS `postal_code`,
1 AS `frequency`,
1 AS `warehouse_id` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `integra2_escala__`
--
DROP TABLE IF EXISTS `integra2_escala__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `integra2_escala__` (
`province_id` smallint(6) unsigned NOT NULL,
`warehouse_id` smallint(6) unsigned NOT NULL,
PRIMARY KEY (`province_id`,`warehouse_id`),
KEY `warehouse_escala_idx` (`warehouse_id`),
CONSTRAINT `province_escala` FOREIGN KEY (`province_id`) REFERENCES `vn`.`province` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `warehouse_escala` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `integra2_province`
--
DROP TABLE IF EXISTS `integra2_province`;
/*!50001 DROP VIEW IF EXISTS `integra2_province`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `integra2_province` AS SELECT
1 AS `province_id`,
1 AS `franquicia` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `invoice_observation__`
--
DROP TABLE IF EXISTS `invoice_observation__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoice_observation__` (
`invoice_observation_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`desde` date NOT NULL,
`hasta` date NOT NULL,
`serie` varchar(1) NOT NULL DEFAULT '0',
`empresa_id` smallint(5) unsigned NOT NULL DEFAULT 0,
`text` text NOT NULL,
PRIMARY KEY (`invoice_observation_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `jerarquia__`
--
DROP TABLE IF EXISTS `jerarquia__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `jerarquia__` (
`worker_id` int(10) unsigned NOT NULL,
`boss_id` int(10) unsigned NOT NULL,
`vinculado` tinyint(3) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`worker_id`,`boss_id`),
KEY `worker_trabajador` (`worker_id`),
KEY `jerarquiaBossFk_idx` (`boss_id`),
CONSTRAINT `jerarquiaBossFk` FOREIGN KEY (`boss_id`) REFERENCES `account`.`account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `jerarquiaWorkerFk` FOREIGN KEY (`worker_id`) REFERENCES `account`.`account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #7258 @deprecated 2023-12-13';
/*!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) NOT NULL,
`name` varchar(20) NOT NULL,
`active` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `link__`
--
DROP TABLE IF EXISTS `link__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `link__` (
`Id_Cliente` int(11) NOT NULL,
`Id_Proveedor` int(11) NOT NULL,
PRIMARY KEY (`Id_Cliente`,`Id_Proveedor`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `mail`
--
DROP TABLE IF EXISTS `mail`;
/*!50001 DROP VIEW IF EXISTS `mail`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `mail` AS SELECT
1 AS `id`,
1 AS `senderFk`,
1 AS `recipientFk`,
1 AS `to`,
1 AS `reply_to`,
1 AS `subject`,
1 AS `text`,
1 AS `plainTextBody`,
1 AS `path`,
1 AS `DATE_ODBC`,
1 AS `sent`,
1 AS `error` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `mandato`
--
DROP TABLE IF EXISTS `mandato`;
/*!50001 DROP VIEW IF EXISTS `mandato`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `mandato` AS SELECT
1 AS `id`,
1 AS `Id_Cliente`,
1 AS `empresa_id`,
1 AS `Id_mandato`,
1 AS `FAlta`,
1 AS `Fbaja`,
1 AS `idmandato_tipo` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `mandato_tipo`
--
DROP TABLE IF EXISTS `mandato_tipo`;
/*!50001 DROP VIEW IF EXISTS `mandato_tipo`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `mandato_tipo` AS SELECT
1 AS `idmandato_tipo`,
1 AS `Nombre` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `nichos__`
--
DROP TABLE IF EXISTS `nichos__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `nichos__` (
`id` varchar(5) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `pago`
--
DROP TABLE IF EXISTS `pago`;
/*!50001 DROP VIEW IF EXISTS `pago`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `pago` AS SELECT
1 AS `id`,
1 AS `fecha`,
1 AS `dueDated`,
1 AS `id_proveedor`,
1 AS `importe`,
1 AS `id_moneda`,
1 AS `divisa`,
1 AS `id_banco`,
1 AS `pay_met_id`,
1 AS `empresa_id`,
1 AS `conciliado`,
1 AS `g_bancarios`,
1 AS `concepte`,
1 AS `odbc_date` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `pago_sdc`
--
DROP TABLE IF EXISTS `pago_sdc`;
/*!50001 DROP VIEW IF EXISTS `pago_sdc`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `pago_sdc` AS SELECT
1 AS `pago_sdc_id`,
1 AS `importe`,
1 AS `fecha`,
1 AS `vencimiento`,
1 AS `entity_id`,
1 AS `ref`,
1 AS `rate`,
1 AS `empresa_id`,
1 AS `financialProductTypefk`,
1 AS `upperBarrier`,
1 AS `lowerBarrier`,
1 AS `strike` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `pay_dem`
--
DROP TABLE IF EXISTS `pay_dem`;
/*!50001 DROP VIEW IF EXISTS `pay_dem`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `pay_dem` AS SELECT
1 AS `id`,
1 AS `pay_dem` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `pay_dem_det`
--
DROP TABLE IF EXISTS `pay_dem_det`;
/*!50001 DROP VIEW IF EXISTS `pay_dem_det`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `pay_dem_det` AS SELECT
1 AS `id`,
1 AS `detalle` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `pay_met`
--
DROP TABLE IF EXISTS `pay_met`;
/*!50001 DROP VIEW IF EXISTS `pay_met`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `pay_met` AS SELECT
1 AS `id`,
1 AS `name`,
1 AS `graceDays`,
1 AS `deudaviva`,
1 AS `solucion`,
1 AS `isNotified` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `payroll_basess__`
--
DROP TABLE IF EXISTS `payroll_basess__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payroll_basess__` (
`id_payroll_Basess` int(11) NOT NULL AUTO_INCREMENT,
`empresa_id` int(10) NOT NULL,
`id_tipobasess` int(11) NOT NULL,
`valor` double NOT NULL,
`fechadesde` date NOT NULL,
`fechahasta` date DEFAULT NULL,
`contratotemporal` tinyint(1) DEFAULT 0,
PRIMARY KEY (`id_payroll_Basess`),
KEY `payroll_basess_1_idx` (`id_tipobasess`),
KEY `payroll_basess_2_idx` (`empresa_id`),
CONSTRAINT `payroll_basess_1` FOREIGN KEY (`id_tipobasess`) REFERENCES `payroll_tipobasess__` (`id_payroll_tipobasess`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `payroll_basess_2` FOREIGN KEY (`empresa_id`) REFERENCES `vn`.`payrollWorkCenter` (`empresa_id__`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `payroll_bonificaciones__`
--
DROP TABLE IF EXISTS `payroll_bonificaciones__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payroll_bonificaciones__` (
`codtrabajador` int(11) NOT NULL,
`codempresa` int(11) NOT NULL,
`Fecha` date NOT NULL,
`bonificacionSS` double NOT NULL,
PRIMARY KEY (`codtrabajador`,`codempresa`,`Fecha`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `payroll_categorias`
--
DROP TABLE IF EXISTS `payroll_categorias`;
/*!50001 DROP VIEW IF EXISTS `payroll_categorias`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `payroll_categorias` AS SELECT
1 AS `codcategoria`,
1 AS `Tarifa`,
1 AS `descripcion` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `payroll_centros`
--
DROP TABLE IF EXISTS `payroll_centros`;
/*!50001 DROP VIEW IF EXISTS `payroll_centros`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `payroll_centros` AS SELECT
1 AS `cod_centro`,
1 AS `codempresa` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `payroll_conceptos`
--
DROP TABLE IF EXISTS `payroll_conceptos`;
/*!50001 DROP VIEW IF EXISTS `payroll_conceptos`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `payroll_conceptos` AS SELECT
1 AS `conceptoid`,
1 AS `concepto`,
1 AS `isSalaryAgreed`,
1 AS `isVariable`,
1 AS `isException` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `payroll_datos__`
--
DROP TABLE IF EXISTS `payroll_datos__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payroll_datos__` (
`codtrabajador` int(11) NOT NULL,
`codempresa` int(10) NOT NULL,
`Fecha` date NOT NULL,
`conceptoid` int(11) NOT NULL,
`orden` tinyint(4) DEFAULT NULL,
`dias` smallint(6) DEFAULT NULL,
`Importe` decimal(8,2) NOT NULL,
`DH` tinyint(4) DEFAULT NULL,
`T_Paga` tinyint(4) NOT NULL,
`TributaIRPF` tinyint(4) NOT NULL,
PRIMARY KEY (`codtrabajador`,`codempresa`,`conceptoid`,`Fecha`),
KEY `fgkey_payrolldatos_1_idx` (`conceptoid`),
CONSTRAINT `fgkey_payrolldatos_1` FOREIGN KEY (`conceptoid`) REFERENCES `vn`.`payrollComponent` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `payroll_embargos__`
--
DROP TABLE IF EXISTS `payroll_embargos__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payroll_embargos__` (
`codtrabajador` int(11) NOT NULL,
`codempresa` int(10) NOT NULL,
`conceptoid` int(11) NOT NULL,
`Fecha` date NOT NULL,
`pagado` double NOT NULL,
`pendiente` double DEFAULT NULL,
`total` double NOT NULL,
PRIMARY KEY (`codtrabajador`,`codempresa`,`Fecha`,`conceptoid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `payroll_employee`
--
DROP TABLE IF EXISTS `payroll_employee`;
/*!50001 DROP VIEW IF EXISTS `payroll_employee`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `payroll_employee` AS SELECT
1 AS `CodTrabajador`,
1 AS `codempresa`,
1 AS `workerFk` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `payroll_tipobasess__`
--
DROP TABLE IF EXISTS `payroll_tipobasess__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payroll_tipobasess__` (
`id_payroll_tipobasess` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id_payroll_tipobasess`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `payrroll_apEmpresarial__`
--
DROP TABLE IF EXISTS `payrroll_apEmpresarial__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `payrroll_apEmpresarial__` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`codTrabajador` int(11) NOT NULL,
`Fecha` date NOT NULL,
`CosteEmpresaAT` decimal(8,2) NOT NULL,
`costeEmpresaCC` decimal(8,2) NOT NULL,
`costeEmpresaDesempleo` decimal(8,2) NOT NULL,
`costeEmpresaFP` decimal(8,2) NOT NULL,
`costeEmpresaFogasa` decimal(8,2) NOT NULL,
`costeEmpresaExtra` decimal(8,2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `plantpassport`
--
DROP TABLE IF EXISTS `plantpassport`;
/*!50001 DROP VIEW IF EXISTS `plantpassport`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `plantpassport` AS SELECT
1 AS `producer_id`,
1 AS `plantpassport_authority_id`,
1 AS `number`,
1 AS `isRequested` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `plantpassport_authority`
--
DROP TABLE IF EXISTS `plantpassport_authority`;
/*!50001 DROP VIEW IF EXISTS `plantpassport_authority`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `plantpassport_authority` AS SELECT
1 AS `plantpassport_authority_id`,
1 AS `denomination`,
1 AS `Paises_Id` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `preparation_exception__`
--
DROP TABLE IF EXISTS `preparation_exception__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `preparation_exception__` (
`exception_day` date NOT NULL COMMENT 'preparation day',
`warehouse_id` smallint(6) unsigned DEFAULT NULL,
`percentage` tinyint(2) NOT NULL DEFAULT 0,
UNIQUE KEY `exception_day_UNIQUE` (`exception_day`),
UNIQUE KEY `warehouse_id_UNIQUE` (`warehouse_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `price_fixed`
--
DROP TABLE IF EXISTS `price_fixed`;
/*!50001 DROP VIEW IF EXISTS `price_fixed`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `price_fixed` AS SELECT
1 AS `item_id`,
1 AS `rate_0`,
1 AS `rate_1`,
1 AS `rate_2`,
1 AS `rate_3`,
1 AS `date_start`,
1 AS `date_end`,
1 AS `bonus`,
1 AS `warehouse_id`,
1 AS `odbc_date`,
1 AS `price_fixed_id`,
1 AS `grouping`,
1 AS `Packing`,
1 AS `caja` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `producer`
--
DROP TABLE IF EXISTS `producer`;
/*!50001 DROP VIEW IF EXISTS `producer`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `producer` AS SELECT
1 AS `producer_id`,
1 AS `name`,
1 AS `visible` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `proveedores_clientes`
--
DROP TABLE IF EXISTS `proveedores_clientes`;
/*!50001 DROP VIEW IF EXISTS `proveedores_clientes`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `proveedores_clientes` AS SELECT
1 AS `Id_Proveedor`,
1 AS `Proveedor`,
1 AS `Id_Cliente`,
1 AS `Cliente` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `province`
--
DROP TABLE IF EXISTS `province`;
/*!50001 DROP VIEW IF EXISTS `province`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `province` AS SELECT
1 AS `province_id`,
1 AS `name`,
1 AS `Paises_Id`,
1 AS `warehouse_id`,
1 AS `zone`,
1 AS `geoFk` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `rec_translator__`
--
DROP TABLE IF EXISTS `rec_translator__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `rec_translator__` (
`Id_Article` int(11) NOT NULL,
`denominacion` varchar(85) NOT NULL,
PRIMARY KEY (`Id_Article`,`denominacion`),
KEY `id_article_rec_idx` (`Id_Article`),
CONSTRAINT `id_article_rec` FOREIGN KEY (`Id_Article`) REFERENCES `vn`.`item` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `recibida`
--
DROP TABLE IF EXISTS `recibida`;
/*!50001 DROP VIEW IF EXISTS `recibida`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `recibida` AS SELECT
1 AS `id`,
1 AS `num_recibida`,
1 AS `serie`,
1 AS `proveedor_id`,
1 AS `fecha`,
1 AS `sref`,
1 AS `contabilizada`,
1 AS `moneda_id`,
1 AS `MYSQL_TIME`,
1 AS `empresa_id`,
1 AS `gestdoc_id`,
1 AS `dateBooking`,
1 AS `dateOperation`,
1 AS `siiTypeInvoiceInFk`,
1 AS `cplusRectificationTypeFk`,
1 AS `cplusSubjectOpFk`,
1 AS `cplusTaxBreakFk`,
1 AS `siiTrascendencyInvoiceInFk`,
1 AS `bookEntried`,
1 AS `isVatDeductible`,
1 AS `withholdingSageFk`,
1 AS `expenseFkDeductible` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `recibida_agricola__`
--
DROP TABLE IF EXISTS `recibida_agricola__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `recibida_agricola__` (
`recibida_id` mediumint(8) unsigned NOT NULL,
`num` smallint(5) unsigned NOT NULL,
PRIMARY KEY (`recibida_id`),
CONSTRAINT `recibida_agricola___ibfk_1` FOREIGN KEY (`recibida_id`) REFERENCES `vn`.`invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `recibida_intrastat`
--
DROP TABLE IF EXISTS `recibida_intrastat`;
/*!50001 DROP VIEW IF EXISTS `recibida_intrastat`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `recibida_intrastat` AS SELECT
1 AS `recibida_id`,
1 AS `Codintrastat`,
1 AS `importe` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `recibida_iva`
--
DROP TABLE IF EXISTS `recibida_iva`;
/*!50001 DROP VIEW IF EXISTS `recibida_iva`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `recibida_iva` AS SELECT
1 AS `id`,
1 AS `recibida_id`,
1 AS `iva_id`,
1 AS `bi`,
1 AS `gastos_id`,
1 AS `divisa`,
1 AS `taxTypeSageFk`,
1 AS `transactionTypeSageFk`,
1 AS `MYSQL_TIME` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `recibida_vencimiento`
--
DROP TABLE IF EXISTS `recibida_vencimiento`;
/*!50001 DROP VIEW IF EXISTS `recibida_vencimiento`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `recibida_vencimiento` AS SELECT
1 AS `id`,
1 AS `recibida_id`,
1 AS `fecha`,
1 AS `banco_id`,
1 AS `cantidad`,
1 AS `divisa`,
1 AS `stamp` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `recovery`
--
DROP TABLE IF EXISTS `recovery`;
/*!50001 DROP VIEW IF EXISTS `recovery`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `recovery` AS SELECT
1 AS `recovery_id`,
1 AS `Id_Cliente`,
1 AS `dstart`,
1 AS `dend`,
1 AS `amount`,
1 AS `period` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `reference_rate`
--
DROP TABLE IF EXISTS `reference_rate`;
/*!50001 DROP VIEW IF EXISTS `reference_rate`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `reference_rate` AS SELECT
1 AS `moneda_id`,
1 AS `date`,
1 AS `rate` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `reinos`
--
DROP TABLE IF EXISTS `reinos`;
/*!50001 DROP VIEW IF EXISTS `reinos`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `reinos` AS SELECT
1 AS `id`,
1 AS `reino`,
1 AS `display`,
1 AS `color`,
1 AS `icon`,
1 AS `mercancia`,
1 AS `orden`,
1 AS `efimero` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `rounding__`
--
DROP TABLE IF EXISTS `rounding__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `rounding__` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`amount` double NOT NULL DEFAULT 0,
`price` double DEFAULT 0,
`discount` double NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `route__`
--
DROP TABLE IF EXISTS `route__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `route__` (
`agency_id` smallint(5) unsigned NOT NULL,
`week_day` tinyint(3) unsigned NOT NULL COMMENT 'weekday de access el domingo = 1, sabado = 7. Intentar cambiar al de Mysql Lunes = 0',
PRIMARY KEY (`agency_id`,`week_day`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `scanTree__`
--
DROP TABLE IF EXISTS `scanTree__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `scanTree__` (
`id` int(11) NOT NULL DEFAULT 0,
`name` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`lft` int(11) NOT NULL,
`rgt` int(11) NOT NULL,
`depth` bigint(22) NOT NULL DEFAULT 0,
`sons` int(11) DEFAULT 0,
`lastScanned` datetime DEFAULT NULL,
`routeCount` int(11) DEFAULT NULL,
`minRoute` int(11) DEFAULT NULL,
`maxRoute` int(11) DEFAULT NULL,
`scanned` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `lft_rgt_depth` (`lft`,`rgt`,`depth`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `scan__`
--
DROP TABLE IF EXISTS `scan__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `scan__` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`lft` int(11) NOT NULL,
`rgt` int(11) NOT NULL,
`name` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`odbc_date` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `scan_line__`
--
DROP TABLE IF EXISTS `scan_line__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `scan_line__` (
`scan_line_id` int(11) NOT NULL AUTO_INCREMENT,
`scan_id` int(11) NOT NULL,
`code` varchar(45) NOT NULL,
`odbc_date` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`scan_line_id`),
KEY `id_scan_id_idx` (`scan_id`),
CONSTRAINT `id_scan_id` FOREIGN KEY (`scan_id`) REFERENCES `scan__` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `sort_merge_results_ernesto__`
--
DROP TABLE IF EXISTS `sort_merge_results_ernesto__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sort_merge_results_ernesto__` (
`hora` datetime NOT NULL,
`uptime` int(11) DEFAULT NULL,
`log_output` varchar(5) DEFAULT NULL,
`uptime_since_flush` int(11) DEFAULT NULL,
`smp_old` int(11) DEFAULT NULL,
`smp_new` int(11) DEFAULT NULL,
`smp` int(11) DEFAULT NULL,
`smp_hour` int(11) DEFAULT NULL,
`connections` int(11) DEFAULT NULL,
`Threads_created` int(11) DEFAULT NULL,
`Threads_cached` int(11) DEFAULT NULL,
`Thread_cache_size` int(11) DEFAULT NULL,
`comment` varchar(255) DEFAULT NULL,
`TABLE_OPEN_CACHE_OVERFLOWS` int(11) DEFAULT NULL,
`TABLE_OPEN_CACHE_MISSES` int(11) DEFAULT NULL,
`TABLE_OPEN_CACHE_HITS` int(11) DEFAULT NULL,
`table_open_cache` int(11) DEFAULT NULL,
`table_open_cache_instances` int(11) DEFAULT NULL,
`open_tables` int(11) DEFAULT NULL,
`opened_tables` int(11) DEFAULT NULL,
`Innodb_os_log_written` double DEFAULT NULL,
`table_definition_cache` int(11) DEFAULT NULL,
`Open_table_definitions` int(11) DEFAULT NULL,
`sort_buffer_size` int(11) DEFAULT NULL,
`join_buffer_size` int(11) DEFAULT NULL,
`read_rnd_buffer_size` int(11) DEFAULT NULL,
`tmp_table_size` int(11) DEFAULT NULL,
`max_heap_table_size` int(11) DEFAULT NULL,
`created_tmp_disk_tables` int(11) DEFAULT NULL,
`created_tmp_tables` int(11) DEFAULT NULL,
`Created_tmp_files` int(11) DEFAULT NULL,
`OpenTablesxUptimeDivOpened` float DEFAULT NULL,
`innodb_open_files` int(11) DEFAULT NULL,
`Innodb_num_open_files` int(11) DEFAULT NULL,
`open_files_limit` int(11) DEFAULT NULL,
`query_cache_size` int(11) DEFAULT NULL,
`query_cache_type` varchar(3) DEFAULT NULL,
`trx_rseg_history_len` int(11) DEFAULT NULL,
`Qcache_hits` int(11) DEFAULT NULL,
`Qcache_inserts` int(11) DEFAULT NULL,
`Qcache_not_cached` int(11) DEFAULT NULL,
PRIMARY KEY (`hora`),
UNIQUE KEY `hora_UNIQUE` (`hora`),
KEY `uptime` (`uptime`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `state`
--
DROP TABLE IF EXISTS `state`;
/*!50001 DROP VIEW IF EXISTS `state`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `state` AS SELECT
1 AS `id`,
1 AS `name`,
1 AS `order`,
1 AS `alert_level`,
1 AS `code`,
1 AS `sectorProdPriority`,
1 AS `nextStateFk`,
1 AS `isPreviousPreparable`,
1 AS `isPicked` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `tag`
--
DROP TABLE IF EXISTS `tag`;
/*!50001 DROP VIEW IF EXISTS `tag`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `tag` AS SELECT
1 AS `id`,
1 AS `name`,
1 AS `isFree`,
1 AS `isQuantitatif`,
1 AS `sourceTable`,
1 AS `unit` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `tarifa_componentes`
--
DROP TABLE IF EXISTS `tarifa_componentes`;
/*!50001 DROP VIEW IF EXISTS `tarifa_componentes`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `tarifa_componentes` AS SELECT
1 AS `Id_Componente`,
1 AS `Componente`,
1 AS `tarifa_componentes_series_id`,
1 AS `tarifa_class`,
1 AS `tax`,
1 AS `is_renewable` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `tarifa_componentes_series`
--
DROP TABLE IF EXISTS `tarifa_componentes_series`;
/*!50001 DROP VIEW IF EXISTS `tarifa_componentes_series`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `tarifa_componentes_series` AS SELECT
1 AS `tarifa_componentes_series_id`,
1 AS `Serie`,
1 AS `base` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `tblContadores`
--
DROP TABLE IF EXISTS `tblContadores`;
/*!50001 DROP VIEW IF EXISTS `tblContadores`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `tblContadores` AS SELECT
1 AS `id`,
1 AS `ochoa`,
1 AS `nfactura`,
1 AS `FechaInventario`,
1 AS `HistoricoArticulo`,
1 AS `week_goal`,
1 AS `Rutafotos`,
1 AS `numCaja`,
1 AS `CodigoRojo`,
1 AS `Tablet_Hora`,
1 AS `t0`,
1 AS `t1`,
1 AS `t2`,
1 AS `t3`,
1 AS `cc`,
1 AS `palet`,
1 AS `campaign`,
1 AS `campaign_life`,
1 AS `truck_days`,
1 AS `tasa_transporte`,
1 AS `escaner_path`,
1 AS `turnoimpreso`,
1 AS `truck_length`,
1 AS `fuel_consumption`,
1 AS `petrol`,
1 AS `maintenance`,
1 AS `hour_price`,
1 AS `meter_price`,
1 AS `km_price`,
1 AS `route_option`,
1 AS `dbproduccion`,
1 AS `mdbServer`,
1 AS `fakeEmail`,
1 AS `defaultersMaxAmount`,
1 AS `ASIEN` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `tblIVA__`
--
DROP TABLE IF EXISTS `tblIVA__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tblIVA__` (
`tipoiva` varchar(50) NOT NULL,
`iva` smallint(6) NOT NULL DEFAULT 0,
`cuenta` double DEFAULT 0,
`cuentaRE` double DEFAULT 0,
`cuentaivaRE` double DEFAULT 0,
`REQ` double DEFAULT 0,
PRIMARY KEY (`tipoiva`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `template_bionic_component__`
--
DROP TABLE IF EXISTS `template_bionic_component__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `template_bionic_component__` (
`warehouse_id` smallint(5) unsigned NOT NULL,
`item_id` int(11) NOT NULL,
`component_id` int(10) unsigned NOT NULL,
`cost` decimal(10,4) NOT NULL,
UNIQUE KEY `item_warehouse_component` (`item_id`,`warehouse_id`,`component_id`) USING HASH,
KEY `item_warehouse` (`item_id`,`warehouse_id`) USING BTREE
) ENGINE=MEMORY DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `template_bionic_lot__`
--
DROP TABLE IF EXISTS `template_bionic_lot__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `template_bionic_lot__` (
`warehouse_id` smallint(5) unsigned NOT NULL,
`item_id` int(11) NOT NULL,
`available` double DEFAULT NULL,
`buy_id` int(11) DEFAULT NULL,
`fix` tinyint(3) unsigned DEFAULT 0,
UNIQUE KEY `warehouse_id` (`warehouse_id`,`item_id`),
KEY `item_id` (`item_id`)
) ENGINE=MEMORY DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `template_bionic_price__`
--
DROP TABLE IF EXISTS `template_bionic_price__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `template_bionic_price__` (
`warehouse_id` smallint(5) unsigned NOT NULL,
`item_id` int(11) NOT NULL,
`rate` tinyint(3) unsigned NOT NULL,
`items` int(11) DEFAULT NULL,
`grouping` int(11) DEFAULT NULL,
`price` decimal(10,2) DEFAULT NULL,
UNIQUE KEY `warehouse_id` (`warehouse_id`,`item_id`,`rate`),
KEY `item_id` (`item_id`) USING BTREE
) ENGINE=MEMORY DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `thermograph`
--
DROP TABLE IF EXISTS `thermograph`;
/*!50001 DROP VIEW IF EXISTS `thermograph`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `thermograph` AS SELECT
1 AS `thermograph_id`,
1 AS `model` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `ticket_observation`
--
DROP TABLE IF EXISTS `ticket_observation`;
/*!50001 DROP VIEW IF EXISTS `ticket_observation`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticket_observation` AS SELECT
1 AS `ticket_observation_id`,
1 AS `Id_Ticket`,
1 AS `observation_type_id`,
1 AS `text` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `tickets_gestdoc`
--
DROP TABLE IF EXISTS `tickets_gestdoc`;
/*!50001 DROP VIEW IF EXISTS `tickets_gestdoc`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `tickets_gestdoc` AS SELECT
1 AS `Id_Ticket`,
1 AS `gestdoc_id` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `time`
--
DROP TABLE IF EXISTS `time`;
/*!50001 DROP VIEW IF EXISTS `time`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `time` AS SELECT
1 AS `date`,
1 AS `period`,
1 AS `month`,
1 AS `year`,
1 AS `day`,
1 AS `week`,
1 AS `yearMonth` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `tipsa__`
--
DROP TABLE IF EXISTS `tipsa__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tipsa__` (
`kilos` tinyint(3) unsigned NOT NULL,
`importe` double unsigned NOT NULL,
`zona` tinyint(3) unsigned NOT NULL,
PRIMARY KEY (`kilos`,`zona`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `tmpNEWTARIFAS__`
--
DROP TABLE IF EXISTS `tmpNEWTARIFAS__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tmpNEWTARIFAS__` (
`Id_Cliente` int(11) NOT NULL,
`Cliente` varchar(50) NOT NULL,
`Consumo_medio_mensual` double(17,0) DEFAULT NULL,
`Tarifa_Actual` int(11) DEFAULT 0,
`Nueva_Tarifa` int(11) DEFAULT NULL,
`Id_Trabajador` int(11) DEFAULT 20,
PRIMARY KEY (`Id_Cliente`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `transport__`
--
DROP TABLE IF EXISTS `transport__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `transport__` (
`wday` tinyint(4) NOT NULL,
PRIMARY KEY (`wday`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `travel`
--
DROP TABLE IF EXISTS `travel`;
/*!50001 DROP VIEW IF EXISTS `travel`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `travel` AS SELECT
1 AS `id`,
1 AS `shipment`,
1 AS `shipment_hour`,
1 AS `landing`,
1 AS `landing_hour`,
1 AS `warehouse_id`,
1 AS `warehouse_id_out`,
1 AS `agency_id`,
1 AS `ref`,
1 AS `delivered`,
1 AS `received`,
1 AS `m3`,
1 AS `kg`,
1 AS `cargoSupplierFk`,
1 AS `totalEntries`,
1 AS `appointment`,
1 AS `awbFk` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `travel_pattern__`
--
DROP TABLE IF EXISTS `travel_pattern__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `travel_pattern__` (
`travel_pattern_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`week_start` tinyint(3) unsigned NOT NULL,
`week_end` tinyint(3) unsigned NOT NULL,
`warehouse_out` smallint(5) unsigned NOT NULL,
`warehouse_in` smallint(5) unsigned NOT NULL,
`agency_id` int(11) NOT NULL,
`day_out` tinyint(3) unsigned NOT NULL,
`duration` tinyint(3) unsigned NOT NULL,
`ref` varchar(20) NOT NULL,
`cargoSupplierFk` int(10) unsigned DEFAULT NULL,
`kg` decimal(10,0) unsigned DEFAULT NULL,
`travelFk` int(10) unsigned DEFAULT NULL COMMENT 'travel origen para clonar ademas sus entradas',
PRIMARY KEY (`travel_pattern_id`),
KEY `warehouse_out` (`warehouse_out`),
KEY `warehouse_in` (`warehouse_in`),
KEY `agency_id` (`agency_id`),
KEY `travel_pattern_ibfk_6_idx` (`cargoSupplierFk`),
KEY `travel_pattern_FK` (`travelFk`),
CONSTRAINT `travel_pattern_FK` FOREIGN KEY (`travelFk`) REFERENCES `vn`.`travel` (`id`) ON UPDATE CASCADE,
CONSTRAINT `travel_pattern___ibfk_3` FOREIGN KEY (`warehouse_out`) REFERENCES `vn`.`warehouse` (`id`) ON UPDATE CASCADE,
CONSTRAINT `travel_pattern___ibfk_4` FOREIGN KEY (`agency_id`) REFERENCES `vn`.`agencyMode` (`id`) ON UPDATE CASCADE,
CONSTRAINT `travel_pattern___ibfk_5` FOREIGN KEY (`warehouse_in`) REFERENCES `vn`.`warehouse` (`id`) ON UPDATE CASCADE,
CONSTRAINT `travel_pattern_supplierFk` FOREIGN KEY (`cargoSupplierFk`) REFERENCES `vn`.`supplier` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `travel_reserve__`
--
DROP TABLE IF EXISTS `travel_reserve__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `travel_reserve__` (
`travel_reserve_id` int(11) NOT NULL AUTO_INCREMENT,
`travel_id` int(11) unsigned NOT NULL,
`Id_Trabajador` int(11) NOT NULL,
`reserved` decimal(4,1) DEFAULT NULL,
`buyed` decimal(4,1) DEFAULT NULL,
`askingfor` decimal(4,1) DEFAULT NULL,
`odbc_date` timestamp NULL DEFAULT current_timestamp(),
`labeled` decimal(4,1) unsigned NOT NULL DEFAULT 0.0,
PRIMARY KEY (`Id_Trabajador`,`travel_id`),
UNIQUE KEY `travel_reserve_id_UNIQUE` (`travel_reserve_id`),
KEY `travel_travel_reserve_idx` (`travel_id`),
KEY `traveL_buyer_id_idx` (`Id_Trabajador`),
CONSTRAINT `travel_reserve___ibfk_1` FOREIGN KEY (`travel_id`) REFERENCES `vn`.`travel` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `trolley__`
--
DROP TABLE IF EXISTS `trolley__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `trolley__` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`fecha` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`ref` varchar(4) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `unaryScanFilter__`
--
DROP TABLE IF EXISTS `unaryScanFilter__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `unaryScanFilter__` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`filter` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `unary__`
--
DROP TABLE IF EXISTS `unary__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `unary__` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `idunary_UNIQUE` (`id`),
KEY `unary_parent_idx` (`parent`),
CONSTRAINT `unary_parent` FOREIGN KEY (`parent`) REFERENCES `unary__` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #7258 @deprecated 2023-12-13';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `unary_scan__`
--
DROP TABLE IF EXISTS `unary_scan__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `unary_scan__` (
`unary_id` int(11) NOT NULL,
`name` varchar(45) DEFAULT NULL,
`odbc_date` timestamp NOT NULL DEFAULT current_timestamp(),
`type` set('BUYS','EXPEDITIONS') NOT NULL,
PRIMARY KEY (`unary_id`),
KEY `scan_unary_idx` (`unary_id`),
CONSTRAINT `unary_scan` FOREIGN KEY (`unary_id`) REFERENCES `unary__` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `unary_scan_line__`
--
DROP TABLE IF EXISTS `unary_scan_line__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `unary_scan_line__` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(45) NOT NULL,
`odbc_date` timestamp NOT NULL DEFAULT current_timestamp(),
`unary_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
KEY `unary_line_idx` (`unary_id`),
CONSTRAINT `unary_line` FOREIGN KEY (`unary_id`) REFERENCES `unary_scan__` (`unary_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `unary_scan_line_buy__`
--
DROP TABLE IF EXISTS `unary_scan_line_buy__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `unary_scan_line_buy__` (
`scan_line_id` int(11) NOT NULL,
`Id_Article` int(11) NOT NULL,
PRIMARY KEY (`scan_line_id`),
UNIQUE KEY `scan_line_id_UNIQUE` (`scan_line_id`),
KEY `Id_Article_buy_idx` (`Id_Article`),
CONSTRAINT `Id_Article_buy` FOREIGN KEY (`Id_Article`) REFERENCES `vn`.`item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `scan_line_id_patriarcal` FOREIGN KEY (`scan_line_id`) REFERENCES `unary_scan_line__` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `unary_scan_line_expedition__`
--
DROP TABLE IF EXISTS `unary_scan_line_expedition__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `unary_scan_line_expedition__` (
`scan_line_id` int(11) NOT NULL,
`expedition_id` int(11) NOT NULL,
PRIMARY KEY (`scan_line_id`),
UNIQUE KEY `scan_line_id_UNIQUE` (`scan_line_id`),
KEY `expedition_id_scan_idx` (`expedition_id`),
CONSTRAINT `expedition_id_scan` FOREIGN KEY (`expedition_id`) REFERENCES `vn`.`expedition` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `unary_source__`
--
DROP TABLE IF EXISTS `unary_source__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `unary_source__` (
`name` varchar(100) NOT NULL,
PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `v_Articles_botanical`
--
DROP TABLE IF EXISTS `v_Articles_botanical`;
/*!50001 DROP VIEW IF EXISTS `v_Articles_botanical`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_Articles_botanical` AS SELECT
1 AS `itemFk`,
1 AS `ediBotanic` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `v_compres`
--
DROP TABLE IF EXISTS `v_compres`;
/*!50001 DROP VIEW IF EXISTS `v_compres`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_compres` AS SELECT
1 AS `Familia`,
1 AS `reino_id`,
1 AS `Id_Compra`,
1 AS `Id_Entrada`,
1 AS `Id_Article`,
1 AS `Cantidad`,
1 AS `Costefijo`,
1 AS `Portefijo`,
1 AS `Novincular`,
1 AS `Etiquetas`,
1 AS `Packing`,
1 AS `grouping`,
1 AS `Comisionfija`,
1 AS `Embalajefijo`,
1 AS `Id_Cubo`,
1 AS `Tarifa1`,
1 AS `Tarifa2`,
1 AS `Tarifa3`,
1 AS `PVP`,
1 AS `Vida`,
1 AS `Id_Trabajador`,
1 AS `punteo`,
1 AS `odbc_date`,
1 AS `Inventario`,
1 AS `Id_Proveedor`,
1 AS `Fecha`,
1 AS `Confirmada`,
1 AS `Redada`,
1 AS `empresa_id`,
1 AS `travel_id`,
1 AS `Pedida`,
1 AS `recibida_id`,
1 AS `id`,
1 AS `shipment`,
1 AS `landing`,
1 AS `warehouse_id`,
1 AS `warehouse_id_out`,
1 AS `agency_id`,
1 AS `ref`,
1 AS `delivered`,
1 AS `received`,
1 AS `Article`,
1 AS `Medida`,
1 AS `Tallos`,
1 AS `caja`,
1 AS `Categoria`,
1 AS `id_origen`,
1 AS `Tipo`,
1 AS `tipo_id`,
1 AS `Color`,
1 AS `Min`,
1 AS `Coste`,
1 AS `fuente`,
1 AS `cm3`,
1 AS `producer_id` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `v_empresa`
--
DROP TABLE IF EXISTS `v_empresa`;
/*!50001 DROP VIEW IF EXISTS `v_empresa`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_empresa` AS SELECT
1 AS `logo`,
1 AS `id`,
1 AS `registro`,
1 AS `gerente_id`,
1 AS `alta`,
1 AS `Nombre`,
1 AS `Apellidos`,
1 AS `Proveedor`,
1 AS `Domicilio`,
1 AS `CP`,
1 AS `Localidad`,
1 AS `NIF`,
1 AS `Telefono`,
1 AS `Alias`,
1 AS `abbreviation` */;
SET character_set_client = @saved_cs_client;
--
-- Temporary table structure for view `versiones`
--
DROP TABLE IF EXISTS `versiones`;
/*!50001 DROP VIEW IF EXISTS `versiones`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `versiones` AS SELECT
1 AS `programa`,
1 AS `version`,
1 AS `critical` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `viaxpress__`
--
DROP TABLE IF EXISTS `viaxpress__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `viaxpress__` (
`codigo_postal` varchar(5) NOT NULL,
`zona` tinyint(4) NOT NULL DEFAULT 2,
`m_t` tinyint(4) NOT NULL DEFAULT 0,
`POBLACION` varchar(25) NOT NULL,
`PROVINCIA` varchar(20) NOT NULL,
PRIMARY KEY (`codigo_postal`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `warehouse_filtro__`
--
DROP TABLE IF EXISTS `warehouse_filtro__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `warehouse_filtro__` (
`warehouse_id` smallint(6) unsigned NOT NULL,
`Id_Trabajador` int(11) NOT NULL,
`ok` tinyint(3) unsigned DEFAULT 1,
PRIMARY KEY (`Id_Trabajador`,`warehouse_id`),
KEY `wh_worker_idx` (`Id_Trabajador`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `warehouse_group__`
--
DROP TABLE IF EXISTS `warehouse_group__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `warehouse_group__` (
`warehouse_alias_id` smallint(5) unsigned NOT NULL DEFAULT 22,
`warehouse_id` smallint(5) unsigned NOT NULL,
PRIMARY KEY (`warehouse_alias_id`,`warehouse_id`),
KEY `warehosue_group_ware_idx` (`warehouse_id`),
CONSTRAINT `warehosue_group_ware` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `warehouse_group_alias` FOREIGN KEY (`warehouse_alias_id`) REFERENCES `vn`.`warehouseAlias__` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `warehouse_joined__`
--
DROP TABLE IF EXISTS `warehouse_joined__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `warehouse_joined__` (
`warehouse_id` smallint(5) unsigned NOT NULL,
`warehouse_alias_id` smallint(5) unsigned NOT NULL,
PRIMARY KEY (`warehouse_id`,`warehouse_alias_id`),
CONSTRAINT `warehouse_joined___ibfk_3` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `warehouse_lc__`
--
DROP TABLE IF EXISTS `warehouse_lc__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `warehouse_lc__` (
`whin` smallint(6) unsigned NOT NULL,
`whout` smallint(6) unsigned NOT NULL,
`m3` double NOT NULL DEFAULT 15,
`days` int(11) NOT NULL DEFAULT 1,
PRIMARY KEY (`whin`,`whout`),
KEY `whout_wh_idx` (`whout`),
CONSTRAINT `whin_wh` FOREIGN KEY (`whin`) REFERENCES `vn`.`warehouse` (`id`) ON UPDATE CASCADE,
CONSTRAINT `whout_wh` FOREIGN KEY (`whout`) REFERENCES `vn`.`warehouse` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Temporary table structure for view `warehouse_pickup`
--
DROP TABLE IF EXISTS `warehouse_pickup`;
/*!50001 DROP VIEW IF EXISTS `warehouse_pickup`*/;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `warehouse_pickup` AS SELECT
1 AS `warehouse_id`,
1 AS `agency_id` */;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `wh_selection__`
--
DROP TABLE IF EXISTS `wh_selection__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wh_selection__` (
`Id_Trabajador` int(10) unsigned NOT NULL,
`warehouse_id` smallint(6) unsigned NOT NULL,
PRIMARY KEY (`Id_Trabajador`,`warehouse_id`),
KEY `Trabajadores` (`Id_Trabajador`),
KEY `Warehouse` (`warehouse_id`),
CONSTRAINT `Trabajadores` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `Warehouse` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `widget__`
--
DROP TABLE IF EXISTS `widget__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `widget__` (
`widget_id` int(11) NOT NULL,
`chr` int(11) NOT NULL,
PRIMARY KEY (`widget_id`),
UNIQUE KEY `chr_UNIQUE` (`chr`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `wks__`
--
DROP TABLE IF EXISTS `wks__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wks__` (
`wk` int(10) unsigned NOT NULL,
`yr` int(10) unsigned NOT NULL,
`vwk` int(10) unsigned NOT NULL,
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`comments` text DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `zones__`
--
DROP TABLE IF EXISTS `zones__`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zones__` (
`zone_id` tinyint(4) NOT NULL,
`name` varchar(45) NOT NULL,
`printingOrder` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`zone_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping events for database 'vn2008'
--
--
-- Dumping routines for database 'vn2008'
--
--
-- 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 = utf8mb3 */;
/*!50001 SET character_set_results = utf8mb3 */;
/*!50001 SET collation_connection = utf8mb3_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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` <> 0 */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `emailUser`
--
/*!50001 DROP VIEW IF EXISTS `emailUser`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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` = `myUser_getId`() */;
/*!50001 SET character_set_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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` = `myUser_getName`() */
/*!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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 `claims_ratio`
--
/*!50001 DROP VIEW IF EXISTS `claims_ratio`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `claims_ratio` AS select `cr`.`clientFk` AS `Id_Cliente`,`cr`.`yearSale` AS `Consumo`,`cr`.`claimAmount` AS `Reclamaciones`,`cr`.`claimingRate` AS `Ratio`,`cr`.`priceIncreasing` AS `recobro`,`cr`.`packingRate` AS `inflacion` from `vn`.`claimRatio` `cr` */;
/*!50001 SET character_set_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `customerRiskOverdue` AS select `cr`.`clientFk` AS `customer_id`,`cr`.`amount` AS `amount`,`cr`.`companyFk` AS `company_id` from (((`vn`.`clientRisk` `cr` join `vn`.`company` `co` on(`co`.`id` = `cr`.`companyFk`)) join `vn`.`client` `c` on(`cr`.`clientFk` = `c`.`id`)) join `vn`.`payMethod` `pm` on(`pm`.`id` = `c`.`payMethodFk`)) where `cr`.`amount` <> 0 and `co`.`isDefaulter` <> 0 and `pm`.`outstandingDebt` <> 0 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` > `util`.`VN_CURDATE`() + interval -101 day and `i`.`dued` + interval `pm`.`graceDays` day > `util`.`VN_CURDATE`() and `i`.`amount` > 0 and `co`.`isDefaulter` <> 0 and `pm`.`outstandingDebt` <> 0 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 `defaulters`
--
/*!50001 DROP VIEW IF EXISTS `defaulters`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `defaulters` AS select `d`.`clientFk` AS `client`,`d`.`created` AS `date`,`d`.`amount` AS `amount`,`d`.`defaulterSinced` AS `defaulterSince`,`d`.`hasChanged` AS `hasChanged`,`d`.`frozened` AS `frozened` from `bs`.`defaulter` `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 `facturacion_media_anual`
--
/*!50001 DROP VIEW IF EXISTS `facturacion_media_anual`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `facturacion_media_anual` AS select `cac`.`clientFk` AS `Id_Cliente`,`cac`.`invoiced` AS `Consumo` from `bs`.`clientAnnualConsumption` `cac` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `rotacion`
--
/*!50001 DROP VIEW IF EXISTS `rotacion`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `rotacion` AS select `ic`.`itemFk` AS `Id_Article`,`ic`.`warehouseFk` AS `warehouse_id`,`ic`.`quantity` AS `total`,`ic`.`rotation` AS `rotacion`,`ic`.`cm3` AS `cm3`,`ic`.`storage` AS `almacenaje`,`ic`.`handling` AS `manipulacion`,`ic`.`extraCharge` AS `auxiliar`,`ic`.`wasted` AS `mermas`,`ic`.`cm3delivery` AS `cm3reparto`,`ic`.`grams` AS `grams` from `vn`.`itemCost` `ic` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `tarifa_componentes`
--
/*!50001 DROP VIEW IF EXISTS `tarifa_componentes`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `tarifa_componentes` AS select `c`.`id` AS `Id_Componente`,`c`.`name` AS `Componente`,`c`.`typeFk` AS `tarifa_componentes_series_id`,`c`.`classRate` AS `tarifa_class`,`c`.`tax` AS `tax`,`c`.`isRenewable` AS `is_renewable`,`c`.`code` AS `code` from `vn`.`component` `c` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `tarifa_componentes_series`
--
/*!50001 DROP VIEW IF EXISTS `tarifa_componentes_series`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `tarifa_componentes_series` AS select `ct`.`id` AS `tarifa_componentes_series_id`,`ct`.`type` AS `Serie`,`ct`.`isBase` AS `base`,`ct`.`isMargin` AS `margen` from `vn`.`componentType` `ct` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Current Database: `bs`
--
USE `bs`;
--
-- Final view structure for view `lastIndicators`
--
/*!50001 DROP VIEW IF EXISTS `lastIndicators`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `lastIndicators` AS select `i`.`updated` AS `updated`,`i`.`lastYearSales` AS `lastYearSales`,`i`.`lastYearSales` - `yi`.`lastYearSales` AS `incLastYearSales`,`i`.`totalGreuge` AS `totalGreuge`,`i`.`totalGreuge` - `yi`.`totalGreuge` AS `incTotalGreuge`,`i`.`latePaymentRate` AS `latePaymentRate`,`i`.`latePaymentRate` - `yi`.`latePaymentRate` AS `incLatePaymentRate`,`i`.`countEmployee` AS `countEmployee`,`i`.`countEmployee` - `yi`.`countEmployee` AS `incCountEmployee`,`i`.`averageMana` AS `averageMana`,`i`.`averageMana` - `yi`.`averageMana` AS `incAverageMana`,`i`.`bankingPool` AS `bankingPool`,`i`.`bankingPool` - `yi`.`bankingPool` AS `incbankingPool`,`i`.`lastMonthActiveClients` AS `lastMonthActiveClients`,`i`.`lastMonthActiveClients` - `yi`.`lastMonthActiveClients` AS `incLastMonthActiveClients`,`i`.`lastMonthLostClients` AS `lastMonthLostClients`,`i`.`lastMonthLostClients` - `yi`.`lastMonthLostClients` AS `incLastMonthLostClients`,`i`.`lastMonthNewClients` AS `lastMonthNewClients`,`i`.`lastMonthNewClients` - `yi`.`lastMonthNewClients` AS `incLastMonthNewClients`,`i`.`lastMonthWebBuyingRate` AS `lastMonthWebBuyingRate`,`i`.`lastMonthWebBuyingRate` - `yi`.`lastMonthWebBuyingRate` AS `incLastMonthWebBuyingRate`,`i`.`thisWeekSales` AS `thisWeekSales`,`i`.`lastYearWeekSales` AS `lastYearWeekSales` from (`indicators` `i` join `indicators` `yi` on(`yi`.`updated` = (select max(`indicators`.`updated`) + interval -1 day from `indicators`))) where `i`.`updated` = (select max(`indicators`.`updated`) from `indicators`) */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `packingSpeed`
--
/*!50001 DROP VIEW IF EXISTS `packingSpeed`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `packingSpeed` AS select hour(`e`.`created`) AS `hora`,minute(`e`.`created`) AS `minuto`,ifnull(`p`.`volume`,`p`.`width` * `p`.`height` * `p`.`depth`) AS `cm3`,`t`.`warehouseFk` AS `warehouse_id`,`e`.`created` AS `odbc_date` from ((`vn`.`expedition` `e` join `vn`.`packaging` `p` on(`p`.`id` = `e`.`packagingFk`)) join `vn`.`ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) where `e`.`created` between `util`.`VN_CURDATE`() and `util`.`dayend`(`util`.`VN_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 `ventas`
--
/*!50001 DROP VIEW IF EXISTS `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `ventas` AS select `s`.`saleFk` AS `Id_Movimiento`,`s`.`amount` AS `importe`,`s`.`surcharge` AS `recargo`,`s`.`dated` AS `fecha`,`s`.`typeFk` AS `tipo_id`,`s`.`clientFk` AS `Id_Cliente`,`s`.`companyFk` AS `empresa_id`,`s`.`margin` AS `margen` from `sale` `s` */;
/*!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: `dipole`
--
USE `dipole`;
--
-- Final view structure for view `expeditionControl`
--
/*!50001 DROP VIEW IF EXISTS `expeditionControl`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `expeditionControl` AS select cast(`epo`.`created` as date) AS `fecha`,count(0) AS `total`,count(`er`.`expeditionFk`) AS `leidas` from (`expedition_PrintOut` `epo` left join `expedition_Read` `er` on(`er`.`expeditionFk` = `epo`.`expeditionFk`)) group by cast(`epo`.`created` as date) */;
/*!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: `edi`
--
USE `edi`;
--
-- Final view structure for view `ektK2`
--
/*!50001 DROP VIEW IF EXISTS `ektK2`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `ektK2` AS select `eek`.`id` AS `id`,`eek`.`description` AS `description` from `ektK1` `eek` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `ektRecent`
--
/*!50001 DROP VIEW IF EXISTS `ektRecent`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `ektRecent` AS select `e`.`id` AS `id`,`e`.`barcode` AS `barcode`,`e`.`entryYear` AS `entryYear`,`e`.`batchNumber` AS `batchNumber`,`e`.`deliveryNumber` AS `deliveryNumber`,`e`.`vendorOrderNumber` AS `vendorOrderNumber`,`e`.`fec` AS `fec`,`e`.`hor` AS `hor`,`e`.`now` AS `now`,`e`.`ptj` AS `ptj`,`e`.`ref` AS `ref`,`e`.`item` AS `item`,`e`.`pac` AS `pac`,`e`.`qty` AS `qty`,`e`.`ori` AS `ori`,`e`.`cat` AS `cat`,`e`.`agj` AS `agj`,`e`.`kop` AS `kop`,`e`.`ptd` AS `ptd`,`e`.`sub` AS `sub`,`e`.`pro` AS `pro`,`e`.`pri` AS `pri`,`e`.`package` AS `package`,`e`.`auction` AS `auction`,`e`.`klo` AS `klo`,`e`.`k1` AS `k1`,`e`.`k2` AS `k2`,`e`.`k3` AS `k3`,`e`.`k4` AS `k4`,`e`.`s1` AS `s1`,`e`.`s2` AS `s2`,`e`.`s3` AS `s3`,`e`.`s4` AS `s4`,`e`.`s5` AS `s5`,`e`.`s6` AS `s6`,`e`.`ok` AS `ok`,`e`.`trolleyFk` AS `trolleyFk`,`e`.`putOrderFk` AS `putOrderFk`,`e`.`scanned` AS `scanned`,`e`.`cps` AS `cps`,`e`.`dp` AS `dp`,`e`.`sender` AS `sender`,`ec`.`usefulAuctionLeftSegmentLength` AS `usefulAuctionLeftSegmentLength`,`ec`.`standardBarcodeLength` AS `standardBarcodeLength`,`ec`.`floridayBarcodeLength` AS `floridayBarcodeLength`,`ec`.`floramondoBarcodeLength` AS `floramondoBarcodeLength`,`ec`.`defaultKlo` AS `defaultKlo`,`ec`.`ektRecentScopeDays` AS `ektRecentScopeDays` from (`ekt` `e` join `ektConfig` `ec`) where `e`.`entryYear` = year(`util`.`VN_CURDATE`()) and `e`.`fec` >= `util`.`VN_CURDATE`() + interval -`ec`.`ektRecentScopeDays` day */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `errorList`
--
/*!50001 DROP VIEW IF EXISTS `errorList`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `errorList` AS select `po`.`id` AS `id`,`c`.`name` AS `name`,`i`.`longName` AS `longName`,`po`.`quantity` AS `quantity`,left(`po`.`error`,4) AS `stock`,`po`.`error` AS `error`,`po`.`deliveryInformationID` AS `deliveryInformationID`,`po`.`supplyResponseID` AS `supplyResponseID`,`po`.`OrderTradeLineDateTime` AS `OrderTradeLineDateTime`,`po`.`EndUserPartyGLN` AS `EndUserPartyGLN` from ((`edi`.`putOrder` `po` left join `vn`.`client` `c` on(`c`.`id` = `po`.`EndUserPartyGLN`)) left join `vn`.`item` `i` on(`i`.`supplyResponseFk` = `po`.`supplyResponseID`)) where `po`.`OrderTradeLineDateTime` > `util`.`VN_CURDATE`() + interval -12 hour and `po`.`OrderStatus` = 3 and left(`po`.`error`,4) <> '(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 `supplyOffer`
--
/*!50001 DROP VIEW IF EXISTS `supplyOffer`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `supplyOffer` AS select `sr`.`vmpID` AS `vmpID`,`di`.`ID` AS `diId`,`sr`.`ID` AS `srId`,`sr`.`Item_ArticleCode` AS `Item_ArticleCode`,`sr`.`VBNOmschrijving` AS `product_name`,`s`.`company_name` AS `company_name`,cast(`sr`.`Price` as decimal(10,3)) AS `Price`,`sr`.`Quality` AS `Quality`,`sr`.`s1` AS `s1`,`sr`.`s2` AS `s2`,`sr`.`s3` AS `s3`,`sr`.`s4` AS `s4`,`sr`.`s5` AS `s5`,`sr`.`s6` AS `s6`,`sr`.`NumberOfUnits` AS `NumberOfUnits`,least(if(`sr`.`EmbalageCode` = 800,`sr`.`EmbalageCode` * 10 + `sr`.`NumberOfItemsPerCask`,`sr`.`EmbalageCode`),ifnull(`idt`.`bucket_id`,'999')) AS `EmbalageCode`,`di`.`LatestDeliveryDateTime` AS `LatestDeliveryDateTime`,`di`.`EarliestDespatchDateTime` AS `EarliestDespatchDateTime`,`di`.`FirstOrderDateTime` AS `FirstOrderDateTime`,`di`.`LatestOrderDateTime` AS `LatestOrderDateTime`,`sr`.`NumberOfItemsPerCask` AS `NumberOfItemsPerCask`,`sr`.`NumberOfLayersPerTrolley` AS `NumberOfLayersPerTrolley`,`sr`.`MinimumNumberToOrder` AS `MinimumNumberToOrder`,`sr`.`MaximumNumberToOrder` AS `MaximumNumberToOrder`,`sr`.`IncrementalOrderableQuantity` AS `IncrementalOrderableQuantity`,`sr`.`PackingPrice` AS `PackingPrice`,`sr`.`MarketPlaceID` AS `MarketPlaceID`,`sr`.`PictureReference` AS `PictureReference`,`sr`.`updated` AS `supplyResponseUpdated`,`i`.`group_id` AS `group_id`,`mp`.`name` AS `marketPlace`,`di`.`DeliveryPrice` AS `DeliveryPrice`,`di`.`ChargeAmount` AS `ChargeAmount`,`di`.`MinimumQuantity` AS `MinimumQuantity`,`di`.`MaximumQuantity Integer` AS `MaximumQuantity`,cast(`sr`.`MinimumNumberToOrder` * case `sr`.`MinimumOrderUnitType` when 1 then 1 when 2 then `sr`.`NumberOfItemsPerCask` / `sr`.`NumberBunchesPerCask` when 3 then `sr`.`NumberOfItemsPerCask` when 4 then floor(128 * 56 / (`b`.`x_size` * `b`.`y_size`)) * `sr`.`NumberOfItemsPerCask` when 5 then floor(128 * 56 / (`b`.`x_size` * `b`.`y_size`)) * `sr`.`NumberOfItemsPerCask` * `sr`.`NumberOfLayersPerTrolley` end as decimal(10,0)) AS `OrderUnit`,cast(`sr`.`IncrementalOrderableQuantity` * case `sr`.`IncrementalOrderableQuantityType` when 1 then 1 when 2 then `sr`.`NumberOfItemsPerCask` / `sr`.`NumberBunchesPerCask` when 3 then `sr`.`NumberOfItemsPerCask` when 4 then floor(128 * 56 / (`b`.`x_size` * `b`.`y_size`)) * `sr`.`NumberOfItemsPerCask` when 5 then floor(128 * 56 / (`b`.`x_size` * `b`.`y_size`)) * `sr`.`NumberOfItemsPerCask` * `sr`.`NumberOfLayersPerTrolley` end as decimal(10,0)) AS `IncrementalOrderUnit`,`mp`.`isEarlyBird` AS `isEarlyBird`,`v`.`isVNHSupplier` AS `isVNHSupplier`,`igo`.`expenseFk` AS `expenseFk`,`igo`.`intrastatFk` AS `intrastatFk`,`igo`.`originFk` AS `originFk`,ifnull(`idt`.`itemTypeFk`,`igo`.`itemTypeFk`) AS `itemTypeFk` from (((((((((`edi`.`deliveryInformation` `di` join `edi`.`supplyResponse` `sr` on(`sr`.`ID` = `di`.`supplyResponseID`)) left join `edi`.`supplier` `s` on(`s`.`glnAddressCode` = `sr`.`SupplierGLN`)) join `edi`.`bucket` `b` on(`b`.`bucket_id` = `sr`.`EmbalageCode`)) join `edi`.`item` `i` on(`i`.`id` = `sr`.`Item_ArticleCode`)) join `edi`.`marketPlace` `mp` on(`mp`.`id` = `sr`.`MarketPlaceID`)) join `vn`.`floramondoConfig` `fm`) left join `edi`.`item_defaultType` `idt` on(`idt`.`item_id` = `i`.`id`)) join `edi`.`VMPSettings` `v` on(`v`.`VMPID` = `sr`.`vmpID`)) join `edi`.`item_groupToOffer` `igo` on(`igo`.`group_code` = `i`.`group_id`)) where `v`.`isBlocked` = 0 and `s`.`isBanned` = 0 and `sr`.`NumberOfUnits` > 0 and current_timestamp() between `di`.`FirstOrderDateTime` and `di`.`LatestOrderDateTime` and `mp`.`isOffered` = 1 and `di`.`LatestDeliveryDateTime` between cast(`fm`.`nextLanded` as date) and concat(cast(`fm`.`nextLanded` as date),' ',`fm`.`MaxLatestDeliveryHour`) and `sr`.`NumberOfItemsPerCask` > 1 group by `sr`.`ID` having `EmbalageCode` <> 999 */;
/*!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: `floranet`
--
USE `floranet`;
--
-- 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 `messageL10n`
--
/*!50001 DROP VIEW IF EXISTS `messageL10n`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `messageL10n` AS select `m`.`code` AS `code`,ifnull(`mi`.`description`,`m`.`description`) AS `description` from (`message` `m` left join `messageI18n` `mi` on(`mi`.`code` = `m`.`code` and `mi`.`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 `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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`.`agencyModeFk` AS `agencyModeFk` from `vn`.`address` `t` where `t`.`clientFk` = `account`.`myUser_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`@`localhost` 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`.`myUser_getId`())) 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 `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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`.`myUser_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 `myInvoice`
--
/*!50001 DROP VIEW IF EXISTS `myInvoice`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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`.`myUser_getId`() */;
/*!50001 SET character_set_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `myOrder` AS select `o`.`id` AS `id`,`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`,`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`,`o`.`taxableBase` AS `taxableBase`,`o`.`tax` AS `tax`,`o`.`total` AS `total` from `hedera`.`order` `o` where `o`.`customer_id` = `account`.`myUser_getId`() and `o`.`source_app` = 'WEB' and `o`.`confirmed` = 0 */
/*!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 `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `myOrderRow` AS select `orw`.`id` AS `id`,`orw`.`order_id` AS `orderFk`,`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` where `orw`.`order_id` in (select `myOrder`.`id` from `hedera`.`myOrder`) */
/*!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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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`.`myUser_getId`() */;
/*!50001 SET character_set_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 `myTicketService`
--
/*!50001 DROP VIEW IF EXISTS `myTicketService`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `myTicketService` AS select `s`.`id` AS `id`,`s`.`description` AS `description`,`s`.`quantity` AS `quantity`,`s`.`price` AS `price`,`s`.`taxClassFk` AS `taxClassFk`,`s`.`ticketFk` AS `ticketFk`,`s`.`ticketServiceTypeFk` AS `ticketServiceTypeFk` from (`vn`.`ticketService` `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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`.`myUser_getId`() */;
/*!50001 SET character_set_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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`.`myUser_getId`() */;
/*!50001 SET character_set_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_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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: `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `queueMemberConf` AS select `m`.`id` AS `uniqueid`,`m`.`queue` AS `queue_name`,concat('SIP/',`m`.`extension`) AS `interface`,0 AS `paused` from `queueMember` `m` union all select `p`.`id` AS `id`,`p`.`queue` AS `queue`,concat('Local/',`p`.`phone`,'@outgoing') AS `phone`,0 AS `paused` from `queuePhone` `p` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `sipConf`
--
/*!50001 DROP VIEW IF EXISTS `sipConf`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `sipConf` AS select `s`.`user_id` AS `id`,`s`.`extension` AS `name`,`s`.`extension` AS `regexten`,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`.`directMedia` AS `directmedia`,`c`.`insecure` AS `insecure`,`c`.`transport` AS `transport`,`c`.`nat` AS `nat`,`c`.`disallow` AS `disallow`,`c`.`allow` AS `allow`,`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: `psico`
--
USE `psico`;
--
-- Final view structure for view `examView`
--
/*!50001 DROP VIEW IF EXISTS `examView`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `examView` AS select `q`.`text` AS `text`,`eq`.`examFk` AS `examFk`,`eq`.`questionFk` AS `questionFk`,`eq`.`answerFk` AS `answerFk`,`eq`.`id` AS `id` from (`question` `q` join `examQuestion` `eq` on(`q`.`id` = `eq`.`questionFk`)) */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `results`
--
/*!50001 DROP VIEW IF EXISTS `results`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `results` AS select `eq`.`examFk` AS `examFk`,sum(`a`.`correct` * `a`.`correct`) AS `aciertos`,`e`.`questionsCount` AS `questionsCount`,hour(timediff(`e`.`finished`,`e`.`started`)) * 60 + minute(timediff(`e`.`finished`,`e`.`started`)) AS `minutos`,least(3,3 * (`e`.`questionsCount` * 0.5) / (hour(timediff(`e`.`finished`,`e`.`started`)) * 60 + minute(timediff(`e`.`finished`,`e`.`started`)))) + 7 * sum(`a`.`correct` * `a`.`correct`) / `e`.`questionsCount` AS `nota` from ((`exam` `e` join `examQuestion` `eq` on(`eq`.`examFk` = `e`.`id`)) join `answer` `a` on(`eq`.`answerFk` = `a`.`id`)) group by `eq`.`examFk`,`e`.`questionsCount` */;
/*!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: `sage`
--
USE `sage`;
--
-- Final view structure for view `clientLastTwoMonths`
--
/*!50001 DROP VIEW IF EXISTS `clientLastTwoMonths`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `clientLastTwoMonths` AS select `vn`.`invoiceOut`.`clientFk` AS `clientFk`,`vn`.`invoiceOut`.`companyFk` AS `companyFk` from `vn`.`invoiceOut` where `vn`.`invoiceOut`.`issued` > `util`.`VN_CURDATE`() - interval 2 month union select `vn`.`receipt`.`clientFk` AS `clientFk`,`vn`.`receipt`.`companyFk` AS `companyFk` from `vn`.`receipt` where `vn`.`receipt`.`payed` > `util`.`VN_CURDATE`() - interval 2 month */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `supplierLastThreeMonths`
--
/*!50001 DROP VIEW IF EXISTS `supplierLastThreeMonths`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `supplierLastThreeMonths` AS select `vn`.`invoiceIn`.`supplierFk` AS `supplierFk`,`vn`.`invoiceIn`.`companyFk` AS `companyFk` from `vn`.`invoiceIn` where `vn`.`invoiceIn`.`issued` > `util`.`VN_CURDATE`() - interval 3 month union select `vn`.`payment`.`supplierFk` AS `supplierFk`,`vn`.`payment`.`companyFk` AS `companyFk` from `vn`.`payment` where `vn`.`payment`.`received` > `util`.`VN_CURDATE`() + interval -3 month */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Current Database: `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 */;
--
-- 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 = utf8mb3 */;
/*!50001 SET character_set_results = utf8mb3 */;
/*!50001 SET collation_connection = utf8mb3_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `User` AS select `account`.`user`.`id` AS `id`,`account`.`user`.`realm` AS `realm`,`account`.`user`.`name` AS `username`,`account`.`user`.`password` AS `password`,`account`.`user`.`email` AS `email`,`account`.`user`.`emailVerified` AS `emailVerified`,`account`.`user`.`verificationToken` AS `verificationToken` 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 */;
--
-- Current Database: `srt`
--
USE `srt`;
--
-- Final view structure for view `bufferDayMinute`
--
/*!50001 DROP VIEW IF EXISTS `bufferDayMinute`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `bufferDayMinute` AS select `b`.`id` AS `bufferFk`,`e`.`id` AS `expeditionFk`,`srt`.`dayMinute`(ifnull(`et`.`eta`,`z`.`hour`)) AS `dayMinute`,`e`.`position` AS `position`,ifnull(`et`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) minute) AS `ETD`,`e2`.`ticketFk` AS `ticketFk`,ifnull(`t`.`routeFk`,`t`.`agencyModeFk`) AS `routeFk`,`z`.`name` AS `zonaTicket`,`es`.`description` AS `expeditionState` from ((((((((`srt`.`buffer` `b` left join `srt`.`expedition` `e` on(`b`.`id` = `e`.`bufferFk`)) left join `srt`.`expeditionState` `es` on(`es`.`id` = `e`.`stateFk`)) join `srt`.`bufferType` `bt` on(`bt`.`id` = `b`.`typeFk`)) left join `vn`.`expedition` `e2` on(`e2`.`id` = `e`.`id`)) left join `vn`.`ticket` `t` on(`e2`.`ticketFk` = `t`.`id`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`expeditionTruck` `et` on(`rm`.`expeditionTruckFk` = `et`.`id`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) where `b`.`isActive` <> 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 `bufferFreeLength`
--
/*!50001 DROP VIEW IF EXISTS `bufferFreeLength`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `bufferFreeLength` AS select cast(`b`.`id` as decimal(10,0)) AS `bufferFk`,`b`.`code` AS `bufferName`,cast(`b`.`length` - sum(ifnull(`e`.`length`,900) + 500) as decimal(10,0)) AS `freeLength`,cast(sum(ifnull(`e`.`length`,900) + 500) as decimal(10,0)) AS `saturacion`,`bs`.`description` AS `state`,`b`.`stateFk` AS `stateFk`,`b`.`typeFk` AS `typeFk`,`bt`.`typeName` AS `typeName`,count(`e`.`id`) AS `stock`,cast(`b`.`length` - sum(if(`es`.`description` = 'STORED',`e`.`length` + 500,0)) as decimal(10,0)) AS `RealFreeLength` from ((((`buffer` `b` left join `expedition` `e` on(`e`.`bufferFk` = `b`.`id`)) left join `expeditionState` `es` on(`es`.`id` = `e`.`stateFk`)) join `bufferType` `bt` on(`bt`.`id` = `b`.`typeFk`)) join `bufferState` `bs` on(`bs`.`id` = `b`.`stateFk`)) group by `b`.`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 `bufferStock`
--
/*!50001 DROP VIEW IF EXISTS `bufferStock`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `bufferStock` AS select `e`.`id` AS `expeditionFk`,`e`.`bufferFk` AS `bufferFk`,`e`.`position` AS `position`,`srt`.`dayMinute`(ifnull(`et`.`eta`,`z`.`hour`)) AS `dayMinute`,ifnull(`et`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) + 120 minute) AS `eta`,`ve`.`ticketFk` AS `ticketFk`,ifnull(`t`.`routeFk`,`t`.`agencyModeFk`) AS `routeFk`,`z`.`name` AS `zonaTicket`,`et`.`description` AS `truck`,`es`.`description` AS `expeditionState`,`b`.`hasWorkerWaiting` AS `hasWorkerWaiting`,`b`.`isActive` AS `isActive`,if(`et`.`id` is null,`c`.`bufferDefault`,`et`.`bufferFk`) AS `bufferTruck`,`bt`.`typeName` AS `typeName`,`rm`.`bufferFk` AS `routeBuffer` from (((((((((`srt`.`expedition` `e` left join `vn`.`expedition` `ve` on(`ve`.`id` = `e`.`id`)) join `srt`.`expeditionState` `es` on(`es`.`id` = `e`.`stateFk`)) join `srt`.`buffer` `b` on(`b`.`id` = `e`.`bufferFk`)) left join `vn`.`ticket` `t` on(`t`.`id` = `ve`.`ticketFk`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`expeditionTruck` `et` on(`rm`.`expeditionTruckFk` = `et`.`id`)) join `srt`.`config` `c`) join `srt`.`bufferType` `bt` on(`bt`.`id` = `b`.`typeFk`)) where `bt`.`typeName` <> 'DISABLED' */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `expeditionVolume`
--
/*!50001 DROP VIEW IF EXISTS `expeditionVolume`*/;
/*!50001 SET @saved_cs_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=`juan`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `expeditionVolume` AS select `bs`.`dayMinute` AS `dayMinute`,`bs`.`eta` AS `ETD`,count(0) AS `cajas`,`bs`.`eta` + interval -`c`.`minutesBeforeTruckDeparture` minute < `util`.`VN_NOW`() or count(0) >= `c`.`minBoxesToUnloading` AS `isReady`,`bs`.`truck` AS `truck`,`bs`.`zonaTicket` AS `zonaTicket`,`bs`.`bufferTruck` AS `bufferTruck` from (`srt`.`bufferStock` `bs` join `srt`.`config` `c`) where `bs`.`expeditionState` = 'STORED' and `bs`.`isActive` <> 0 and `bs`.`hasWorkerWaiting` = 0 and `bs`.`typeName` = 'ACCUMULATION' group by `bs`.`dayMinute` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `routePalletized`
--
/*!50001 DROP VIEW IF EXISTS `routePalletized`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `routePalletized` AS select `t`.`routeFk` AS `routeFk`,count(distinct `e`.`id`) AS `expediciones`,sum(`es`.`description` <=> 'OUT' or `esc`.`expeditionFk` is not null) AS `paletizadas` from ((((((`vn`.`ticket` `t` left join `vn`.`expedition` `e` on(`e`.`ticketFk` = `t`.`id`)) left join `srt`.`expedition` `e2` on(`e2`.`id` = `e`.`id`)) left join `srt`.`expeditionState` `es` on(`es`.`id` = `e2`.`stateFk`)) left join `vn`.`expeditionScan` `esc` on(`esc`.`expeditionFk` = `e`.`id`)) join `vn`.`ticketCollection` `tc` on(`tc`.`ticketFk` = `t`.`id`)) join `vn`.`collection` `c` on(`c`.`id` = `tc`.`collectionFk`)) where `t`.`shipped` between `util`.`yesterday`() and `util`.`tomorrow`() and `c`.`itemPackingTypeFk` = 'H' group by `t`.`routeFk` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `routeVolume`
--
/*!50001 DROP VIEW IF EXISTS `routeVolume`*/;
/*!50001 SET @saved_cs_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=`juan`@`%` SQL SECURITY DEFINER */
/*!50001 VIEW `routeVolume` AS select `bs`.`dayMinute` AS `dayMinute`,`bs`.`eta` AS `ETD`,count(0) AS `cajas`,`bs`.`eta` + interval -`c`.`minutesBeforeTruckDeparture` minute < `util`.`VN_NOW`() or count(0) >= `c`.`minBoxesToUnloading` AS `isReady`,`bs`.`routeFk` AS `routeFk`,`bs`.`zonaTicket` AS `zonaTicket`,`bs`.`bufferTruck` AS `bufferTruck`,`bs`.`routeBuffer` AS `routeBuffer` from (`srt`.`bufferStock` `bs` join `srt`.`config` `c`) where `bs`.`expeditionState` = 'STORED' and `bs`.`isActive` <> 0 and `bs`.`hasWorkerWaiting` = 0 group by `bs`.`routeFk` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `ticketPalletized`
--
/*!50001 DROP VIEW IF EXISTS `ticketPalletized`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketPalletized` AS select `t`.`id` AS `ticketFk`,`t`.`routeFk` AS `routeFk`,count(distinct `e`.`id`) AS `expediciones`,sum(`es`.`description` <=> 'OUT' or `esc`.`expeditionFk` is not null) AS `paletizadas` from ((((((`vn`.`ticket` `t` left join `vn`.`expedition` `e` on(`e`.`ticketFk` = `t`.`id`)) left join `srt`.`expedition` `e2` on(`e2`.`id` = `e`.`id`)) left join `srt`.`expeditionState` `es` on(`es`.`id` = `e2`.`stateFk`)) left join `vn`.`expeditionScan` `esc` on(`esc`.`expeditionFk` = `e`.`id`)) join `vn`.`ticketCollection` `tc` on(`tc`.`ticketFk` = `t`.`id`)) join `vn`.`collection` `c` on(`c`.`id` = `tc`.`collectionFk`)) where `t`.`shipped` between `util`.`yesterday`() and `util`.`tomorrow`() and `c`.`itemPackingTypeFk` = 'H' 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 `upperStickers`
--
/*!50001 DROP VIEW IF EXISTS `upperStickers`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `upperStickers` AS select `e`.`id` AS `expeditionFk`,`e`.`id` MOD 10000 AS `expedition`,ifnull(`et`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) + 120 minute) AS `ETD`,`ve`.`ticketFk` AS `ticketFk`,right(ifnull(`t`.`routeFk`,`t`.`agencyModeFk`),3) AS `routeFk`,`z`.`name` AS `zonaTicket`,`et`.`description` AS `truck`,`epo`.`workerCode` AS `worker`,`p`.`name` AS `labeler`,`ve`.`counter` AS `expeditionCounter`,`vn`.`ticketTotalVolume`(`t`.`id`) AS `m3`,`t`.`clientFk` AS `clientFk` from (((((((`srt`.`expedition` `e` left join `vn`.`expedition` `ve` on(`ve`.`id` = `e`.`id`)) left join `vn`.`ticket` `t` on(`t`.`id` = `ve`.`ticketFk`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`expeditionTruck` `et` on(`rm`.`expeditionTruckFk` = `et`.`id`)) join `dipole`.`expedition_PrintOut` `epo` on(`epo`.`expeditionFk` = `e`.`id`)) join `vn`.`printer` `p` on(`p`.`id` = `epo`.`printerFk`)) */;
/*!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: `tmp`
--
USE `tmp`;
--
-- Current Database: `util`
--
USE `util`;
--
-- Final view structure for view `eventLogGrouped`
--
/*!50001 DROP VIEW IF EXISTS `eventLogGrouped`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb3 */;
/*!50001 SET character_set_results = utf8mb3 */;
/*!50001 SET collation_connection = utf8mb3_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `eventLogGrouped` AS select max(`t`.`date`) AS `lastHappened`,count(0) AS `nErrors`,`t`.`event` AS `event`,`t`.`error` AS `error` from `eventLog` `t` group by `t`.`event`,`t`.`error` order by max(`t`.`date`) desc */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Current Database: `vn`
--
USE `vn`;
--
-- Final view structure for view `NewView`
--
/*!50001 DROP VIEW IF EXISTS `NewView`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `NewView` AS select `c`.`id` AS `clientFk`,max(`t`.`shipped`) AS `lastShipped`,`pc`.`notBuyingMonths` AS `notBuyingMonths` from ((`client` `c` join `productionConfig` `pc`) left join `ticket` `t` on(`c`.`id` = `t`.`clientFk` and `t`.`shipped` < `util`.`VN_CURDATE`() + interval -`pc`.`rookieDays` day)) group by `c`.`id` having `lastShipped` is null or `lastShipped` < `util`.`VN_CURDATE`() + interval -`notBuyingMonths` month */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `agencyTerm`
--
/*!50001 DROP VIEW IF EXISTS `agencyTerm`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb3 */;
/*!50001 SET character_set_results = utf8mb3 */;
/*!50001 SET collation_connection = utf8mb3_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `agencyTerm` AS select `sat`.`agencyFk` AS `agencyFk`,`sat`.`minimumPackages` AS `minimumPackages`,`sat`.`kmPrice` AS `kmPrice`,`sat`.`packagePrice` AS `packagePrice`,`sat`.`routePrice` AS `routePrice`,`sat`.`minimumKm` AS `minimumKm`,`sat`.`minimumM3` AS `minimumM3`,`sat`.`m3Price` AS `m3Price` from `supplierAgencyTerm` `sat` */;
/*!50001 SET character_set_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `annualAverageInvoiced` AS select `cec`.`clientFk` AS `clientFk`,`cec`.`invoiced` AS `invoiced` from `bs`.`clientAnnualConsumption` `cec` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `awbVolume`
--
/*!50001 DROP VIEW IF EXISTS `awbVolume`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `awbVolume` AS select `t`.`awbFk` AS `awbFk`,`b`.`stickers` * `i`.`density` * if(`p`.`volume` > 0,`p`.`volume`,`p`.`width` * `p`.`depth` * if(`p`.`height` = 0,`i`.`size` + 10,`p`.`height`)) / (`vc`.`aerealVolumetricDensity` * 1000) AS `volume`,`b`.`id` AS `buyFk` from ((((((`buy` `b` join `item` `i` on(`b`.`itemFk` = `i`.`id`)) join `itemType` `it` on(`i`.`typeFk` = `it`.`id`)) join `packaging` `p` on(`p`.`id` = `b`.`packagingFk`)) join `entry` `e` on(`b`.`entryFk` = `e`.`id`)) join `travel` `t` on(`t`.`id` = `e`.`travelFk`)) join `volumeConfig` `vc`) where `t`.`shipped` > makedate(year(`util`.`VN_CURDATE`()) - 1,1) and `t`.`awbFk` <> 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 `businessCalendar`
--
/*!50001 DROP VIEW IF EXISTS `businessCalendar`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `businessCalendar` AS select `c`.`id` AS `id`,`c`.`businessFk` AS `businessFk`,`c`.`dayOffTypeFk` AS `absenceTypeFk`,`c`.`dated` AS `dated` from `calendar` `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 `buyer`
--
/*!50001 DROP VIEW IF EXISTS `buyer`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `buyer` AS select distinct `u`.`id` AS `userFk`,`u`.`nickname` AS `nickname` from (`account`.`user` `u` join `vn`.`itemType` `it` on(`it`.`workerFk` = `u`.`id`)) where `u`.`active` <> 0 order by `u`.`nickname` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `buyerSales`
--
/*!50001 DROP VIEW IF EXISTS `buyerSales`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `buyerSales` AS select `v`.`importe` AS `importe`,`w`.`code` AS `comprador`,`t`.`year` AS `año`,`t`.`week` AS `semana` from (((`bs`.`ventas` `v` join `vn`.`time` `t` on(`t`.`dated` = `v`.`fecha`)) join `vn`.`itemType` `it` on(`it`.`id` = `v`.`tipo_id`)) join `vn`.`worker` `w` on(`w`.`id` = `it`.`workerFk`)) */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `clientLost`
--
/*!50001 DROP VIEW IF EXISTS `clientLost`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `clientLost` AS select `c`.`id` AS `clientFk`,max(`t`.`shipped`) AS `lastShipped`,`pc`.`notBuyingMonths` AS `notBuyingMonths` from ((`client` `c` join `productionConfig` `pc`) left join `ticket` `t` on(`c`.`id` = `t`.`clientFk` and `t`.`shipped` < `util`.`VN_CURDATE`() + interval -`pc`.`rookieDays` day)) group by `c`.`id` having `lastShipped` is null or `lastShipped` < `util`.`VN_CURDATE`() + interval -`notBuyingMonths` month */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `clientPhoneBook`
--
/*!50001 DROP VIEW IF EXISTS `clientPhoneBook`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `clientPhoneBook` AS select `c`.`id` AS `clientFk`,trim(`c`.`phone`) AS `phone` from `client` `c` where `c`.`phone` <> 0 and `c`.`isActive` <> 0 union select `c`.`id` AS `clientFk`,trim(`c`.`mobile`) AS `phone` from `client` `c` where `c`.`mobile` <> 0 and `c`.`isActive` <> 0 union select `a`.`clientFk` AS `clientFk`,trim(`a`.`phone`) AS `phone` from (`address` `a` join `client` `c` on(`c`.`id` = `a`.`clientFk`)) where `a`.`phone` <> 0 and `c`.`isActive` <> 0 union select `a`.`clientFk` AS `clientFk`,trim(`a`.`mobile`) AS `phone` from (`address` `a` join `client` `c` on(`c`.`id` = `a`.`clientFk`)) where `a`.`mobile` <> 0 and `c`.`isActive` <> 0 union select `cc`.`clientFk` AS `clientFk`,trim(`cc`.`phone`) AS `phone` from (`clientContact` `cc` left join `client` `c` on(`c`.`id` = `cc`.`clientFk`)) where `c`.`phone` <> 0 and `c`.`isActive` <> 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 `companyL10n`
--
/*!50001 DROP VIEW IF EXISTS `companyL10n`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `companyL10n` AS select `c`.`id` AS `id`,ifnull(`ci`.`footnotes`,`c`.`footnotes`) AS `footnotes` from (`company` `c` left join `companyI18n` `ci` on(`ci`.`companyFk` = `c`.`id` and `ci`.`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 `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `defaulter` AS select `d`.`clientFk` AS `clientFk`,`d`.`created` AS `created`,`d`.`amount` AS `amount`,`d`.`defaulterSinced` AS `defaulterSinced`,`d`.`hasChanged` AS `hasChanged`,`c`.`countryFk` AS `country`,`c`.`payMethodFk` AS `payMethod` from (((`bs`.`defaulter` `d` join `vn`.`client` `c` on(`c`.`id` = `d`.`clientFk`)) join `vn`.`country` `co` on(`co`.`id` = `c`.`countryFk`)) join `vn`.`payMethod` `pm` on(`pm`.`id` = `c`.`payMethodFk`)) */;
/*!50001 SET character_set_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `departmentTree` AS select `node`.`id` AS `id`,concat(convert(repeat(repeat(' ',5),count(`parent`.`id`) - 1) using utf8mb3),`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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 `ektSubAddress`
--
/*!50001 DROP VIEW IF EXISTS `ektSubAddress`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `ektSubAddress` AS select `eea`.`sub` AS `sub`,`a`.`clientFk` AS `clientFk`,`a`.`nickname` AS `nickname`,`eea`.`addressFk` AS `addressFk` from (`ektEntryAssign` `eea` join `address` `a` on(`a`.`id` = `eea`.`addressFk`)) group by `eea`.`sub` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `especialPrice`
--
/*!50001 DROP VIEW IF EXISTS `especialPrice`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `especialPrice` AS select `sp`.`id` AS `id`,`sp`.`clientFk` AS `clientFk`,`sp`.`itemFk` AS `itemFk`,`sp`.`value` AS `value` from `specialPrice` `sp` */;
/*!50001 SET character_set_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 `util`.`VN_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 `exchangeInsuranceInPrevious` group by `exchangeInsuranceInPrevious`.`dated` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `exchangeInsuranceInPrevious`
--
/*!50001 DROP VIEW IF EXISTS `exchangeInsuranceInPrevious`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `exchangeInsuranceInPrevious` AS select `ei`.`dueDated` AS `dated`,`ei`.`amount` AS `amount`,`ei`.`rate` AS `rate` from `exchangeInsurance` `ei` where `ei`.`amount` <> 0 and `ei`.`financialProductTypefk` = 'SC' */;
/*!50001 SET character_set_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 ((`payment` `p` join `accounting` `a` on(`a`.`id` = `p`.`bankFk`)) join `accountingType` `at2` on(`at2`.`id` = `a`.`accountingTypeFk`)) where `p`.`currencyFk` = 2 and `at2`.`code` = 'wireTransfer' and `p`.`supplierFk` <> 2213 group by `p`.`received` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `exchangeReportSource`
--
/*!50001 DROP VIEW IF EXISTS `exchangeReportSource`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `exchangeReportSource` AS select `e`.`dated` AS `dated`,cast(sum(`e`.`amountIn`) as decimal(10,2)) AS `amountIn`,cast(sum(`e`.`rateIn`) as decimal(10,4)) AS `rateIn`,cast(sum(`e`.`amountOut`) as decimal(10,2)) AS `amountOut`,cast(sum(`e`.`rateOut`) as decimal(10,4)) AS `rateOut`,cast(sum(`e`.`amountEntry`) as decimal(10,2)) AS `amountEntry`,cast(sum(`e`.`rateEntry`) as decimal(10,4)) AS `rateEntry`,cast(ifnull(`rr`.`value`,`rrc`.`simulatedValue`) as decimal(10,4)) AS `rateECB` from ((`exchangeReportSourcePrevious` `e` left join `referenceRate` `rr` on(`rr`.`dated` = `e`.`dated`)) join `referenceRateConfig` `rrc` on(1)) group by `e`.`dated` order by `e`.`dated` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `exchangeReportSourcePrevious`
--
/*!50001 DROP VIEW IF EXISTS `exchangeReportSourcePrevious`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 `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 `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 `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 `expeditionCommon`
--
/*!50001 DROP VIEW IF EXISTS `expeditionCommon`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `expeditionCommon` AS select `et`.`id` AS `truckFk`,`et`.`eta` AS `eta`,ifnull(ucase(`et`.`description`),'SIN ESCANEAR') AS `description`,`es`.`palletFk` AS `palletFk`,`t`.`routeFk` AS `routeFk`,`es`.`id` AS `scanFk`,`e`.`id` AS `expeditionFk`,`r`.`expeditionTruckFk` AS `expeditionTruckFk`,`t`.`warehouseFk` AS `warehouseFk`,`e`.`created` AS `lastPacked`,`t`.`id` AS `ticketFk` from (((((`expeditionTruck` `et` left join `routesMonitor` `r` on(`et`.`id` = `r`.`expeditionTruckFk`)) left join `ticket` `t` on(`r`.`routeFk` = `t`.`routeFk`)) left join `expedition` `e` on(`t`.`id` = `e`.`ticketFk`)) left join `expeditionScan` `es` on(`e`.`id` = `es`.`expeditionFk`)) left join `expeditionPallet` `ep` on(`es`.`palletFk` = `ep`.`id`)) where `et`.`eta` >= `util`.`VN_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 `expeditionPallet_Print`
--
/*!50001 DROP VIEW IF EXISTS `expeditionPallet_Print`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `expeditionPallet_Print` AS select `et2`.`description` AS `truck`,`t`.`routeFk` AS `routeFk`,`r`.`description` AS `zone`,count(`es`.`id`) AS `eti`,`ep`.`id` AS `palletFk`,`et`.`id` <=> `rm`.`expeditionTruckFk` AS `isMatch`,`t`.`warehouseFk` AS `warehouseFk`,if(`r`.`created` > `util`.`VN_CURDATE`() + interval 1 day,ucase(dayname(`r`.`created`)),NULL) AS `nombreDia` from (((((((`expeditionTruck` `et` join `expeditionPallet` `ep` on(`ep`.`truckFk` = `et`.`id`)) join `expeditionScan` `es` on(`es`.`palletFk` = `ep`.`id`)) join `expedition` `e` on(`e`.`id` = `es`.`expeditionFk`)) join `ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) join `route` `r` on(`r`.`id` = `t`.`routeFk`)) left join `routesMonitor` `rm` on(`rm`.`routeFk` = `r`.`id`)) left join `expeditionTruck` `et2` on(`et2`.`id` = `rm`.`expeditionTruckFk`)) group by `ep`.`id`,`t`.`routeFk` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `expeditionRoute_Monitor`
--
/*!50001 DROP VIEW IF EXISTS `expeditionRoute_Monitor`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `expeditionRoute_Monitor` AS select `r`.`id` AS `routeFk`,count(distinct if(`e`.`id` is null,`t`.`id`,NULL)) AS `tickets`,count(distinct `e`.`id`) AS `expeditions`,count(distinct `es`.`id`) AS `scanned`,max(`e`.`created`) AS `lastPacked`,`r`.`created` AS `created` from (((((`route` `r` left join `routesMonitor` `rm` on(`r`.`id` = `rm`.`routeFk`)) left join `expeditionTruck` `et` on(`et`.`id` = `rm`.`expeditionTruckFk`)) join `ticket` `t` on(`t`.`routeFk` = `r`.`id`)) left join `expedition` `e` on(`e`.`ticketFk` = `t`.`id`)) left join `expeditionScan` `es` on(`es`.`expeditionFk` = `e`.`id`)) where `r`.`created` >= `util`.`yesterday`() group by `r`.`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 `expeditionRoute_freeTickets`
--
/*!50001 DROP VIEW IF EXISTS `expeditionRoute_freeTickets`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `expeditionRoute_freeTickets` AS select `t`.`routeFk` AS `routeFk`,`tss`.`ticketFk` AS `ticket`,`s`.`name` AS `code`,`w`.`name` AS `almacen`,`tss`.`updated` AS `updated`,`p`.`code` AS `parkingCode` from (((((`ticketState` `tss` join `ticket` `t` on(`t`.`id` = `tss`.`ticketFk`)) join `warehouse` `w` on(`w`.`id` = `t`.`warehouseFk`)) join `state` `s` on(`s`.`id` = `tss`.`state`)) left join `ticketParking` `tp` on(`tp`.`ticketFk` = `t`.`id`)) left join `parking` `p` on(`p`.`id` = `tp`.`parkingFk`)) where ifnull(`t`.`packages`,0) = 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 `expeditionScan_Monitor`
--
/*!50001 DROP VIEW IF EXISTS `expeditionScan_Monitor`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `expeditionScan_Monitor` AS select `et`.`id` AS `truckFk`,`et`.`eta` AS `ETD`,`et`.`description` AS `description`,`ep`.`id` AS `palletFk`,`ep`.`position` AS `position`,`ep`.`built` AS `built`,`es`.`id` AS `scanFk`,`es`.`expeditionFk` AS `expeditionFk`,`es`.`scanned` AS `scanned` from ((`expeditionTruck` `et` left join `expeditionPallet` `ep` on(`ep`.`truckFk` = `et`.`id`)) left join `expeditionScan` `es` on(`es`.`palletFk` = `ep`.`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 `expeditionSticker`
--
/*!50001 DROP VIEW IF EXISTS `expeditionSticker`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `expeditionSticker` AS select `e`.`id` AS `expeditionFk`,`e`.`ticketFk` AS `ticketFk`,`t`.`addressFk` AS `addressFk`,`t`.`clientFk` AS `clientFk`,`a`.`street` AS `street`,`a`.`postalCode` AS `postalCode`,`a`.`city` AS `city`,`a`.`nickname` AS `nickname`,concat('R(',right(`t`.`routeFk`,3),')') AS `routeFk`,`rm`.`beachFk` AS `beachFk`,if(`t`.`routeFk`,ifnull(`et`.`description`,replace(`am`.`name`,'ZONA ','Z')),`z`.`name`) AS `zona`,`p`.`name` AS `province`,ifnull(`c`.`mobile`,ifnull(`a`.`mobile`,ifnull(`c`.`phone`,`a`.`phone`))) AS `phone`,`w`.`code` AS `workerCode` from (((((((((((`expedition` `e` join `ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) join `address` `a` on(`a`.`id` = `t`.`addressFk`)) join `province` `p` on(`p`.`id` = `a`.`provinceFk`)) left join `routesMonitor` `rm` on(`rm`.`routeFk` = `t`.`routeFk`)) left join `expeditionTruck` `et` on(`et`.`id` = `rm`.`expeditionTruckFk`)) left join `beach` `b` on(`b`.`code` = `rm`.`beachFk`)) left join `zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `route` `r` on(`r`.`id` = `t`.`routeFk`)) left join `agencyMode` `am` on(`am`.`id` = `r`.`agencyModeFk`)) join `client` `c` on(`c`.`id` = `a`.`clientFk`)) join `worker` `w` on(`w`.`id` = `e`.`workerFk`)) */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `expeditionTicket_NoBoxes`
--
/*!50001 DROP VIEW IF EXISTS `expeditionTicket_NoBoxes`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `expeditionTicket_NoBoxes` AS select `t`.`id` AS `ticketFk`,`t`.`warehouseFk` AS `warehouseFk`,`t`.`routeFk` AS `routeFk`,`et`.`description` AS `description` from (((`ticket` `t` left join `expedition` `e` on(`e`.`ticketFk` = `t`.`id`)) join `routesMonitor` `rm` on(`rm`.`routeFk` = `t`.`routeFk`)) join `expeditionTruck` `et` on(`et`.`id` = `rm`.`expeditionTruckFk`)) where `e`.`id` is null and `et`.`eta` > `util`.`VN_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 `expeditionTimeExpended`
--
/*!50001 DROP VIEW IF EXISTS `expeditionTimeExpended`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `expeditionTimeExpended` AS select `e`.`ticketFk` AS `ticketFk`,min(`e`.`created`) AS `started`,max(`e`.`created`) AS `finished`,max(`e`.`counter`) AS `cajas`,`w`.`code` AS `code`,`t`.`warehouseFk` AS `warehouseFk` from ((`expedition` `e` join `worker` `w` on(`w`.`id` = `e`.`workerFk`)) join `ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) where `e`.`created` > `util`.`VN_CURDATE`() group by `e`.`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 `expeditionTruck_Control`
--
/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `expeditionTruck_Control` AS select `e`.`truckFk` AS `id`,`e`.`eta` AS `ETD`,`e`.`description` AS `description`,count(distinct if(`e`.`expeditionFk` is null,`e`.`ticketFk`,NULL)) AS `ticketsSinBultos`,count(distinct `e`.`palletFk`) AS `pallets`,count(distinct `e`.`routeFk`) AS `routes`,count(distinct `e`.`scanFk`) AS `scans`,count(distinct `e`.`expeditionFk`) AS `expeditions`,sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`,max(`e`.`lastPacked`) AS `lastPacked` from `expeditionCommon` `e` group by `e`.`truckFk` order by sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) desc,`e`.`eta` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `expeditionTruck_Control_Detail`
--
/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control_Detail`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `expeditionTruck_Control_Detail` AS select `e`.`truckFk` AS `id`,`e`.`eta` AS `eta`,`e`.`description` AS `destino`,`e`.`palletFk` AS `pallet`,count(distinct `e`.`routeFk`) AS `routes`,count(distinct `e`.`scanFk`) AS `scans`,count(distinct `e`.`expeditionTruckFk`) AS `destinos`,sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`,max(`e`.`lastPacked`) AS `lastPacked` from `expeditionCommon` `e` group by `e`.`truckFk`,`e`.`palletFk` order by sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) desc,`e`.`eta`,`e`.`truckFk` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `expeditionTruck_Control_Detail_Pallet`
--
/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control_Detail_Pallet`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `expeditionTruck_Control_Detail_Pallet` AS select `e`.`truckFk` AS `id`,`e`.`eta` AS `eta`,`e`.`description` AS `destino`,`e`.`palletFk` AS `pallet`,`e`.`routeFk` AS `route`,count(distinct `e`.`scanFk`) AS `scans`,`et`.`description` AS `destinos`,sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`,`e`.`expeditionTruckFk` AS `expeditionTruckFk`,max(`e`.`lastPacked`) AS `lastPacked` from (`expeditionCommon` `e` left join `expeditionTruck` `et` on(`et`.`id` = `e`.`expeditionTruckFk`)) group by `e`.`truckFk`,`e`.`palletFk`,`e`.`routeFk` order by sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) desc,`e`.`palletFk` */;
/*!50001 SET character_set_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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`)) where `t`.`shipped` > `util`.`VN_CURDATE`() + interval -3 year */;
/*!50001 SET character_set_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `itemBotanicalWithGenus` AS select `ib`.`itemFk` AS `itemFk`,concat(`g`.`name`,' ',ifnull(`s`.`name`,'')) AS `ediBotanic` from ((`itemBotanical` `ib` left join `specie` `s` on(`s`.`id` = `ib`.`specieFk`)) left join `genus` `g` on(`g`.`id` = `ib`.`genusFk`)) */;
/*!50001 SET character_set_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 `itemColor`
--
/*!50001 DROP VIEW IF EXISTS `itemColor`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `itemColor` AS select `it`.`itemFk` AS `itemFk`,`it`.`value` AS `color` from (`itemTag` `it` join `tag` `t` on(`t`.`id` = `it`.`tagFk`)) where `t`.`code` = 'COLOR' */;
/*!50001 SET character_set_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_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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`.`isExcludedFromAvailable` = 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_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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`.`isExcludedFromAvailable` = 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 `itemInk`
--
/*!50001 DROP VIEW IF EXISTS `itemInk`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `itemInk` AS select `i`.`longName` AS `longName`,`i`.`inkFk` AS `inkFk`,`ink`.`name` AS `color` from (`item` `i` join `ink` on(`ink`.`id` = `i`.`inkFk`)) where `ink`.`isRealColor` <> 0 group by `i`.`longName` */;
/*!50001 SET character_set_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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`,`ips`.`sectorFk` AS `sectorFk` from ((((`itemPlacementSupply` `ips` join `item` `i` on(`i`.`id` = `ips`.`itemFk`)) left join `worker` `w` on(`w`.`id` = `ips`.`userFk`)) left join `worker` `rw` on(`rw`.`id` = `ips`.`repoUserFk`)) left join `itemShelvingPlacementSupply` `isps` on(`isps`.`itemPlacementSupplyFk` = `ips`.`id`)) where `ips`.`created` >= `util`.`VN_CURDATE`() group by `ips`.`priority`,`ips`.`id`,`ips`.`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 `itemProductor`
--
/*!50001 DROP VIEW IF EXISTS `itemProductor`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `itemProductor` AS select `it`.`itemFk` AS `itemFk`,`it`.`value` AS `productor` from (`itemTag` `it` join `tag` `t` on(`t`.`id` = `it`.`tagFk`)) where `t`.`code` = 'PRODUCER' */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `itemSearch`
--
/*!50001 DROP VIEW IF EXISTS `itemSearch`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `itemSearch` AS select `s`.`itemFk` AS `itemFk`,`s`.`concept` AS `concept`,`s`.`quantity` AS `quantity`,`t`.`nickname` AS `nickname`,`t`.`shipped` AS `shipped` from ((`sale` `s` join `ticket` `t` on(`t`.`id` = `s`.`ticketFk`)) join `warehouse` `w` on(`w`.`id` = `t`.`warehouseFk`)) where `t`.`shipped` between `util`.`yesterday`() and `util`.`tomorrow`() and `w`.`name` in ('VNH','Floramondo') */;
/*!50001 SET character_set_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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`,`t`.`warehouseFk` AS `warehouseFk` from (((((((((`sale` `s` join `ticket` `t` on(`t`.`id` = `s`.`ticketFk`)) join `agencyMode` `am` on(`am`.`id` = `t`.`agencyModeFk`)) join `ticketStateToday` `tst` on(`tst`.`ticketFk` = `t`.`id`)) join `state` `st` on(`st`.`id` = `tst`.`state`)) join `item` `i` on(`i`.`id` = `s`.`itemFk`)) join `itemShelvingStock` `stock` on(`stock`.`itemFk` = `i`.`id`)) left join `saleTracking` `stk` on(`stk`.`saleFk` = `s`.`id`)) left join `zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `saleVolume` `sv` on(`sv`.`saleFk` = `s`.`id`)) where `t`.`shipped` between `util`.`yesterday`() and `util`.`dayend`(`util`.`VN_CURDATE`()) and `stk`.`id` is null and `stock`.`visible` > 0 and `stk`.`saleFk` is null and `st`.`isPreviousPreparable` <> 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 `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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`,`pk`.`sectorFk` AS `sectorFk` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `itemShelvingPlacementSupplyStock` AS select `ish`.`id` AS `itemShelvingFk`,`ish`.`itemFk` AS `itemFk`,`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 `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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`,0 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`,`st`.`code` = 'previousPrepared' AS `isPreviousPrepared` 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 `sectorType` `st` on(`st`.`id` = `s`.`typeFk`)) where `ish`.`visible` <> 0 and `p`.`sectorFk` <> 0 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `itemShelvingStockRemoved` AS select `ish`.`id` AS `itemShelvingFk`,`ish`.`itemFk` AS `itemFk`,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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `itemTagged` AS select distinct `itemTag`.`itemFk` AS `itemFk` from `itemTag` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `itemTaxCountrySpain`
--
/*!50001 DROP VIEW IF EXISTS `itemTaxCountrySpain`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `itemTaxCountrySpain` AS select `i`.`id` AS `id`,`i`.`name` AS `name`,`i`.`typeFk` AS `typeFk`,`i`.`stems` AS `stems`,`i`.`description` AS `description`,`i`.`intrastatFk` AS `intrastatFk`,`i`.`expenseFk` AS `expenseFk`,`i`.`comment` AS `comment`,`i`.`relevancy` AS `relevancy`,`i`.`image` AS `image`,`i`.`generic` AS `generic`,`itc`.`taxClassFk` AS `taxClassFk` from (`item` `i` join `itemTaxCountry` `itc` on(`itc`.`itemFk` = `i`.`id`)) where `itc`.`countryFk` = 1 */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `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_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 `item_Free_Id`
--
/*!50001 DROP VIEW IF EXISTS `item_Free_Id`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `item_Free_Id` AS select `i1`.`id` + 1 AS `newId` from (`item` `i1` left join `item` `i2` on(`i1`.`id` + 1 = `i2`.`id`)) where `i2`.`id` is null and `i1`.`isFloramondo` <> 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 `labelInfo`
--
/*!50001 DROP VIEW IF EXISTS `labelInfo`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `labelInfo` AS select `i`.`id` AS `itemId`,`i`.`name` AS `itemName`,`b`.`stickers` AS `stickers`,`b`.`printedStickers` AS `life`,`i`.`inkFk` AS `colorCode`,`i`.`stems` AS `stems`,`i`.`category` AS `category`,`i`.`subName` AS `productor`,`b`.`packing` AS `packing`,`clb`.`warehouse_id` AS `warehouse_id`,`i`.`size` AS `size`,`b`.`isPickedOff` AS `isPickedOff`,`e`.`evaNotes` AS `notes`,`w`.`name` AS `wh_in`,`e`.`id` AS `entryId`,`b`.`id` AS `buyId` from (((((`vn`.`buy` `b` join `vn`.`item` `i` on(`i`.`id` = `b`.`itemFk`)) join `cache`.`last_buy` `clb` on(`clb`.`item_id` = `i`.`id`)) join `vn`.`entry` `e` on(`e`.`id` = `b`.`entryFk`)) left join `vn`.`travel` `tr` on(`tr`.`id` = `e`.`travelFk`)) join `vn`.`warehouse` `w` on(`w`.`id` = `tr`.`warehouseInFk`)) */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `lastHourProduction`
--
/*!50001 DROP VIEW IF EXISTS `lastHourProduction`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `lastHourProduction` AS select `t`.`warehouseFk` AS `warehouseFk`,cast(sum(ifnull(`p`.`volume`,`p`.`width` * `p`.`height` * `p`.`depth`) / 1000000) as decimal(5,1)) AS `m3` from (((`warehouse` `w` join `ticket` `t` on(`t`.`warehouseFk` = `w`.`id`)) left join `expedition` `e` on(`t`.`id` = `e`.`ticketFk`)) left join `packaging` `p` on(`p`.`id` = `e`.`packagingFk`)) where `e`.`created` between `util`.`VN_NOW`() - interval 1 hour and `util`.`VN_NOW`() group by `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 `lastPurchases`
--
/*!50001 DROP VIEW IF EXISTS `lastPurchases`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `lastPurchases` AS select `tr`.`landed` AS `landed`,`w`.`id` AS `warehouseFk`,`w`.`name` AS `warehouse`,`i`.`longName` AS `longName`,`i`.`subName` AS `subName`,`e`.`id` AS `entryFk`,`b`.`stickers` AS `stickers`,`b`.`packing` AS `packing`,`e`.`invoiceNumber` AS `ref`,`b`.`itemFk` AS `itemFk`,`ek`.`pro` AS `pro`,`ek`.`ref` AS `ektRef`,`ek`.`agj` AS `agj` from (((((`vn`.`buy` `b` join `vn`.`entry` `e` on(`e`.`id` = `b`.`entryFk`)) join `vn`.`item` `i` on(`i`.`id` = `b`.`itemFk`)) join `vn`.`travel` `tr` on(`tr`.`id` = `e`.`travelFk`)) join `vn`.`warehouse` `w` on(`w`.`id` = `tr`.`warehouseInFk`)) left join `edi`.`ekt` `ek` on(`ek`.`id` = `b`.`ektFk`)) where `tr`.`landed` between `util`.`yesterday`() and `util`.`tomorrow`() and `e`.`isRaid` = 0 and `b`.`stickers` > 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 `lastTopClaims`
--
/*!50001 DROP VIEW IF EXISTS `lastTopClaims`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `lastTopClaims` AS select `s`.`itemFk` AS `itemFk`,`i`.`longName` AS `itemName`,`it`.`name` AS `itemTypeName`,count(0) AS `claimsNumber`,round(sum(`cb`.`quantity` * `s`.`price` * (1 - (`c`.`responsibility` - 1) / 4) * (100 - `s`.`discount`) / 100),2) AS `claimedAmount`,round(sum(`cb`.`quantity` * `s`.`price` * (100 - `s`.`discount`) / 100),2) AS `totalAmount` from ((((`claim` `c` join `claimBeginning` `cb` on(`cb`.`claimFk` = `c`.`id`)) join `sale` `s` on(`s`.`id` = `cb`.`saleFk`)) join `item` `i` on(`i`.`id` = `s`.`itemFk`)) join `itemType` `it` on(`it`.`id` = `i`.`typeFk`)) where `c`.`created` >= `util`.`VN_CURDATE`() + interval -1 week group by `s`.`itemFk` having `claimedAmount` > 100 and `claimsNumber` > 2 or `claimsNumber` > 4 order by count(0) 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 `mistake`
--
/*!50001 DROP VIEW IF EXISTS `mistake`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `mistake` AS select `wr`.`code` AS `revisador`,`s`.`concept` AS `concept`,`w`.`code` AS `sacador`,`w`.`firstName` AS `firstName`,`w`.`lastName` AS `lastName`,`mt`.`description` AS `description`,cast(`iss`.`created` as date) AS `created`,`w`.`id` AS `workerFk` from (((((`saleMistake` `sm` join `mistakeType` `mt` on(`mt`.`id` = `sm`.`typeFk`)) join `worker` `wr` on(`wr`.`id` = `sm`.`userFk`)) join `sale` `s` on(`s`.`id` = `sm`.`saleFk`)) join `itemShelvingSale` `iss` on(`iss`.`saleFk` = `sm`.`saleFk`)) join `worker` `w` on(`w`.`id` = `iss`.`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 `mistakeRatio`
--
/*!50001 DROP VIEW IF EXISTS `mistakeRatio`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `mistakeRatio` AS select `wr`.`code` AS `revisador`,`w`.`code` AS `sacador`,`w`.`firstName` AS `firstName`,`w`.`lastName` AS `lastName`,`mt`.`description` AS `description`,cast(`iss`.`created` as date) AS `created`,`w`.`id` AS `workerFk`,`sm`.`saleFk` AS `saleFk` from ((((`itemShelvingSale` `iss` join `worker` `w` on(`w`.`id` = `iss`.`userFk`)) left join `saleMistake` `sm` on(`iss`.`saleFk` = `sm`.`saleFk`)) left join `mistakeType` `mt` on(`mt`.`id` = `sm`.`typeFk`)) left join `worker` `wr` on(`wr`.`id` = `sm`.`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 `newBornSales`
--
/*!50001 DROP VIEW IF EXISTS `newBornSales`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `newBornSales` AS select `v`.`importe` AS `amount`,`v`.`Id_Cliente` AS `clientFk`,`c`.`salesPersonFk` AS `userFk`,`v`.`fecha` AS `dated`,`cn`.`firstShipped` AS `firstShipped` from ((((`bs`.`clientNewBorn` `cn` join `bs`.`ventas` `v` on(`cn`.`firstShipped` + interval 1 year > `v`.`fecha` and `v`.`Id_Cliente` = `cn`.`clientFk`)) join `vn`.`client` `c` on(`c`.`id` = `v`.`Id_Cliente`)) join `account`.`user` `u` on(`u`.`id` = `c`.`salesPersonFk`)) join `account`.`role` `r` on(`r`.`id` = `u`.`role`)) where `r`.`name` = 'salesPerson' and `u`.`name` not in ('ismaelalcolea','ruben') */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `operatorWorkerCode`
--
/*!50001 DROP VIEW IF EXISTS `operatorWorkerCode`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb3 */;
/*!50001 SET character_set_results = utf8mb3 */;
/*!50001 SET collation_connection = utf8mb3_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `operatorWorkerCode` AS select `o`.`workerFk` AS `workerFk`,concat(`w`.`firstName`,' ',`w`.`lastName`) AS `fullName`,`w`.`code` AS `code`,`o`.`numberOfWagons` AS `numberOfWagons` from ((`worker` `w` join `operator` `o` on(`o`.`workerFk` = `w`.`id`)) join `sector` `s` on(`o`.`sectorFk` = `s`.`id`)) where `o`.`sectorFk` is not null and `s`.`code` in ('H2','H2','PEQUES_H','ALTILLO COMP','ALTILLO ARTI') */;
/*!50001 SET character_set_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `packageEquivalentItem` AS select `p`.`itemFk` AS `itemFk`,`p2`.`itemFk` AS `equivalentFk` from ((`packageEquivalent` `pe` join `packaging` `p` on(`p`.`id` = `pe`.`packagingFk`)) join `packaging` `p2` on(`p2`.`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 `paymentExchangeInsurance`
--
/*!50001 DROP VIEW IF EXISTS `paymentExchangeInsurance`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `paymentExchangeInsurance` AS select `ei`.`id` AS `pago_sdc_id`,`ei`.`amount` AS `importe`,`ei`.`dated` AS `fecha`,`ei`.`dueDated` AS `vencimiento`,`ei`.`entityFk` AS `entity_id`,`ei`.`ref` AS `ref`,`ei`.`rate` AS `rate`,`ei`.`companyFk` AS `empresa_id`,`ei`.`financialProductTypefk` AS `financialProductTypefk`,`ei`.`upperBarrier` AS `upperBarrier`,`ei`.`lowerBarrier` AS `lowerBarrier`,`ei`.`strike` AS `strike` from `exchangeInsurance` `ei` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `payrollCenter`
--
/*!50001 DROP VIEW IF EXISTS `payrollCenter`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `payrollCenter` AS select `b`.`workCenterFkA3` AS `codCenter`,`b`.`companyFkA3` AS `companyCode` from `payrollWorkCenter` `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 `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `personMedia` AS select `c`.`id` AS `workerFk`,ifnull(`c`.`mobile`,`c`.`phone`) AS `mediaValue` from (`client` `c` join `worker` `w` on(`w`.`id` = `c`.`id`)) having `mediaValue` is not null */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `phoneBook`
--
/*!50001 DROP VIEW IF EXISTS `phoneBook`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `phoneBook` AS select 'C' AS `Tipo`,`client`.`id` AS `Id`,`client`.`name` AS `Cliente`,`client`.`phone` AS `Telefono` from `client` where `client`.`phone` is not null union select 'C' AS `Tipo`,`client`.`id` AS `Id`,`client`.`name` AS `Cliente`,`client`.`mobile` AS `Movil` from `client` where `client`.`mobile` is not null union select 'C' AS `Tipo`,`clientContact`.`clientFk` AS `clientFk`,`clientContact`.`name` AS `name`,`clientContact`.`phone` AS `phone` from `clientContact` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `productionVolume`
--
/*!50001 DROP VIEW IF EXISTS `productionVolume`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `productionVolume` AS select hour(`e`.`created`) AS `hora`,minute(`e`.`created`) AS `minuto`,ifnull(`p`.`volume`,ifnull(`p`.`width` * `p`.`height` * `p`.`depth`,94500)) AS `cm3`,`t`.`warehouseFk` AS `warehouseFk`,`e`.`created` AS `created` from (((`expedition` `e` left join `packaging` `p` on(`p`.`id` = `e`.`packagingFk`)) join `ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) join `client` `c` on(`c`.`id` = `t`.`clientFk`)) where `e`.`created` between `util`.`VN_CURDATE`() and `util`.`dayend`(`util`.`VN_CURDATE`()) and `c`.`isRelevant` <> 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 `productionVolume_LastHour`
--
/*!50001 DROP VIEW IF EXISTS `productionVolume_LastHour`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `productionVolume_LastHour` AS select cast(sum(`productionVolume`.`cm3` / 1000000) as decimal(10,0)) AS `m3`,`productionVolume`.`warehouseFk` AS `warehouseFk` from `productionVolume` where `productionVolume`.`created` > `util`.`VN_NOW`() + interval -1 hour and `productionVolume`.`warehouseFk` in (1,44,60) group by `productionVolume`.`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 `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 `routesControl`
--
/*!50001 DROP VIEW IF EXISTS `routesControl`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `routesControl` AS select `t`.`routeFk` AS `routeFk`,count(`e`.`id`) AS `expeditions`,count(`es`.`id`) AS `scanned`,count(distinct `es`.`palletFk`) AS `pallets`,max(`es`.`scanned`) AS `lastScanned`,max(`et`.`description`) AS `description`,max(`et`.`eta`) AS `eta` from ((((`ticket` `t` join `expedition` `e` on(`t`.`id` = `e`.`ticketFk`)) left join `expeditionScan` `es` on(`es`.`expeditionFk` = `e`.`id`)) left join `expeditionPallet` `ep` on(`ep`.`id` = `es`.`palletFk`)) left join `expeditionTruck` `et` on(`et`.`id` = `ep`.`truckFk`)) where `t`.`shipped` >= `util`.`VN_CURDATE`() and `t`.`routeFk` <> 0 group by `t`.`routeFk` order by max(`et`.`eta`) */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `saleCost`
--
/*!50001 DROP VIEW IF EXISTS `saleCost`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `saleCost` AS select `s`.`itemFk` AS `itemFk`,`s`.`ticketFk` AS `ticketFk`,`s`.`concept` AS `concept`,`s`.`quantity` AS `quantity`,`s`.`discount` AS `discount`,`s`.`price` AS `price`,`c`.`name` AS `component`,`sc`.`value` AS `coste` from (((`sale` `s` join `saleComponent` `sc` on(`sc`.`saleFk` = `s`.`id`)) join `component` `c` on(`c`.`id` = `sc`.`componentFk`)) join `componentType` `ct` on(`ct`.`id` = `c`.`typeFk`)) where `ct`.`type` = 'coste' */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `saleMistakeList`
--
/*!50001 DROP VIEW IF EXISTS `saleMistakeList`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `saleMistakeList` AS select `st`.`saleFk` AS `saleFk`,`st`.`workerFk` AS `workerFk`,concat(`w2`.`firstName`,' ',`w2`.`lastName`) AS `sacador`,`st`.`created` AS `created`,concat(`w`.`firstName`,' ',`w`.`lastName`) AS `revisador`,`mt`.`description` AS `description`,`sm`.`created` AS `controlled` from (((((`saleTracking` `st` join `worker` `w2` on(`w2`.`id` = `st`.`workerFk`)) join `state` `s` on(`s`.`id` = `st`.`stateFk` and `s`.`code` in ('PREVIOUS_PREPARATION','PREPARED','OK'))) left join `saleMistake` `sm` on(`st`.`saleFk` = `sm`.`saleFk`)) left join `mistakeType` `mt` on(`mt`.`id` = `sm`.`typeFk`)) left join `worker` `w` on(`w`.`id` = `sm`.`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 `saleMistake_list__2`
--
/*!50001 DROP VIEW IF EXISTS `saleMistake_list__2`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `saleMistake_list__2` AS select `st`.`saleFk` AS `saleFk`,`st`.`workerFk` AS `workerFk`,concat(`w2`.`firstName`,' ',`w2`.`lastName`) AS `sacador`,`st`.`created` AS `created`,concat(`w`.`firstName`,' ',`w`.`lastName`) AS `revisador`,`mt`.`description` AS `description`,`sm`.`created` AS `controlled` from (((((`saleTracking` `st` join `worker` `w2` on(`w2`.`id` = `st`.`workerFk`)) join `state` `s` on(`s`.`id` = `st`.`stateFk` and `s`.`code` in ('PREVIOUS_PREPARATION','PREPARED','OK'))) left join `saleMistake` `sm` on(`st`.`saleFk` = `sm`.`saleFk`)) left join `mistakeType` `mt` on(`mt`.`id` = `sm`.`typeFk`)) left join `worker` `w` on(`w`.`id` = `sm`.`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 `saleSaleTracking`
--
/*!50001 DROP VIEW IF EXISTS `saleSaleTracking`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `saleSaleTracking` AS select distinct `st`.`saleFk` AS `saleFk` from `saleTracking` `st` where `st`.`created` >= `util`.`VN_CURDATE`() + interval -1 day */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `saleValue` AS select `wh`.`name` AS `warehouse`,`c`.`name` AS `client`,`c`.`typeFk` AS `typeFk`,`u`.`name` AS `buyer`,`it`.`id` AS `itemTypeFk`,`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` <> 0 */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `saleVolume`
--
/*!50001 DROP VIEW IF EXISTS `saleVolume`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `saleVolume` AS select `s`.`ticketFk` AS `ticketFk`,`s`.`id` AS `saleFk`,round(`ic`.`cm3delivery` * `s`.`quantity` / 1000,0) AS `litros`,`t`.`routeFk` AS `routeFk`,`t`.`shipped` AS `shipped`,`t`.`landed` AS `landed`,`s`.`quantity` * `ic`.`cm3delivery` / 1000000 AS `volume`,`s`.`quantity` * `ic`.`grams` / 1000 AS `physicalWeight`,`s`.`quantity` * `ic`.`cm3delivery` * greatest(`ic`.`grams` / `ic`.`cm3delivery`,`vc`.`aerealVolumetricDensity`) / 1000000 AS `weight`,`s`.`quantity` * `ic`.`cm3delivery` / 1000000 AS `physicalVolume`,`s`.`quantity` * `ic`.`cm3delivery` * ifnull(`t`.`zonePrice` - ifnull(`t`.`zoneBonus`,0),`z`.`price` - `z`.`bonus`) / (`vc`.`standardFlowerBox` * 1000) * `z`.`inflation` AS `freight`,`t`.`zoneFk` AS `zoneFk`,`t`.`clientFk` AS `clientFk`,`s`.`isPicked` AS `isPicked`,`s`.`quantity` * `s`.`price` * (100 - `s`.`discount`) / 100 AS `eurosValue`,`i`.`itemPackingTypeFk` AS `itemPackingTypeFk` from (((((`sale` `s` join `item` `i` on(`i`.`id` = `s`.`itemFk`)) join `ticket` `t` on(`t`.`id` = `s`.`ticketFk`)) join `zone` `z` on(`z`.`id` = `t`.`zoneFk`)) join `volumeConfig` `vc`) join `itemCost` `ic` on(`ic`.`itemFk` = `s`.`itemFk` and `ic`.`warehouseFk` = `t`.`warehouseFk`)) 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 `saleVolume_Today_VNH`
--
/*!50001 DROP VIEW IF EXISTS `saleVolume_Today_VNH`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `saleVolume_Today_VNH` AS select `t`.`nickname` AS `Cliente`,`p`.`name` AS `Provincia`,`c`.`country` AS `Pais`,cast(sum(`sv`.`volume`) as decimal(5,1)) AS `volume` from (((((`saleVolume` `sv` join `ticket` `t` on(`t`.`id` = `sv`.`ticketFk`)) join `address` `a` on(`a`.`id` = `t`.`addressFk`)) join `province` `p` on(`p`.`id` = `a`.`provinceFk`)) join `country` `c` on(`c`.`id` = `p`.`countryFk`)) join `warehouse` `w` on(`w`.`id` = `t`.`warehouseFk`)) where `w`.`name` = 'VNH' and `t`.`shipped` between `util`.`VN_CURDATE`() and `util`.`dayend`(`util`.`VN_CURDATE`()) group by `t`.`nickname`,`p`.`name` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `sale_freightComponent`
--
/*!50001 DROP VIEW IF EXISTS `sale_freightComponent`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `sale_freightComponent` AS select `t`.`id` AS `ticketFk`,`sc`.`value` * `s`.`quantity` AS `amount`,`t`.`shipped` AS `shipped` from ((((`ticket` `t` straight_join `sale` `s` on(`t`.`id` = `s`.`ticketFk`)) join `saleComponent` `sc` on(`sc`.`saleFk` = `s`.`id`)) join `component` `c` on(`c`.`id` = `sc`.`componentFk`)) join `componentType` `ct` on(`ct`.`id` = `c`.`typeFk` and `ct`.`type` = 'agencia')) */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `salesPersonSince`
--
/*!50001 DROP VIEW IF EXISTS `salesPersonSince`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `salesPersonSince` AS select `b`.`workerFk` AS `workerFk`,min(`b`.`started`) AS `started` from ((`business` `b` join `worker` `w` on(`w`.`id` = `b`.`workerFk`)) left join `professionalCategory` `pc` on(`pc`.`id` = `b`.`workerBusinessProfessionalCategoryFk`)) where `pc`.`description` = 'Aux ventas' group by `b`.`workerFk` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `salesPreparedLastHour`
--
/*!50001 DROP VIEW IF EXISTS `salesPreparedLastHour`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `salesPreparedLastHour` AS select `t`.`warehouseFk` AS `warehouseFk`,`st`.`saleFk` AS `saleFk`,`st`.`isChecked` AS `isChecked`,`st`.`originalQuantity` AS `originalQuantity`,`st`.`created` AS `created`,`e`.`code` AS `code`,`w`.`firstName` AS `firstname`,`w`.`lastName` AS `lastName`,`w`.`code` AS `workerCode`,`ic`.`cm3delivery` * `s`.`quantity` / 1000 AS `litros`,`s`.`concept` AS `concept`,`d`.`name` AS `departmentName` from ((((((((`saleTracking` `st` left join `salesPreviousPreparated` `prevPrepSales` on(`prevPrepSales`.`saleFk` = `st`.`saleFk`)) join `sale` `s` on(`s`.`id` = `st`.`saleFk`)) join `ticket` `t` on(`t`.`id` = `s`.`ticketFk`)) join `itemCost` `ic` on(`ic`.`warehouseFk` = `t`.`warehouseFk` and `ic`.`itemFk` = `s`.`itemFk`)) join `worker` `w` on(`w`.`id` = `st`.`workerFk`)) join `state` `e` on(`e`.`id` = `st`.`stateFk`)) join `workerDepartment` `wd` on(`wd`.`workerFk` = `st`.`workerFk`)) join `department` `d` on(`d`.`id` = `wd`.`departmentFk`)) where `st`.`created` > `util`.`VN_NOW`() + interval -1 hour and `prevPrepSales`.`saleFk` is null and `d`.`name` not like 'EQUIPO%' */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `salesPreviousPreparated`
--
/*!50001 DROP VIEW IF EXISTS `salesPreviousPreparated`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `salesPreviousPreparated` AS select `st`.`saleFk` AS `saleFk` from (`saleTracking` `st` join `state` `e` on(`e`.`id` = `st`.`stateFk`)) where `st`.`created` > `util`.`VN_CURDATE`() and `e`.`code` like 'PREVIOUS_PREPARATION' */;
/*!50001 SET character_set_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 `warehouse`,`b`.`buyingValue` AS `buyingValue` 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` <> 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 `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 `ticketDownBuffer`
--
/*!50001 DROP VIEW IF EXISTS `ticketDownBuffer`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketDownBuffer` AS select `td`.`ticketFk` AS `ticketFk`,`td`.`created` AS `created`,`td`.`selected` AS `selected`,concat(`w`.`firstName`,' ',`w`.`lastName`) AS `sacador`,`pk`.`code` AS `parking` from ((((`ticketDown` `td` join `ticketParking` `tp` on(`tp`.`ticketFk` = `td`.`ticketFk`)) join `parking` `pk` on(`pk`.`id` = `tp`.`parkingFk`)) join `ticketStateToday` `tst` on(`tst`.`ticketFk` = `td`.`ticketFk`)) join `worker` `w` on(`w`.`id` = `tst`.`userFk`)) where `td`.`selected` = 2 */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `ticketLastUpdated`
--
/*!50001 DROP VIEW IF EXISTS `ticketLastUpdated`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketLastUpdated` AS select `ticketLastUpdatedList`.`ticketFk` AS `ticketFk`,max(`ticketLastUpdatedList`.`created`) AS `lastUpdated` from `ticketLastUpdatedList` group by `ticketLastUpdatedList`.`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 `ticketLastUpdatedList`
--
/*!50001 DROP VIEW IF EXISTS `ticketLastUpdatedList`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketLastUpdatedList` AS select `s`.`ticketFk` AS `ticketFk`,`st`.`created` AS `created` from (`saleTracking` `st` join `sale` `s` on(`s`.`id` = `st`.`saleFk`)) where `st`.`created` > `util`.`VN_CURDATE`() union all select `tt`.`ticketFk` AS `Id_Ticket`,`tt`.`created` AS `odbc_date` from `ticketTracking` `tt` where `tt`.`created` > `util`.`VN_CURDATE`() union all select `s`.`ticketFk` AS `ticketFk`,`iss`.`created` AS `created` from (`itemShelvingSale` `iss` join `sale` `s` on(`s`.`id` = `iss`.`saleFk`)) where `iss`.`created` > `util`.`VN_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 `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 `t`.`refFk` is null 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 `ticketPackingList`
--
/*!50001 DROP VIEW IF EXISTS `ticketPackingList`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketPackingList` AS select `t`.`nickname` AS `nickname`,`t`.`id` AS `ticketFk`,`am`.`name` AS `agencyMode`,`am`.`flag` AS `flag`,`p`.`name` AS `province`,`s`.`itemFk` AS `itemFk`,`s`.`concept` AS `concept`,`s`.`quantity` AS `quantity`,`sv`.`litros` AS `litros`,`to`.`description` AS `observaciones` from (((((((`ticket` `t` join `address` `a` on(`a`.`id` = `t`.`addressFk`)) join `province` `p` on(`p`.`id` = `a`.`provinceFk`)) join `agencyMode` `am` on(`am`.`id` = `t`.`agencyModeFk`)) left join `sale` `s` on(`s`.`ticketFk` = `t`.`id`)) left join `saleVolume` `sv` on(`sv`.`saleFk` = `s`.`id`)) join `observationType` `ot` on(`ot`.`code` = 'packager')) left join `ticketObservation` `to` on(`to`.`ticketFk` = `t`.`id` and `ot`.`id` = `to`.`observationTypeFk`)) */;
/*!50001 SET character_set_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketPreviousPreparingList` AS select `s`.`ticketFk` AS `ticketFk`,`w`.`code` AS `code`,count(`s`.`id`) AS `saleLines`,sum(`s`.`isPicked` <> 0) AS `alreadyMadeSaleLines`,sum(`s`.`isPicked` <> 0) / count(`s`.`id`) AS `madeRate`,`sg`.`created` AS `created`,`p`.`code` AS `parking`,`iss`.`sectorFk` AS `sectorFk`,`al`.`code` AS `alertCode` from (((((((`saleGroup` `sg` join `saleGroupDetail` `sgd` on(`sgd`.`saleGroupFk` = `sg`.`id`)) join `sale` `s` on(`s`.`id` = `sgd`.`saleFk`)) join `ticketState` `tls` on(`tls`.`ticketFk` = `s`.`ticketFk`)) join `alertLevel` `al` on(`al`.`id` = `tls`.`alertLevel`)) join `worker` `w` on(`w`.`id` = `sg`.`userFk`)) left join `parking` `p` on(`p`.`id` = `sg`.`parkingFk`)) join `itemShelvingStock` `iss` on(`iss`.`itemFk` = `s`.`itemFk`)) where `sg`.`created` >= `util`.`VN_CURDATE`() + interval 0.1 day group by `sg`.`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 `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_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketState` AS select `tt`.`created` AS `updated`,`tt`.`stateFk` AS `stateFk`,`tt`.`userFk` AS `userFk`,`tls`.`ticketFk` AS `ticketFk`,`s`.`id` AS `state`,`s`.`order` AS `productionOrder`,`s`.`alertLevel` AS `alertLevel`,`s`.`code` AS `code`,`s`.`isPreviousPreparable` AS `isPreviousPreparable`,`s`.`isPicked` AS `isPicked` from ((`ticketLastState` `tls` join `ticketTracking` `tt` on(`tt`.`id` = `tls`.`ticketTrackingFk`)) join `state` `s` on(`s`.`id` = `tt`.`stateFk`)) */;
/*!50001 SET character_set_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `ticketStateToday` AS select `ts`.`ticketFk` AS `ticketFk`,`ts`.`state` AS `state`,`ts`.`productionOrder` AS `productionOrder`,`ts`.`alertLevel` AS `alertLevel`,`ts`.`userFk` AS `userFk`,`ts`.`code` AS `code`,`ts`.`updated` AS `updated`,`ts`.`isPicked` AS `isPicked` from (`ticketState` `ts` join `ticket` `t` on(`t`.`id` = `ts`.`ticketFk`)) where `t`.`shipped` between `util`.`VN_CURDATE`() and `MIDNIGHT`(`util`.`VN_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 `tr2`
--
/*!50001 DROP VIEW IF EXISTS `tr2`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `tr2` AS select `travel`.`id` AS `id`,`travel`.`shipped` AS `shipped`,`travel`.`shipmentHour` AS `shipmentHour`,`travel`.`landed` AS `landed`,`travel`.`landingHour` AS `landingHour`,`travel`.`warehouseInFk` AS `warehouseInFk`,`travel`.`warehouseOutFk` AS `warehouseOutFk`,`travel`.`agencyModeFk` AS `agencyFk`,`travel`.`ref` AS `ref`,`travel`.`isDelivered` AS `isDelivered`,`travel`.`isReceived` AS `isReceived`,`travel`.`m3` AS `m3`,`travel`.`kg` AS `kg`,`travel`.`cargoSupplierFk` AS `cargoSupplierFk`,`travel`.`totalEntries` AS `totalEntries` from `travel` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `traceabilityBuy`
--
/*!50001 DROP VIEW IF EXISTS `traceabilityBuy`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `traceabilityBuy` AS select `b`.`id` AS `buyFk`,`b`.`quantity` AS `quantity`,`tr`.`landed` AS `landed`,`w`.`name` AS `warehouseName`,`b`.`entryFk` AS `entryFk`,`s`.`name` AS `supplierName`,ifnull(`b`.`itemOriginalFk`,`b`.`itemFk`) AS `itemFk` 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 `warehouse` `w` on(`w`.`id` = `tr`.`warehouseInFk`)) */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `traceabilitySale`
--
/*!50001 DROP VIEW IF EXISTS `traceabilitySale`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `traceabilitySale` AS select `s`.`ticketFk` AS `ticketFk`,`sb`.`buyFk` AS `buyFk`,`t`.`shipped` AS `shipped`,`t`.`nickname` AS `nickname`,`s`.`quantity` AS `quantity`,concat(`w`.`firstName`,' ',`w`.`lastName`) AS `worker` from (((`saleBuy` `sb` join `sale` `s` on(`s`.`id` = `sb`.`saleFk`)) join `ticket` `t` on(`t`.`id` = `s`.`ticketFk`)) join `worker` `w` on(`w`.`id` = `sb`.`workerFk`)) */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `workerBusinessDated`
--
/*!50001 DROP VIEW IF EXISTS `workerBusinessDated`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `workerBusinessDated` AS select `t`.`dated` AS `dated`,`b`.`id` AS `businessFk`,`b`.`workerFk` AS `workerFk` from (`time` `t` left join `business` `b` on(`t`.`dated` between `b`.`started` and ifnull(`b`.`ended`,`util`.`VN_CURDATE`()))) where `t`.`dated` > `util`.`VN_CURDATE`() + interval -2 year */;
/*!50001 SET character_set_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_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `workerDepartment` AS select `b`.`workerFk` AS `workerFk`,`b`.`departmentFk` AS `departmentFk` from (`business` `b` join `worker` `w` on(`w`.`businessFk` = `b`.`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 `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `workerLabour` AS select `b`.`id` AS `businessFk`,`b`.`workerFk` AS `workerFk`,`b`.`workcenterFk` AS `workCenterFk`,`b`.`started` AS `started`,`b`.`ended` AS `ended`,`b`.`departmentFk` AS `departmentFk`,`b`.`payedHolidays` AS `payedHolidays` from `business` `b` order by `b`.`started` 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 `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `workerMedia` AS select `w`.`id` AS `workerFk`,`w`.`phone` AS `mediaValue` from `worker` `w` where `w`.`phone` is not null */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `workerSpeedExpedition`
--
/*!50001 DROP VIEW IF EXISTS `workerSpeedExpedition`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `workerSpeedExpedition` AS select `sv`.`ticketFk` AS `ticketFk`,sum(`sv`.`litros`) AS `litros`,sum(if(`sub`.`started` > `util`.`VN_NOW`() + interval -1 hour,`sv`.`litros`,0)) AS `literLastHour`,cast(60 * sum(`sv`.`litros`) / time_to_sec(timediff(max(`sub`.`finished`),min(`sub`.`started`))) as decimal(10,1)) AS `litersByMinute`,`sub`.`code` AS `workerCode`,`sub`.`cajas` AS `cajas`,`sub`.`warehouseFk` AS `warehouseFk` from (`saleVolume` `sv` join `expeditionTimeExpended` `sub` on(`sub`.`ticketFk` = `sv`.`ticketFk`)) group by `sub`.`code` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `workerSpeedSaleTracking`
--
/*!50001 DROP VIEW IF EXISTS `workerSpeedSaleTracking`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `workerSpeedSaleTracking` AS select `salesPreparedLastHour`.`warehouseFk` AS `warehouseFk`,`salesPreparedLastHour`.`code` AS `state`,`salesPreparedLastHour`.`workerCode` AS `workerCode`,sum(`salesPreparedLastHour`.`litros`) AS `sumaLitros`,min(`salesPreparedLastHour`.`created`) AS `started`,max(`salesPreparedLastHour`.`created`) AS `finished`,sum(if(`salesPreparedLastHour`.`created` >= `util`.`VN_NOW`() + interval -1 hour,`salesPreparedLastHour`.`litros`,0)) AS `sumaLitrosLastHour`,cast(60 * sum(`salesPreparedLastHour`.`litros`) / time_to_sec(timediff(max(`salesPreparedLastHour`.`created`),min(`salesPreparedLastHour`.`created`))) as decimal(10,1)) AS `litersByMinute`,`salesPreparedLastHour`.`departmentName` AS `departmentName` from `salesPreparedLastHour` group by `salesPreparedLastHour`.`warehouseFk`,`salesPreparedLastHour`.`code`,`salesPreparedLastHour`.`workerCode` */;
/*!50001 SET character_set_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_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` 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`,`wd`.`departmentFk` AS `departmentFk`,left(`c`.`fi`,8) AS `dni` from (((`account`.`user` `u` join `vn`.`worker` `w` on(`w`.`id` = `u`.`id`)) join `vn`.`client` `c` on(`c`.`id` = `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 `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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `workerTimeJourneyNG` AS select `wtc`.`userFk` AS `userFk`,cast(`wtc`.`timed` as date) AS `dated`,if(`wtc`.`order` MOD 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`.`id` = `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 `workerWithoutTractor`
--
/*!50001 DROP VIEW IF EXISTS `workerWithoutTractor`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `workerWithoutTractor` AS select `c`.`workerFk` AS `workerFk`,`cl`.`name` AS `Trabajador`,count(distinct `c`.`id`) AS `Colecciones`,max(`c`.`created`) AS `created` from ((`collection` `c` join `client` `cl` on(`cl`.`id` = `c`.`workerFk`)) left join `machineWorker` `mw` on(`mw`.`workerFk` = `c`.`workerFk` and `mw`.`inTimed` > `util`.`VN_CURDATE`())) where `c`.`created` > `util`.`VN_CURDATE`() and `mw`.`workerFk` is null group by `c`.`workerFk` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `zoneEstimatedDelivery`
--
/*!50001 DROP VIEW IF EXISTS `zoneEstimatedDelivery`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `zoneEstimatedDelivery` AS select `t`.`zoneFk` AS `zoneFk`,`zc`.`hour` AS `zoneClosureHour`,`z`.`hour` AS `zoneHour`,`sv`.`volume` AS `volume`,`al`.`hasToRecalcPrice` AS `hasToRecalcPrice`,`lhp`.`m3` AS `m3`,`dl`.`minSpeed` AS `minSpeed` from (((((((((`vn`.`ticket` `t` join `vn`.`ticketStateToday` `tst` on(`tst`.`ticketFk` = `t`.`id`)) join `vn`.`state` `s` on(`s`.`id` = `tst`.`state`)) join `vn`.`saleVolume` `sv` on(`sv`.`ticketFk` = `t`.`id`)) left join `vn`.`lastHourProduction` `lhp` on(`lhp`.`warehouseFk` = `t`.`warehouseFk`)) join `vn`.`warehouse` `w` on(`w`.`id` = `t`.`warehouseFk`)) straight_join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `vn`.`zoneClosure` `zc` on(`zc`.`zoneFk` = `t`.`zoneFk` and `zc`.`dated` = `util`.`VN_CURDATE`())) left join `cache`.`departure_limit` `dl` on(`dl`.`warehouse_id` = `t`.`warehouseFk` and `dl`.`fecha` = `util`.`VN_CURDATE`())) join `vn`.`alertLevel` `al` on(`al`.`id` = `s`.`alertLevel`)) where `w`.`hasProduction` <> 0 and cast(`t`.`shipped` as date) = `util`.`VN_CURDATE`() */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Current Database: `vn2008`
--
USE `vn2008`;
--
-- Final view structure for view `Agencias`
--
/*!50001 DROP VIEW IF EXISTS `Agencias`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Agencias` AS select `am`.`id` AS `Id_Agencia`,`am`.`name` AS `Agencia`,`am`.`description` AS `description`,`am`.`deliveryMethodFk` AS `Vista`,`am`.`m3` AS `m3`,`am`.`web` AS `web`,`am`.`agencyFk` AS `agency_id`,`am`.`inflation` AS `inflacion`,`am`.`isVolumetric` AS `is_volumetric`,`am`.`reportMail` AS `send_mail`,`am`.`isActive` AS `tpv`,`am`.`code` AS `code`,`am`.`showAgencyName` AS `show_AgencyName`,`am`.`isRiskFree` AS `isRiskFree` from `vn`.`agencyMode` `am` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Articles`
--
/*!50001 DROP VIEW IF EXISTS `Articles`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Articles` AS select `i`.`id` AS `Id_Article`,`i`.`name` AS `Article`,`i`.`typeFk` AS `tipo_id`,`i`.`size` AS `Medida`,`i`.`inkFk` AS `Color`,`i`.`category` AS `Categoria`,`i`.`stems` AS `Tallos`,`i`.`originFk` AS `id_origen`,`i`.`description` AS `description`,`i`.`producerFk` AS `producer_id`,`i`.`intrastatFk` AS `Codintrastat`,`i`.`box` AS `caja`,`i`.`expenseFk` AS `expenseFk`,`i`.`comment` AS `comments`,`i`.`relevancy` AS `relevancy`,`i`.`image` AS `Foto`,`i`.`generic` AS `generic`,`i`.`density` AS `density`,`i`.`minPrice` AS `PVP`,`i`.`hasMinPrice` AS `Min`,`i`.`isActive` AS `isActive`,`i`.`longName` AS `longName`,`i`.`subName` AS `subName`,`i`.`tag5` AS `tag5`,`i`.`value5` AS `value5`,`i`.`tag6` AS `tag6`,`i`.`value6` AS `value6`,`i`.`tag7` AS `tag7`,`i`.`value7` AS `value7`,`i`.`tag8` AS `tag8`,`i`.`value8` AS `value8`,`i`.`tag9` AS `tag9`,`i`.`value9` AS `value9`,`i`.`tag10` AS `tag10`,`i`.`value10` AS `value10`,`i`.`minimum` AS `minimum`,`i`.`upToDown` AS `upToDown`,`i`.`hasKgPrice` AS `hasKgPrice`,`i`.`equivalent` AS `Equivalente`,`i`.`isToPrint` AS `Imprimir`,`i`.`family` AS `Familia__`,`i`.`doPhoto` AS `do_photo`,`i`.`created` AS `odbc_date`,`i`.`isFloramondo` AS `isFloramondo`,`i`.`supplyResponseFk` AS `supplyResponseFk`,`i`.`stemMultiplier` AS `stemMultiplier`,`i`.`itemPackingTypeFk` AS `itemPackingTypeFk`,`i`.`packingOut` AS `packingOut` from `vn`.`item` `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 `Bancos`
--
/*!50001 DROP VIEW IF EXISTS `Bancos`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Bancos` AS select `a`.`id` AS `Id_Banco`,`a`.`bank` AS `Banco`,`a`.`account` AS `Cuenta`,`a`.`accountingTypeFk` AS `cash`,`a`.`entityFk` AS `entity_id`,`a`.`isActive` AS `activo`,`a`.`currencyFk` AS `currencyFk` from `vn`.`accounting` `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 `Bancos_poliza`
--
/*!50001 DROP VIEW IF EXISTS `Bancos_poliza`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Bancos_poliza` AS select `bp`.`id` AS `poliza_id`,`bp`.`ref` AS `referencia`,`bp`.`amount` AS `importe`,`bp`.`committedFee` AS `com_dispuesto`,`bp`.`nonCommittedFee` AS `com_no_dispuesto`,`bp`.`annualFee` AS `com_anual`,`bp`.`started` AS `apertura`,`bp`.`ended` AS `cierre`,`bp`.`accountingFk` AS `Id_Banco`,`bp`.`companyFk` AS `empresa_id`,`bp`.`supplierFk` AS `supplierFk`,`bp`.`description` AS `description`,`bp`.`hasGuarantee` AS `hasGuarantee`,`bp`.`dmsFk` AS `dmsFk`,`bp`.`notaryFk` AS `notaryFk`,`bp`.`currencyFk` AS `currencyFk`,`bp`.`amortizationTypeFk` AS `amortizationTypeFk`,`bp`.`periodicityTypeFk` AS `periodicityTypeFk`,`bp`.`insuranceExpired` AS `insuranceExpired` from `vn`.`bankPolicy` `bp` order by `bp`.`id` 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 `Cajas`
--
/*!50001 DROP VIEW IF EXISTS `Cajas`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Cajas` AS select `t`.`id` AS `Id_Caja`,`t`.`dated` AS `Cajafecha`,`t`.`serie` AS `Serie`,`t`.`concept` AS `Concepto`,`t`.`in` AS `Entrada`,`t`.`out` AS `Salida`,`t`.`bankFk` AS `Id_Banco`,`t`.`companyFk` AS `empresa_id`,`t`.`isAccountable` AS `Partida`,`t`.`InForeignValue` AS `InForeignValue`,`t`.`OutForeignValue` AS `OutForeignValue`,`t`.`workerFk` AS `Id_Trabajador`,`t`.`calculatedCode` AS `id_calculated`,`t`.`number` AS `Numero`,`t`.`isLinked` AS `linked`,`t`.`created` AS `odbc_date`,`t`.`isOk` AS `ok`,`t`.`warehouseFk` AS `warehouse_id`,`t`.`isConciliate` AS `conciliado`,`t`.`supplierAccountFk` AS `Proveedores_account_Id` from `vn`.`till` `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 `Clientes`
--
/*!50001 DROP VIEW IF EXISTS `Clientes`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Clientes` AS select `c`.`id` AS `id_cliente`,`c`.`name` AS `cliente`,`c`.`fi` AS `if`,`c`.`socialName` AS `razonSocial`,`c`.`contact` AS `contacto`,`c`.`street` AS `domicilio`,`c`.`city` AS `poblacion`,`c`.`postcode` AS `codPostal`,`c`.`phone` AS `telefono`,`c`.`mobile` AS `movil`,`c`.`isRelevant` AS `real`,`c`.`email` AS `e-mail`,`c`.`iban` AS `iban`,`c`.`dueDay` AS `vencimiento`,`c`.`accountingAccount` AS `Cuenta`,`c`.`isEqualizated` AS `RE`,`c`.`provinceFk` AS `province_id`,`c`.`hasToInvoice` AS `invoice`,`c`.`credit` AS `credito`,`c`.`countryFk` AS `Id_Pais`,`c`.`isActive` AS `activo`,`c`.`gestdocFk` AS `gestdoc_id`,`c`.`quality` AS `calidad`,`c`.`payMethodFk` AS `pay_met_id`,`c`.`created` AS `created`,`c`.`isToBeMailed` AS `mail`,`c`.`contactChannelFk` AS `chanel_id`,`c`.`hasSepaVnl` AS `sepaVnl`,`c`.`hasCoreVnl` AS `coreVnl`,`c`.`hasCoreVnh` AS `coreVnh`,`c`.`hasLcr` AS `hasLcr`,`c`.`defaultAddressFk` AS `default_address`,`c`.`riskCalculated` AS `risk_calculated`,`c`.`hasToInvoiceByAddress` AS `invoiceByAddress`,`c`.`isTaxDataChecked` AS `contabilizado`,`c`.`isFreezed` AS `congelado`,`c`.`creditInsurance` AS `creditInsurance`,`c`.`isCreatedAsServed` AS `isCreatedAsServed`,`c`.`hasInvoiceSimplified` AS `hasInvoiceSimplified`,`c`.`salesPersonFk` AS `Id_Trabajador`,`c`.`isVies` AS `vies`,`c`.`bankEntityFk` AS `bankEntityFk`,`c`.`typeFk` AS `typeFk` from `vn`.`client` `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 `Comparativa`
--
/*!50001 DROP VIEW IF EXISTS `Comparativa`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Comparativa` AS select `c`.`timePeriod` AS `Periodo`,`c`.`itemFk` AS `Id_Article`,`c`.`warehouseFk` AS `warehouse_id`,`c`.`quantity` AS `Cantidad`,`c`.`price` AS `price`,`c`.`countryFk` AS `countryFk` from `vn`.`comparative` `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 `Compres`
--
/*!50001 DROP VIEW IF EXISTS `Compres`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb3 */;
/*!50001 SET character_set_results = utf8mb3 */;
/*!50001 SET collation_connection = utf8mb3_general_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Compres` AS select `c`.`id` AS `Id_Compra`,`c`.`entryFk` AS `Id_Entrada`,`c`.`itemFk` AS `Id_Article`,`c`.`buyingValue` AS `Costefijo`,`c`.`quantity` AS `Cantidad`,`c`.`packagingFk` AS `Id_Cubo`,`c`.`stickers` AS `Etiquetas`,`c`.`freightValue` AS `Portefijo`,`c`.`packageValue` AS `Embalajefijo`,`c`.`comissionValue` AS `Comisionfija`,`c`.`packing` AS `Packing`,`c`.`grouping` AS `grouping`,`c`.`groupingMode` AS `caja`,`c`.`location` AS `Nicho`,`c`.`price1` AS `Tarifa1`,`c`.`price2` AS `Tarifa2`,`c`.`price3` AS `Tarifa3`,`c`.`minPrice` AS `PVP`,`c`.`printedStickers` AS `Vida`,`c`.`isChecked` AS `punteo`,`c`.`ektFk` AS `buy_edi_id`,`c`.`created` AS `odbc_date`,`c`.`isIgnored` AS `Novincular`,`c`.`isPickedOff` AS `isPickedOff`,`c`.`workerFk` AS `Id_Trabajador`,`c`.`weight` AS `weight`,`c`.`dispatched` AS `dispatched`,`c`.`containerFk` AS `container_id`,`c`.`itemOriginalFk` AS `itemOriginalFk` from `vn`.`buy` `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 `Compres_mark`
--
/*!50001 DROP VIEW IF EXISTS `Compres_mark`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Compres_mark` AS select `bm`.`id` AS `Id_Compra`,`bm`.`comment` AS `comment`,`bm`.`mark` AS `mark`,`bm`.`odbcDate` AS `odbc_date` from `vn`.`buyMark` `bm` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Consignatarios`
--
/*!50001 DROP VIEW IF EXISTS `Consignatarios`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Consignatarios` AS select `a`.`id` AS `id_consigna`,`a`.`clientFk` AS `Id_cliente`,`a`.`street` AS `domicilio`,`a`.`city` AS `poblacion`,`a`.`postalCode` AS `codPostal`,`a`.`provinceFk` AS `province_id`,`a`.`phone` AS `telefono`,`a`.`mobile` AS `movil`,`a`.`nickname` AS `consignatario`,`a`.`isDefaultAddress` AS `predeterminada`,`a`.`longitude` AS `longitude`,`a`.`latitude` AS `latitude`,`a`.`agencyModeFk` AS `Id_Agencia`,`a`.`isEqualizated` AS `isEqualizated`,`a`.`isActive` AS `active` from `vn`.`address` `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 `Cubos`
--
/*!50001 DROP VIEW IF EXISTS `Cubos`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Cubos` AS select `p`.`id` AS `Id_Cubo`,`p`.`volume` AS `Volumen`,`p`.`width` AS `X`,`p`.`depth` AS `Y`,`p`.`height` AS `Z`,`p`.`isPackageReturnable` AS `Retornable`,`p`.`created` AS `odbc_date`,`p`.`itemFk` AS `item_id`,`p`.`price` AS `pvp`,`p`.`cubicPackage` AS `bultoCubico`,`p`.`value` AS `Valor`,`p`.`packagingReturnFk` AS `idCubos_Retorno`,`p`.`lower` AS `Bajan`,`p`.`upload` AS `Suben`,`p`.`base` AS `Base`,`p`.`isBox` AS `box`,`p`.`returnCost` AS `costeRetorno` from `vn`.`packaging` `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 `Cubos_Retorno`
--
/*!50001 DROP VIEW IF EXISTS `Cubos_Retorno`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Cubos_Retorno` AS select `rb`.`id` AS `idCubos_Retorno`,`rb`.`freightContainerType` AS `Soporte`,`rb`.`freightPackagingEmpty` AS `Vacio`,`rb`.`freightPackagingFull` AS `Lleno` from `vn`.`returnBuckets` `rb` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Entradas`
--
/*!50001 DROP VIEW IF EXISTS `Entradas`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Entradas` AS select `e`.`id` AS `Id_Entrada`,`e`.`supplierFk` AS `Id_Proveedor`,`e`.`invoiceNumber` AS `Referencia`,`e`.`reference` AS `reference`,`e`.`isExcludedFromAvailable` AS `Inventario`,`e`.`isConfirmed` AS `Confirmada`,`e`.`isOrdered` AS `Pedida`,`e`.`isRaid` AS `Redada`,`e`.`commission` AS `comision`,`e`.`created` AS `odbc_date`,`e`.`evaNotes` AS `Notas_Eva`,`e`.`travelFk` AS `travel_id`,`e`.`currencyFk` AS `Id_Moneda`,`e`.`companyFk` AS `empresa_id`,`e`.`gestDocFk` AS `gestdoc_id`,`e`.`invoiceInFk` AS `recibida_id`,`e`.`dated` AS `Fecha`,`e`.`isBooked` AS `Anotadoencaja`,`e`.`loadPriority` AS `loadPriority`,`e`.`sub` AS `sub`,`e`.`kop` AS `kop`,`e`.`pro` AS `pro`,`e`.`invoiceAmount` AS `invoiceAmount`,`e`.`buyerFk` AS `buyerFk`,`e`.`typeFk` AS `typeFk` from `vn`.`entry` `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 `Entradas_Auto`
--
/*!50001 DROP VIEW IF EXISTS `Entradas_Auto`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Entradas_Auto` AS select `ev`.`entryFk` AS `Id_Entrada` from `vn`.`entryVirtual` `ev` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Entradas_orden`
--
/*!50001 DROP VIEW IF EXISTS `Entradas_orden`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Entradas_orden` AS select `eo`.`entryFk` AS `Id_Entrada`,`eo`.`order` AS `orden` from `vn`.`entryOrder` `eo` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Impresoras`
--
/*!50001 DROP VIEW IF EXISTS `Impresoras`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Impresoras` AS select `vn`.`printer`.`id` AS `Id_impresora`,`vn`.`printer`.`path` AS `Ruta`,`vn`.`printer`.`name` AS `Impresora`,`vn`.`printer`.`reference` AS `referencia`,`vn`.`printer`.`isLabeler` AS `isLabeler` from `vn`.`printer` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Monedas`
--
/*!50001 DROP VIEW IF EXISTS `Monedas`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Monedas` AS select `c`.`id` AS `Id_Moneda`,`c`.`code` AS `Moneda`,`c`.`name` AS `Descripcion`,`c`.`ratio` AS `Cambio` from `vn`.`currency` `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 `Movimientos`
--
/*!50001 DROP VIEW IF EXISTS `Movimientos`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Movimientos` AS select `m`.`id` AS `Id_Movimiento`,`m`.`itemFk` AS `Id_Article`,`m`.`ticketFk` AS `Id_Ticket`,`m`.`concept` AS `Concepte`,`m`.`quantity` AS `Cantidad`,`m`.`price` AS `Preu`,`m`.`discount` AS `Descuento`,`m`.`reserved` AS `Reservado`,`m`.`isPicked` AS `OK`,`m`.`created` AS `odbc_date`,`m`.`priceFixed` AS `CostFixat`,`m`.`isPriceFixed` AS `PrecioFijado`,`m`.`originalQuantity` AS `quantity`,`m`.`isAdded` AS `isAdded` from `vn`.`sale` `m` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Movimientos_componentes`
--
/*!50001 DROP VIEW IF EXISTS `Movimientos_componentes`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Movimientos_componentes` AS select `sc`.`saleFk` AS `Id_Movimiento`,`sc`.`componentFk` AS `Id_Componente`,`sc`.`value` AS `Valor`,`sc`.`created` AS `created`,`sc`.`isGreuge` AS `greuge` from `vn`.`saleComponent` `sc` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Movimientos_mark`
--
/*!50001 DROP VIEW IF EXISTS `Movimientos_mark`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Movimientos_mark` AS select `mm`.`saleFk` AS `Id_Movimiento`,`mm`.`isChecked` AS `valor`,`mm`.`created` AS `odbc_date`,`mm`.`originalQuantity` AS `original_quantity`,`mm`.`workerFk` AS `Id_Trabajador`,`mm`.`id` AS `Id_Movimiento_mark`,`mm`.`stateFk` AS `stateFk` from `vn`.`saleTracking` `mm` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Ordenes`
--
/*!50001 DROP VIEW IF EXISTS `Ordenes`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Ordenes` AS select `tr`.`id` AS `Id_ORDEN`,`tr`.`description` AS `ORDEN`,`tr`.`requesterFk` AS `requesterFk`,`tr`.`attenderFk` AS `attenderFk`,`tr`.`quantity` AS `CANTIDAD`,`tr`.`itemFk` AS `Id_ARTICLE`,`tr`.`price` AS `PRECIOMAX`,`tr`.`isOk` AS `isOk`,`tr`.`saleFk` AS `Id_Movimiento`,`tr`.`ticketFk` AS `ticketFk`,`tr`.`response` AS `COMENTARIO`,`tr`.`created` AS `odbc_date`,`tr`.`ordered` AS `datORDEN`,`tr`.`shipped` AS `datTICKET`,`tr`.`salesPersonCode` AS `CodVENDEDOR`,`tr`.`clientFk` AS `Id_CLIENTE`,`tr`.`total` AS `TOTAL`,`tr`.`buyed` AS `datCOMPRA` from `vn`.`ticketRequest` `tr` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Origen`
--
/*!50001 DROP VIEW IF EXISTS `Origen`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Origen` AS select `o`.`id` AS `id`,`o`.`code` AS `Abreviatura`,`o`.`name` AS `Origen`,`o`.`countryFk` AS `Id_Paises`,`o`.`warehouseFk` AS `warehouse_id` from `vn`.`origin` `o` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Pagares`
--
/*!50001 DROP VIEW IF EXISTS `Pagares`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Pagares` AS select `p`.`id` AS `Id_Pagare`,`p`.`issued` AS `Fechaemision`,`p`.`Concept` AS `Concepto`,`p`.`paymentFk` AS `pago_id` from `vn`.`promissoryNote` `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 `Paises`
--
/*!50001 DROP VIEW IF EXISTS `Paises`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Paises` AS select `c`.`id` AS `Id`,`c`.`country` AS `Pais`,`c`.`CEE` AS `CEE`,`c`.`isUeeMember` AS `isUeeMember`,`c`.`code` AS `Codigo`,`c`.`currencyFk` AS `Id_Moneda`,`c`.`geoFk` AS `geoFk`,`c`.`ibanLength` AS `ibanLength`,`c`.`hasDailyInvoice` AS `hasDailyInvoice` from `vn`.`country` `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 `PreciosEspeciales`
--
/*!50001 DROP VIEW IF EXISTS `PreciosEspeciales`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `PreciosEspeciales` AS select `sp`.`id` AS `Id_PrecioEspecial`,`sp`.`clientFk` AS `Id_Cliente`,`sp`.`itemFk` AS `Id_Article`,`sp`.`value` AS `PrecioEspecial` from `vn`.`specialPrice` `sp` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Proveedores`
--
/*!50001 DROP VIEW IF EXISTS `Proveedores`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Proveedores` AS select `s`.`id` AS `Id_Proveedor`,`s`.`name` AS `Proveedor`,`s`.`account` AS `cuenta`,`s`.`countryFk` AS `pais_id`,`s`.`nif` AS `NIF`,`s`.`isFarmer` AS `Agricola`,`s`.`phone` AS `Telefono`,`s`.`retAccount` AS `cuentaret`,`s`.`commission` AS `ComisionProveedor`,`s`.`created` AS `odbc_time`,`s`.`postcodeFk` AS `postcode_id`,`s`.`isActive` AS `active`,`s`.`street` AS `Domicilio`,`s`.`city` AS `Localidad`,`s`.`provinceFk` AS `province_id`,`s`.`postCode` AS `codpos`,`s`.`payMethodFk` AS `pay_met_id`,`s`.`payDemFk` AS `pay_dem_id`,`s`.`nickname` AS `Alias`,`s`.`isOfficial` AS `oficial`,`s`.`workerFk` AS `workerFk`,`s`.`payDay` AS `pay_day`,`s`.`isReal` AS `serious`,`s`.`note` AS `notas`,`s`.`taxTypeSageFk` AS `taxTypeSageFk`,`s`.`withholdingSageFk` AS `withholdingSageFk`,`s`.`isTrucker` AS `isTrucker`,`s`.`transactionTypeSageFk` AS `transactionTypeSageFk`,`s`.`supplierActivityFk` AS `supplierActivityFk`,`s`.`healthRegister` AS `healthRegister`,`s`.`isPayMethodChecked` AS `isPayMethodChecked` from `vn`.`supplier` `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 `Proveedores_cargueras`
--
/*!50001 DROP VIEW IF EXISTS `Proveedores_cargueras`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Proveedores_cargueras` AS select `fs`.`supplierFk` AS `Id_Proveedor` from `vn`.`supplierFreight` `fs` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Proveedores_gestdoc`
--
/*!50001 DROP VIEW IF EXISTS `Proveedores_gestdoc`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Proveedores_gestdoc` AS select `sd`.`supplierFk` AS `Id_Proveedor`,`sd`.`dmsFk` AS `gestdoc_id` from `vn`.`supplierDms` `sd` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Recibos`
--
/*!50001 DROP VIEW IF EXISTS `Recibos`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Recibos` AS select `r`.`Id` AS `Id`,`r`.`invoiceFk` AS `Id_Factura`,`r`.`amountPaid` AS `Entregado`,`r`.`payed` AS `Fechacobro`,`r`.`workerFk` AS `Id_Trabajador`,`r`.`bankFk` AS `Id_Banco`,`r`.`clientFk` AS `Id_Cliente`,`r`.`created` AS `odbc_date`,`r`.`companyFk` AS `empresa_id`,`r`.`isConciliate` AS `conciliado` from `vn`.`receipt` `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 `Remesas`
--
/*!50001 DROP VIEW IF EXISTS `Remesas`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Remesas` AS select `r`.`id` AS `Id_Remesa`,`r`.`dated` AS `Fecha Remesa`,`r`.`accountingFk` AS `Banco`,`r`.`companyFk` AS `empresa_id` from `vn`.`remittance` `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 `Rutas`
--
/*!50001 DROP VIEW IF EXISTS `Rutas`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Rutas` AS select `r`.`id` AS `Id_Ruta`,`r`.`workerFk` AS `Id_Trabajador`,`r`.`created` AS `Fecha`,`r`.`vehicleFk` AS `Id_Vehiculo`,`r`.`agencyModeFk` AS `Id_Agencia`,`r`.`time` AS `Hora`,`r`.`isOk` AS `ok`,`r`.`kmStart` AS `km_start`,`r`.`kmEnd` AS `km_end`,`r`.`started` AS `date_start`,`r`.`finished` AS `date_end`,`r`.`gestdocFk` AS `gestdoc_id`,`r`.`cost` AS `cost`,`r`.`m3` AS `m3`,`r`.`description` AS `description` from `vn`.`route` `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 `Saldos_Prevision`
--
/*!50001 DROP VIEW IF EXISTS `Saldos_Prevision`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Saldos_Prevision` AS select `fb`.`id` AS `Saldos_Prevision_id`,`fb`.`description` AS `Descripcion`,`fb`.`amount` AS `Importe`,`fb`.`dated` AS `Fecha`,`fb`.`accountingFk` AS `Id_Banco`,`fb`.`companyFk` AS `empresa_id` from `vn`.`forecastedBalance` `fb` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Split_lines`
--
/*!50001 DROP VIEW IF EXISTS `Split_lines`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Split_lines` AS select `sl`.`id` AS `Id_Split_lines`,`sl`.`splitFk` AS `Id_Split`,`sl`.`itemFk` AS `Id_Article`,`sl`.`buyFk` AS `Id_Compra` from `vn`.`splitLine` `sl` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Splits`
--
/*!50001 DROP VIEW IF EXISTS `Splits`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Splits` AS select `s`.`id` AS `Id_Split`,`s`.`ticketFk` AS `Id_Ticket`,`s`.`entryFk` AS `Id_Entrada`,`s`.`dated` AS `Fecha`,`s`.`note` AS `Notas` from `vn`.`split` `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 `Tickets`
--
/*!50001 DROP VIEW IF EXISTS `Tickets`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Tickets` AS select `t`.`id` AS `Id_Ticket`,`t`.`clientFk` AS `Id_Cliente`,`t`.`warehouseFk` AS `warehouse_id`,`t`.`shipped` AS `Fecha`,`t`.`landed` AS `landing`,`t`.`nickname` AS `Alias`,`t`.`refFk` AS `Factura`,`t`.`addressFk` AS `Id_Consigna`,`t`.`location` AS `Localizacion`,`t`.`solution` AS `Solucion`,`t`.`routeFk` AS `Id_Ruta`,`t`.`companyFk` AS `empresa_id`,`t`.`agencyModeFk` AS `Id_Agencia`,`t`.`priority` AS `Prioridad`,`t`.`packages` AS `Bultos`,`t`.`isDeleted` AS `isDeleted`,`t`.`created` AS `odbc_date`,`t`.`workerFk` AS `Id_Trabajador`,`t`.`observations` AS `Observaciones`,`t`.`isSigned` AS `Firmado`,`t`.`isLabeled` AS `Etiquetasemitidas`,`t`.`isPrinted` AS `PedidoImpreso`,`t`.`hour` AS `Hora`,`t`.`isBlocked` AS `blocked`,`t`.`hasPriority` AS `priority`,`t`.`isBoxed` AS `boxed`,`t`.`zoneFk` AS `zoneFk`,`t`.`totalWithVat` AS `totalWithVat`,`t`.`totalWithoutVat` AS `totalWithoutVat` from `vn`.`ticket` `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 `Tickets_state`
--
/*!50001 DROP VIEW IF EXISTS `Tickets_state`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Tickets_state` AS select `t`.`ticketFk` AS `Id_Ticket`,`t`.`ticketTrackingFk` AS `inter_id`,`t`.`name` AS `state_name` from `vn`.`ticketLastState` `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 `Tickets_turno`
--
/*!50001 DROP VIEW IF EXISTS `Tickets_turno`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Tickets_turno` AS select `tw`.`ticketFk` AS `Id_Ticket`,`tw`.`weekDay` AS `weekDay` from `vn`.`ticketWeekly` `tw` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Tintas`
--
/*!50001 DROP VIEW IF EXISTS `Tintas`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Tintas` AS select `i`.`id` AS `Id_Tinta`,`i`.`name` AS `name`,`i`.`picture` AS `Tinta`,`i`.`showOrder` AS `Orden`,`i`.`ball` AS `ball`,`i`.`isCargex` AS `cargex`,`i`.`hex` AS `colorHex` from `vn`.`ink` `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 `Tipos`
--
/*!50001 DROP VIEW IF EXISTS `Tipos`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Tipos` AS select `it`.`id` AS `tipo_id`,`it`.`code` AS `Id_Tipo`,`it`.`name` AS `Tipo`,`it`.`order` AS `Orden`,`it`.`categoryFk` AS `reino_id`,`it`.`workerFk` AS `Id_Trabajador`,`it`.`life` AS `life`,`it`.`isPackaging` AS `isPackaging`,`it`.`density` AS `density`,`it`.`isInventory` AS `inventory`,`it`.`created` AS `odbc_date`,`it`.`making` AS `confeccion`,`it`.`temperatureFk` AS `Temperatura`,`it`.`promo` AS `promo`,`it`.`maneuver` AS `maneuver`,`it`.`target` AS `target`,`it`.`topMargin` AS `top_margin`,`it`.`profit` AS `profit` from `vn`.`itemType` `it` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Trabajadores`
--
/*!50001 DROP VIEW IF EXISTS `Trabajadores`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Trabajadores` AS select `w`.`id` AS `Id_Trabajador`,`w`.`firstName` AS `Nombre`,`w`.`id` AS `user_id`,`w`.`phone` AS `phone`,`w`.`bossFk` AS `boss`,NULL AS `Foto`,`w`.`fiDueDate` AS `DniExpiration`,`w`.`code` AS `CodigoTrabajador`,`w`.`lastName` AS `Apellidos`,`w`.`hasMachineryAuthorized` AS `hasMachineryAuthorized`,`w`.`sub` AS `sub`,`w`.`maritalStatus` AS `marital_status` from `vn`.`worker` `w` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Tramos`
--
/*!50001 DROP VIEW IF EXISTS `Tramos`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Tramos` AS select `s`.`id` AS `id`,`s`.`section` AS `Tramo` from `vn`.`timeSlots` `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 `V_edi_item_track`
--
/*!50001 DROP VIEW IF EXISTS `V_edi_item_track`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `V_edi_item_track` AS select `edi`.`item_track`.`item_id` AS `item_id`,`edi`.`item_track`.`s1` AS `s1`,`edi`.`item_track`.`s2` AS `s2`,`edi`.`item_track`.`s3` AS `s3`,`edi`.`item_track`.`s4` AS `s4`,`edi`.`item_track`.`s5` AS `s5`,`edi`.`item_track`.`s6` AS `s6`,`edi`.`item_track`.`kop` AS `kop`,`edi`.`item_track`.`pac` AS `pac`,`edi`.`item_track`.`cat` AS `cat`,`edi`.`item_track`.`ori` AS `ori`,`edi`.`item_track`.`pro` AS `pro`,`edi`.`item_track`.`sub` AS `sub`,`edi`.`item_track`.`package` AS `package`,`edi`.`item_track`.`item` AS `item` from `edi`.`item_track` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `Vehiculos_consumo`
--
/*!50001 DROP VIEW IF EXISTS `Vehiculos_consumo`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `Vehiculos_consumo` AS select `vc`.`id` AS `Vehiculos_consumo_id`,`vc`.`vehicleFk` AS `Id_Vehiculo`,`vc`.`dated` AS `fecha`,`vc`.`km` AS `km`,`vc`.`liters` AS `litros`,`vc`.`price` AS `precio`,`vc`.`adblue` AS `adblue`,`vc`.`tolls` AS `peajes`,`vc`.`discount` AS `descuento`,`vc`.`silla` AS `silla`,`vc`.`created` AS `odbc_date`,`vc`.`others` AS `otros`,`vc`.`fuelTypeFk` AS `fuelTypeFk`,`vc`.`supplierFk` AS `proveedoresFk`,`vc`.`liters100km` AS `liters100km`,`vc`.`gasoline` AS `gasoline` from `vn`.`vehicleConsumption` `vc` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `account_conciliacion`
--
/*!50001 DROP VIEW IF EXISTS `account_conciliacion`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `account_conciliacion` AS select `ar`.`id` AS `idaccount_conciliacion`,`ar`.`supplierAccountFk` AS `Id_Proveedores_account`,`ar`.`operationDated` AS `Fechaoperacion`,`ar`.`valueDated` AS `FechaValor`,`ar`.`amount` AS `importe`,`ar`.`concept` AS `Concepto`,`ar`.`debitCredit` AS `DebeHaber`,`ar`.`calculatedCode` AS `id_calculated`,`ar`.`created` AS `odbc_date` from `vn`.`accountReconciliation` `ar` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `account_detail`
--
/*!50001 DROP VIEW IF EXISTS `account_detail`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `account_detail` AS select `ac`.`id` AS `account_detail_id`,`ac`.`value` AS `value`,`ac`.`accountDetailTypeFk` AS `account_detail_type_id`,`ac`.`supplierAccountFk` AS `Id_Proveedores_account` from `vn`.`accountDetail` `ac` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `account_detail_type`
--
/*!50001 DROP VIEW IF EXISTS `account_detail_type`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `account_detail_type` AS select `adt`.`id` AS `account_detail_type_id`,`adt`.`description` AS `description` from `vn`.`accountDetailType` `adt` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `agency`
--
/*!50001 DROP VIEW IF EXISTS `agency`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `agency` AS select `a`.`id` AS `agency_id`,`a`.`name` AS `name`,`a`.`warehouseFk` AS `warehouse_id`,`a`.`isOwn` AS `propios`,`a`.`workCenterFk` AS `workCenterFk` from `vn`.`agency` `a` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `airline`
--
/*!50001 DROP VIEW IF EXISTS `airline`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `airline` AS select `a`.`id` AS `airline_id`,`a`.`name` AS `name` from `vn`.`airline` `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 `airport`
--
/*!50001 DROP VIEW IF EXISTS `airport`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `airport` AS select `a`.`id` AS `airport_id`,`a`.`name` AS `name` from `vn`.`airport` `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 `albaran`
--
/*!50001 DROP VIEW IF EXISTS `albaran`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `albaran` AS select `dn`.`id` AS `albaran_id`,`dn`.`ref` AS `ref`,`dn`.`note` AS `note`,`dn`.`shipped` AS `fecha`,`dn`.`landed` AS `fecha_entrega`,`dn`.`amount` AS `valor`,`dn`.`supplierFk` AS `Id_Proveedor`,`dn`.`companyFk` AS `empresa_id`,`dn`.`warehouseFk` AS `warehouse_id`,`dn`.`stateFk` AS `albaran_state_id`,`dn`.`workerFk` AS `Id_Trabajador`,`dn`.`supervisorFk` AS `Id_Responsable`,`dn`.`departmentFk` AS `department_id`,`dn`.`invoiceInFk` AS `recibida_id`,`dn`.`farmingFk` AS `farmingFk` from `vn`.`deliveryNote` `dn` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `albaran_gestdoc`
--
/*!50001 DROP VIEW IF EXISTS `albaran_gestdoc`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `albaran_gestdoc` AS select `dnd`.`dmsFk` AS `gestdoc_id`,`dnd`.`deliveryNoteFk` AS `albaran_id` from `vn`.`deliveryNoteDms` `dnd` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `albaran_state`
--
/*!50001 DROP VIEW IF EXISTS `albaran_state`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `albaran_state` AS select `dn`.`id` AS `albaran_state_id`,`dn`.`state` AS `state` from `vn`.`deliveryNoteState` `dn` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `awb`
--
/*!50001 DROP VIEW IF EXISTS `awb`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `awb` AS select `a`.`id` AS `id`,`a`.`code` AS `codigo`,`a`.`package` AS `bultos`,`a`.`weight` AS `peso`,`a`.`created` AS `MYSQL_TIME`,`a`.`transitoryFk` AS `transitario_id`,`a`.`taxFk` AS `iva_id`,`a`.`duakk` AS `duakk`,`a`.`docFk` AS `gestdoc_id`,`a`.`amount` AS `importe`,`a`.`freightFk` AS `carguera_id`,`a`.`m3` AS `m3`,`a`.`stems` AS `stems`,`a`.`flightFk` AS `flight_id`,`a`.`volumeWeight` AS `volume_weight`,`a`.`hb` AS `hb`,`a`.`rate` AS `rate`,`a`.`booked` AS `booked`,`a`.`issued` AS `issued`,`a`.`operated` AS `operated`,`a`.`bookEntried` AS `bookEntried`,`a`.`invoiceInFk` AS `invoiceInFk`,`a`.`isChecked` AS `isChecked`,`a`.`isTransitoryChecked` AS `isTransitoryChecked`,`a`.`year` AS `year`,`a`.`invoiceInPaletizedFk` AS `invoiceInPaletizedFk`,`a`.`observation` AS `observation`,`a`.`hasFreightPrepaid` AS `hasFreightPrepaid`,`a`.`propertyNumber` AS `propertyNumber` from `vn`.`awb` `a` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `awb_component`
--
/*!50001 DROP VIEW IF EXISTS `awb_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `awb_component` AS select `ac`.`id` AS `id`,`ac`.`awbFk` AS `awb_id`,`ac`.`supplierFk` AS `Id_Proveedor`,`ac`.`typeFk` AS `awb_component_type_id`,`ac`.`awbRoleFk` AS `awb_role_id`,`ac`.`awbUnitFk` AS `awb_unit_id`,`ac`.`value` AS `value`,`ac`.`currencyFk` AS `Id_Moneda`,`ac`.`invoiceInFk` AS `recibida_id` from `vn`.`awbComponent` `ac` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `awb_component_template`
--
/*!50001 DROP VIEW IF EXISTS `awb_component_template`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `awb_component_template` AS select `act`.`id` AS `awb_component_template_id`,`act`.`freightFk` AS `carguera_id`,`act`.`airportIn` AS `airport_in`,`act`.`airportOut` AS `airport_out`,`act`.`airlineFk` AS `airline_id`,`act`.`typeFk` AS `awb_component_type_id`,`act`.`dated` AS `Fecha`,`act`.`awbRoleFk` AS `awb_role_id`,`act`.`awbUnit` AS `awb_unit_id`,`act`.`value` AS `value`,`act`.`maxValue` AS `max_value`,`act`.`minValue` AS `min_value`,`act`.`currencyFk` AS `Id_Moneda`,`act`.`days` AS `days` from `vn`.`awbComponentTemplate` `act` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `awb_component_type`
--
/*!50001 DROP VIEW IF EXISTS `awb_component_type`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `awb_component_type` AS select `act`.`id` AS `awb_component_type_id`,`act`.`description` AS `description`,`act`.`hasStems` AS `hasStems` from `vn`.`awbComponentType` `act` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `awb_gestdoc`
--
/*!50001 DROP VIEW IF EXISTS `awb_gestdoc`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `awb_gestdoc` AS select `ad`.`id` AS `awb_gestdoc_id`,`ad`.`awbFk` AS `awb_id`,`ad`.`dmsFk` AS `gestdoc_id` from `vn`.`awbDms` `ad` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `awb_recibida`
--
/*!50001 DROP VIEW IF EXISTS `awb_recibida`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `awb_recibida` AS select `aii`.`awbFk` AS `awb_id`,`aii`.`invoiceInFk` AS `recibida_id`,`aii`.`sad` AS `dua` from `vn`.`awbInvoiceIn` `aii` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `awb_role`
--
/*!50001 DROP VIEW IF EXISTS `awb_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 = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `awb_role` AS select `ar`.`id` AS `awb_role_id`,`ar`.`name` AS `name` from `vn`.`awbRole` `ar` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `awb_unit`
--
/*!50001 DROP VIEW IF EXISTS `awb_unit`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `awb_unit` AS select `au`.`id` AS `awb_unit_id`,`au`.`operation` AS `operation` from `vn`.`awbUnit` `au` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `balance_nest_tree`
--
/*!50001 DROP VIEW IF EXISTS `balance_nest_tree`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `balance_nest_tree` AS select `bnt`.`lft` AS `lft`,`bnt`.`rgt` AS `rgt`,`bnt`.`name` AS `name`,`bnt`.`id` AS `id`,`bnt`.`expenseFk` AS `Id_Gasto`,`bnt`.`isSelected` AS `isSelected` from `vn`.`balanceNestTree` `bnt` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `barcodes`
--
/*!50001 DROP VIEW IF EXISTS `barcodes`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `barcodes` AS select `b`.`id` AS `id`,`b`.`itemFk` AS `Id_Article`,`b`.`code` AS `code` from `vn`.`itemBarcode` `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 `buySource`
--
/*!50001 DROP VIEW IF EXISTS `buySource`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `buySource` AS select `b`.`entryFk` AS `Id_Entrada`,`b`.`isPickedOff` AS `isPickedOff`,NULL AS `tarifa0`,`e`.`kop` AS `kop`,`b`.`id` AS `Id_Compra`,`i`.`typeFk` AS `tipo_id`,`b`.`itemFk` AS `Id_Article`,`i`.`size` AS `Medida`,`i`.`stems` AS `Tallos`,`b`.`stickers` AS `Etiquetas`,`b`.`packagingFk` AS `Id_Cubo`,`b`.`buyingValue` AS `Costefijo`,`b`.`packing` AS `Packing`,`b`.`grouping` AS `Grouping`,`b`.`quantity` AS `Cantidad`,`b`.`price2` AS `Tarifa2`,`b`.`price3` AS `Tarifa3`,`b`.`isChecked` AS `Punteo`,`b`.`groupingMode` AS `Caja`,`i`.`isToPrint` AS `Imprimir`,`i`.`name` AS `Article`,`vn`.`ink`.`picture` AS `Tinta`,`i`.`originFk` AS `id_origen`,`i`.`minPrice` AS `PVP`,NULL AS `Id_Accion`,`s`.`company_name` AS `pro`,`i`.`hasMinPrice` AS `Min`,`b`.`isIgnored` AS `Novincular`,`b`.`freightValue` AS `Portefijo`,round(`b`.`buyingValue` * `b`.`quantity`,2) AS `Importe`,`b`.`printedStickers` AS `Vida`,`i`.`comment` AS `reference`,`b`.`workerFk` AS `Id_Trabajador`,`e`.`s1` AS `S1`,`e`.`s2` AS `S2`,`e`.`s3` AS `S3`,`e`.`s4` AS `S4`,`e`.`s5` AS `S5`,`e`.`s6` AS `S6`,0 AS `price_fixed`,`i`.`producerFk` AS `producer_id`,`i`.`subName` AS `tag1`,`i`.`value5` AS `tag2`,`i`.`value6` AS `tag3`,`i`.`value7` AS `tag4`,`i`.`value8` AS `tag5`,`i`.`value9` AS `tag6`,`i`.`value10` AS `tag7`,`s`.`company_name` AS `company_name`,`b`.`weight` AS `weightPacking`,`i`.`packingOut` AS `packingOut`,`b`.`itemOriginalFk` AS `itemOriginalFk`,`io`.`longName` AS `itemOriginalName`,`it`.`gramsMax` AS `gramsMax`,`i`.`minQuantity` AS `minQuantity` from ((((((`vn`.`item` `i` join `vn`.`itemType` `it` on(`it`.`id` = `i`.`typeFk`)) left join `vn`.`ink` on(`vn`.`ink`.`id` = `i`.`inkFk`)) left join `vn`.`buy` `b` on(`b`.`itemFk` = `i`.`id`)) left join `vn`.`item` `io` on(`io`.`id` = `b`.`itemOriginalFk`)) left join `edi`.`ekt` `e` on(`e`.`id` = `b`.`ektFk`)) left join `edi`.`supplier` `s` on(`e`.`pro` = `s`.`supplier_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 `buy_edi`
--
/*!50001 DROP VIEW IF EXISTS `buy_edi`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `buy_edi` AS select `t`.`id` AS `id`,`t`.`barcode` AS `barcode`,`t`.`entryYear` AS `entry_year`,`t`.`deliveryNumber` AS `delivery_number`,`t`.`fec` AS `fec`,`t`.`hor` AS `hor`,`t`.`now` AS `now`,`t`.`ptj` AS `ptj`,`t`.`ref` AS `ref`,`t`.`item` AS `item`,`t`.`pac` AS `pac`,`t`.`qty` AS `qty`,`t`.`ori` AS `ori`,`t`.`cat` AS `cat`,`t`.`agj` AS `agj`,`t`.`kop` AS `kop`,`t`.`ptd` AS `ptd`,`t`.`sub` AS `sub`,`t`.`pro` AS `pro`,`t`.`pri` AS `pri`,`t`.`package` AS `package`,`t`.`auction` AS `auction`,`t`.`klo` AS `klo`,`t`.`k1` AS `k01`,`t`.`k2` AS `k02`,`t`.`k3` AS `k03`,`t`.`k4` AS `k04`,`t`.`s1` AS `s1`,`t`.`s2` AS `s2`,`t`.`s3` AS `s3`,`t`.`s4` AS `s4`,`t`.`s5` AS `s5`,`t`.`s6` AS `s6`,`t`.`ok` AS `ok`,`t`.`trolleyFk` AS `trolley_id`,`t`.`putOrderFk` AS `putOrderFk`,`t`.`scanned` AS `scanned` from `edi`.`ekt` `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 `buy_edi_k012`
--
/*!50001 DROP VIEW IF EXISTS `buy_edi_k012`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `buy_edi_k012` AS select `eek`.`id` AS `buy_edi_k012_id`,`eek`.`description` AS `description` from `edi`.`ektK1` `eek` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `buy_edi_k03`
--
/*!50001 DROP VIEW IF EXISTS `buy_edi_k03`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `buy_edi_k03` AS select `eek`.`id` AS `buy_edi_k03_id`,`eek`.`description` AS `description` from `edi`.`ektK3` `eek` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `buy_edi_k04`
--
/*!50001 DROP VIEW IF EXISTS `buy_edi_k04`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `buy_edi_k04` AS select `eek`.`id` AS `buy_edi_k04_id`,`eek`.`description` AS `description` from `edi`.`ektK4` `eek` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `cdr`
--
/*!50001 DROP VIEW IF EXISTS `cdr`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `cdr` AS select `c`.`call_date` AS `calldate`,`c`.`clid` AS `clid`,`c`.`src` AS `src`,`c`.`dst` AS `dst`,`c`.`dcontext` AS `dcontext`,`c`.`channel` AS `channel`,`c`.`dst_channel` AS `dstchannel`,`c`.`last_app` AS `lastapp`,`c`.`last_data` AS `lastdata`,`c`.`duration` AS `duration`,`c`.`billsec` AS `billsec`,`c`.`disposition` AS `disposition`,`c`.`ama_flags` AS `amaflags`,`c`.`account_code` AS `accountcode`,`c`.`unique_id` AS `uniqueid`,`c`.`user_field` AS `userfield` from `pbx`.`cdr` `c` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `chanel`
--
/*!50001 DROP VIEW IF EXISTS `chanel`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `chanel` AS select `c`.`id` AS `chanel_id`,`c`.`name` AS `name` from `vn`.`contactChannel` `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 `cl_act`
--
/*!50001 DROP VIEW IF EXISTS `cl_act`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `cl_act` AS select `c`.`id` AS `id`,`c`.`saleFk` AS `Id_Movimiento`,`c`.`claimFk` AS `cl_main_id`,`c`.`workerFk` AS `Id_Trabajador`,`c`.`claimDestinationFk` AS `cl_sol_id`,`c`.`isGreuge` AS `greuge` from `vn`.`claimEnd` `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 `cl_cau`
--
/*!50001 DROP VIEW IF EXISTS `cl_cau`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `cl_cau` AS select `c`.`id` AS `id`,`c`.`claimFk` AS `cl_main_id`,`c`.`claimResponsibleFk` AS `cl_res_id`,`c`.`workerFk` AS `Id_Trabajador`,`c`.`claimReasonFk` AS `cl_mot_id`,`c`.`claimResultFk` AS `cl_con_id`,`c`.`claimRedeliveryFk` AS `cl_dev`,`c`.`claimDestinationFk` AS `cl_sol` from `vn`.`claimDevelopment` `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 `cl_con`
--
/*!50001 DROP VIEW IF EXISTS `cl_con`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `cl_con` AS select `c`.`id` AS `id`,`c`.`description` AS `consecuencia` from `vn`.`claimResult` `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 `cl_det`
--
/*!50001 DROP VIEW IF EXISTS `cl_det`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `cl_det` AS select `c`.`id` AS `id`,`c`.`claimFk` AS `cl_main_id`,`c`.`saleFk` AS `Id_Movimiento`,`c`.`quantity` AS `numero` from `vn`.`claimBeginning` `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 `cl_main`
--
/*!50001 DROP VIEW IF EXISTS `cl_main`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `cl_main` AS select `c`.`id` AS `id`,`c`.`ticketCreated` AS `Fecha`,`c`.`claimStateFk` AS `cl_est_id`,`c`.`observation` AS `notas`,`c`.`clientFk` AS `Id_Cliente`,`c`.`workerFk` AS `Id_Trabajador`,`c`.`responsibility` AS `sensib`,`c`.`isChargedToMana` AS `mana`,`c`.`ticketFk` AS `ticketFk`,`c`.`created` AS `odbc_date` from `vn`.`claim` `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 `cl_mot`
--
/*!50001 DROP VIEW IF EXISTS `cl_mot`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `cl_mot` AS select `c`.`id` AS `id`,`c`.`description` AS `motivo` from `vn`.`claimReason` `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 `cl_res`
--
/*!50001 DROP VIEW IF EXISTS `cl_res`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `cl_res` AS select `c`.`id` AS `id`,`c`.`description` AS `responsable`,`c`.`responsability` AS `sensibility` from `vn`.`claimResponsible` `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 `cl_sol`
--
/*!50001 DROP VIEW IF EXISTS `cl_sol`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `cl_sol` AS select `c`.`id` AS `id`,`c`.`description` AS `solucion`,`c`.`addressFk` AS `addressFk` from `vn`.`claimDestination` `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 `config_host`
--
/*!50001 DROP VIEW IF EXISTS `config_host`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `config_host` AS select `vn`.`host`.`code` AS `config_host_id`,`vn`.`host`.`warehouseFk` AS `warehouse`,`vn`.`host`.`companyFk` AS `empresaId`,`vn`.`host`.`bankFk` AS `caja`,`vn`.`host`.`printerFk` AS `Id_Impresora`,`vn`.`host`.`routeDaysBefore` AS `route_days_before`,`vn`.`host`.`routeDaysAfter` AS `route_days_after` from `vn`.`host` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `consignatarios_observation`
--
/*!50001 DROP VIEW IF EXISTS `consignatarios_observation`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `consignatarios_observation` AS select `co`.`id` AS `consignatarios_observation_id`,`co`.`addressFk` AS `Id_Consigna`,`co`.`observationTypeFk` AS `observation_type_id`,`co`.`description` AS `text` from `vn`.`addressObservation` `co` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `credit`
--
/*!50001 DROP VIEW IF EXISTS `credit`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `credit` AS select `c`.`id` AS `id`,`c`.`clientFk` AS `Id_Cliente`,`c`.`workerFk` AS `Id_Trabajador`,`c`.`amount` AS `amount`,`c`.`created` AS `odbc_date` from `vn`.`clientCredit` `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 `definitivo`
--
/*!50001 DROP VIEW IF EXISTS `definitivo`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `definitivo` AS select `d`.`id` AS `definitivo_id`,`d`.`companyFk` AS `empresa_id`,`d`.`started` AS `desde`,`d`.`ended` AS `hasta`,`d`.`created` AS `fecha` from `vn`.`dmsStorageBox` `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 `edi_article`
--
/*!50001 DROP VIEW IF EXISTS `edi_article`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `edi_article` AS select `edi`.`item`.`id` AS `id`,`edi`.`item`.`product_name` AS `product_name`,`edi`.`item`.`name` AS `name`,`edi`.`item`.`plant_id` AS `plant_id`,`edi`.`item`.`group_id` AS `group_id`,`edi`.`item`.`entry_date` AS `entry_date`,`edi`.`item`.`expiry_date` AS `expiry_date`,`edi`.`item`.`change_date_time` AS `change_date_time` from `edi`.`item` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `edi_bucket`
--
/*!50001 DROP VIEW IF EXISTS `edi_bucket`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `edi_bucket` AS select cast(`edi`.`bucket`.`bucket_id` as char charset utf8mb3) collate utf8mb3_general_ci AS `bucket_id`,`edi`.`bucket`.`bucket_type_id` AS `bucket_type_id`,`edi`.`bucket`.`description` AS `description`,`edi`.`bucket`.`x_size` AS `x_size`,`edi`.`bucket`.`y_size` AS `y_size`,`edi`.`bucket`.`z_size` AS `z_size`,`edi`.`bucket`.`entry_date` AS `entry_date`,`edi`.`bucket`.`expiry_date` AS `expiry_date`,`edi`.`bucket`.`change_date_time` AS `change_date_time` from `edi`.`bucket` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `edi_bucket_type`
--
/*!50001 DROP VIEW IF EXISTS `edi_bucket_type`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `edi_bucket_type` AS select `edi`.`bucket_type`.`bucket_type_id` AS `bucket_type_id`,`edi`.`bucket_type`.`description` AS `description`,`edi`.`bucket_type`.`entry_date` AS `entry_date`,`edi`.`bucket_type`.`expiry_date` AS `expiry_date`,`edi`.`bucket_type`.`change_date_time` AS `change_date_time` from `edi`.`bucket_type` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `edi_specie`
--
/*!50001 DROP VIEW IF EXISTS `edi_specie`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `edi_specie` AS select `edi`.`specie`.`specie_id` AS `specie_id`,`edi`.`specie`.`genus_id` AS `genus_id`,`edi`.`specie`.`latin_species_name` AS `latin_species_name`,`edi`.`specie`.`entry_date` AS `entry_date`,`edi`.`specie`.`expiry_date` AS `expiry_date`,`edi`.`specie`.`change_date_time` AS `change_date_time` from `edi`.`specie` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `edi_supplier`
--
/*!50001 DROP VIEW IF EXISTS `edi_supplier`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `edi_supplier` AS select `edi`.`supplier`.`supplier_id` AS `supplier_id`,`edi`.`supplier`.`company_name` AS `company_name` from `edi`.`supplier` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `empresa`
--
/*!50001 DROP VIEW IF EXISTS `empresa`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `empresa` AS select `c`.`id` AS `id`,`c`.`code` AS `abbreviation`,`c`.`supplierAccountFk` AS `Id_Proveedores_account`,`c`.`workerManagerFk` AS `gerente_id`,`c`.`phytosanitary` AS `phytosanitary`,`c`.`companyCode` AS `CodigoEmpresa`,`c`.`companyGroupFk` AS `empresa_grupo`,`c`.`isDefaulter` AS `morosidad`,`c`.`expired` AS `baja`,`c`.`register` AS `registro`,`c`.`registered` AS `alta`,`c`.`logo` AS `logo`,`c`.`isOfficial` AS `oficial`,`c`.`hasCyc` AS `cyc`,`c`.`rgb` AS `rgb`,`c`.`email` AS `mail`,`c`.`stamp` AS `cuno`,`c`.`created` AS `ODBC_DATE`,`c`.`clientFk` AS `Id_Cliente` from `vn`.`company` `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 `empresa_grupo`
--
/*!50001 DROP VIEW IF EXISTS `empresa_grupo`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `empresa_grupo` AS select `vn`.`companyGroup`.`id` AS `empresa_grupo_id`,`vn`.`companyGroup`.`code` AS `grupo` from `vn`.`companyGroup` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `entrySource`
--
/*!50001 DROP VIEW IF EXISTS `entrySource`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `entrySource` AS select `e`.`gestDocFk` AS `gestdoc_id`,`e`.`id` AS `Id_Entrada`,`e`.`invoiceNumber` AS `invoiceNumber`,`e`.`reference` AS `reference`,`e`.`isExcludedFromAvailable` AS `Inventario`,`e`.`isConfirmed` AS `Confirmada`,`e`.`isOrdered` AS `Pedida`,`e`.`isRaid` AS `Redada`,`e`.`evaNotes` AS `notas`,`e`.`supplierFk` AS `Id_Proveedor`,`tr`.`shipped` AS `shipment`,`tr`.`landed` AS `landing`,`w2`.`name` AS `wh_in`,`w1`.`name` AS `wh_out`,`am`.`name` AS `Agencia`,`e`.`commission` AS `comision`,`tr`.`warehouseInFk` AS `warehouse_id`,`w1`.`id` AS `warehouse_id_out`,`e`.`isBooked` AS `anotadoencaja`,`e`.`invoiceInFk` AS `invoiceInFk`,`e`.`companyFk` AS `empresa_id`,`e`.`currencyFk` AS `Id_Moneda`,`tr`.`id` AS `TravelFk`,`e`.`sub` AS `sub`,`e`.`kop` AS `kop`,`e`.`pro` AS `pro`,`e`.`invoiceAmount` AS `invoiceAmount`,`w`.`code` AS `buyerCode`,`e`.`typeFk` AS `typeFk`,`w3`.`code` AS `observationWorkerCode` from (((((((`vn`.`entry` `e` left join `vn`.`travel` `tr` on(`e`.`travelFk` = `tr`.`id`)) left join `vn`.`agencyMode` `am` on(`am`.`id` = `tr`.`agencyModeFk`)) left join `vn`.`warehouse` `w1` on(`tr`.`warehouseOutFk` = `w1`.`id`)) left join `vn`.`warehouse` `w2` on(`tr`.`warehouseInFk` = `w2`.`id`)) left join `vn`.`supplier` `s` on(`e`.`supplierFk` = `s`.`id`)) left join `vn`.`worker` `w` on(`w`.`id` = `e`.`buyerFk`)) left join `vn`.`worker` `w3` on(`w3`.`id` = `e`.`observationEditorFk`)) */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `financialProductType`
--
/*!50001 DROP VIEW IF EXISTS `financialProductType`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `financialProductType` AS select `vn`.`financialProductType`.`id` AS `id`,`vn`.`financialProductType`.`description` AS `description`,`vn`.`financialProductType`.`isAcumulattor` AS `isAcumulattor` from `vn`.`financialProductType` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `flight`
--
/*!50001 DROP VIEW IF EXISTS `flight`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `flight` AS select `f`.`id` AS `flight_id`,`f`.`duration` AS `duration`,`f`.`flightPath` AS `route`,`f`.`days` AS `days`,`f`.`airlineFk` AS `airline_id`,`f`.`airportArrivalFk` AS `airport_out`,`f`.`airportDepartureFk` AS `airport_in` from `vn`.`flight` `f` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `gastos_resumen`
--
/*!50001 DROP VIEW IF EXISTS `gastos_resumen`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `gastos_resumen` AS select `es`.`id` AS `id`,`es`.`expenseFk` AS `Id_Gasto`,`es`.`year` AS `year`,`es`.`month` AS `month`,`es`.`amount` AS `importe`,`es`.`companyFk` AS `empresa_id` from `vn`.`expenseManual` `es` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `integra2`
--
/*!50001 DROP VIEW IF EXISTS `integra2`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `integra2` AS select `i2`.`postCode` AS `postal_code`,`i2`.`frequency` AS `frequency`,`i2`.`warehouseFk` AS `warehouse_id` from `vn`.`integra2` `i2` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `integra2_province`
--
/*!50001 DROP VIEW IF EXISTS `integra2_province`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `integra2_province` AS select `ip`.`provinceFk` AS `province_id`,`ip`.`franchise` AS `franquicia` from `vn`.`integra2Province` `ip` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `mail`
--
/*!50001 DROP VIEW IF EXISTS `mail`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `mail` AS select `m`.`id` AS `id`,`m`.`senderFk` AS `senderFk`,`m`.`recipientFk` AS `recipientFk`,`m`.`receiver` AS `to`,`m`.`replyTo` AS `reply_to`,`m`.`subject` AS `subject`,`m`.`body` AS `text`,`m`.`plainTextBody` AS `plainTextBody`,`m`.`attachment` AS `path`,`m`.`creationDate` AS `DATE_ODBC`,`m`.`sent` AS `sent`,`m`.`status` AS `error` from `vn`.`mail` `m` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `mandato`
--
/*!50001 DROP VIEW IF EXISTS `mandato`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `mandato` AS select `m`.`id` AS `id`,`m`.`clientFk` AS `Id_Cliente`,`m`.`companyFk` AS `empresa_id`,`m`.`code` AS `Id_mandato`,`m`.`created` AS `FAlta`,`m`.`finished` AS `Fbaja`,`m`.`mandateTypeFk` AS `idmandato_tipo` from `vn`.`mandate` `m` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `mandato_tipo`
--
/*!50001 DROP VIEW IF EXISTS `mandato_tipo`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `mandato_tipo` AS select `m`.`id` AS `idmandato_tipo`,`m`.`name` AS `Nombre` from `vn`.`mandateType` `m` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `pago`
--
/*!50001 DROP VIEW IF EXISTS `pago`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `pago` AS select `p`.`id` AS `id`,`p`.`received` AS `fecha`,`p`.`dueDated` AS `dueDated`,`p`.`supplierFk` AS `id_proveedor`,`p`.`amount` AS `importe`,`p`.`currencyFk` AS `id_moneda`,`p`.`divisa` AS `divisa`,`p`.`bankFk` AS `id_banco`,`p`.`payMethodFk` AS `pay_met_id`,`p`.`companyFk` AS `empresa_id`,`p`.`isConciliated` AS `conciliado`,`p`.`bankingFees` AS `g_bancarios`,`p`.`concept` AS `concepte`,`p`.`created` AS `odbc_date` from `vn`.`payment` `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 `pago_sdc`
--
/*!50001 DROP VIEW IF EXISTS `pago_sdc`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `pago_sdc` AS select `ei`.`id` AS `pago_sdc_id`,`ei`.`amount` AS `importe`,`ei`.`dated` AS `fecha`,`ei`.`dueDated` AS `vencimiento`,`ei`.`entityFk` AS `entity_id`,`ei`.`ref` AS `ref`,`ei`.`rate` AS `rate`,`ei`.`companyFk` AS `empresa_id`,`ei`.`financialProductTypefk` AS `financialProductTypefk`,`ei`.`upperBarrier` AS `upperBarrier`,`ei`.`lowerBarrier` AS `lowerBarrier`,`ei`.`strike` AS `strike` from `vn`.`exchangeInsurance` `ei` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `pay_dem`
--
/*!50001 DROP VIEW IF EXISTS `pay_dem`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `pay_dem` AS select `pd`.`id` AS `id`,`pd`.`payDem` AS `pay_dem` from `vn`.`payDem` `pd` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `pay_dem_det`
--
/*!50001 DROP VIEW IF EXISTS `pay_dem_det`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `pay_dem_det` AS select `pdd`.`id` AS `id`,`pdd`.`detail` AS `detalle` from `vn`.`payDemDetail` `pdd` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `pay_met`
--
/*!50001 DROP VIEW IF EXISTS `pay_met`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `pay_met` AS select `pm`.`id` AS `id`,`pm`.`name` AS `name`,`pm`.`graceDays` AS `graceDays`,`pm`.`outstandingDebt` AS `deudaviva`,`pm`.`solution` AS `solucion`,`pm`.`isNotified` AS `isNotified` from `vn`.`payMethod` `pm` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `payroll_categorias`
--
/*!50001 DROP VIEW IF EXISTS `payroll_categorias`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `payroll_categorias` AS select `pc`.`id` AS `codcategoria`,`pc`.`rate` AS `Tarifa`,`pc`.`description` AS `descripcion` from `vn`.`payrollCategories` `pc` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `payroll_centros`
--
/*!50001 DROP VIEW IF EXISTS `payroll_centros`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `payroll_centros` AS select `pwc`.`workCenterFkA3` AS `cod_centro`,`pwc`.`companyFkA3` AS `codempresa` from `vn`.`payrollWorkCenter` `pwc` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `payroll_conceptos`
--
/*!50001 DROP VIEW IF EXISTS `payroll_conceptos`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `payroll_conceptos` AS select `pc`.`id` AS `conceptoid`,`pc`.`name` AS `concepto`,`pc`.`isSalaryAgreed` AS `isSalaryAgreed`,`pc`.`isVariable` AS `isVariable`,`pc`.`isException` AS `isException` from `vn`.`payrollComponent` `pc` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `payroll_employee`
--
/*!50001 DROP VIEW IF EXISTS `payroll_employee`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `payroll_employee` AS select `pw`.`workerFkA3` AS `CodTrabajador`,`pw`.`companyFkA3` AS `codempresa`,`pw`.`workerFk` AS `workerFk` from `vn`.`payrollWorker` `pw` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `plantpassport`
--
/*!50001 DROP VIEW IF EXISTS `plantpassport`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `plantpassport` AS select `pp`.`producerFk` AS `producer_id`,`pp`.`plantpassportAuthorityFk` AS `plantpassport_authority_id`,`pp`.`number` AS `number`,`pp`.`isRequested` AS `isRequested` from `vn`.`plantpassport` `pp` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `plantpassport_authority`
--
/*!50001 DROP VIEW IF EXISTS `plantpassport_authority`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `plantpassport_authority` AS select `ppa`.`id` AS `plantpassport_authority_id`,`ppa`.`denomination` AS `denomination`,`ppa`.`countryFk` AS `Paises_Id` from `vn`.`plantpassportAuthority` `ppa` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `price_fixed`
--
/*!50001 DROP VIEW IF EXISTS `price_fixed`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `price_fixed` AS select `pf`.`itemFk` AS `item_id`,`pf`.`rate0` AS `rate_0`,`pf`.`rate1` AS `rate_1`,`pf`.`rate2` AS `rate_2`,`pf`.`rate3` AS `rate_3`,`pf`.`started` AS `date_start`,`pf`.`ended` AS `date_end`,`pf`.`bonus` AS `bonus`,`pf`.`warehouseFk` AS `warehouse_id`,`pf`.`created` AS `odbc_date`,`pf`.`id` AS `price_fixed_id`,`pf`.`grouping` AS `grouping`,`pf`.`packing` AS `Packing`,`pf`.`box` AS `caja` from `vn`.`priceFixed` `pf` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `producer`
--
/*!50001 DROP VIEW IF EXISTS `producer`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `producer` AS select `p`.`id` AS `producer_id`,`p`.`name` AS `name`,`p`.`isVisible` AS `visible` from `vn`.`producer` `p` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `proveedores_clientes`
--
/*!50001 DROP VIEW IF EXISTS `proveedores_clientes`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `proveedores_clientes` AS select `Proveedores`.`Id_Proveedor` AS `Id_Proveedor`,`Proveedores`.`Proveedor` AS `Proveedor`,`Clientes`.`id_cliente` AS `Id_Cliente`,`Clientes`.`cliente` AS `Cliente` from (`vn2008`.`Proveedores` join `vn2008`.`Clientes` on(`Proveedores`.`NIF` = `Clientes`.`if`)) */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `province`
--
/*!50001 DROP VIEW IF EXISTS `province`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `province` AS select `p`.`id` AS `province_id`,`p`.`name` AS `name`,`p`.`countryFk` AS `Paises_Id`,`p`.`warehouseFk` AS `warehouse_id`,`p`.`zoneFk` AS `zone`,`p`.`geoFk` AS `geoFk` from `vn`.`province` `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 `recibida`
--
/*!50001 DROP VIEW IF EXISTS `recibida`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `recibida` AS select `r`.`id` AS `id`,`r`.`serialNumber` AS `num_recibida`,`r`.`serial` AS `serie`,`r`.`supplierFk` AS `proveedor_id`,`r`.`issued` AS `fecha`,`r`.`supplierRef` AS `sref`,`r`.`isBooked` AS `contabilizada`,`r`.`currencyFk` AS `moneda_id`,`r`.`created` AS `MYSQL_TIME`,`r`.`companyFk` AS `empresa_id`,`r`.`docFk` AS `gestdoc_id`,`r`.`booked` AS `dateBooking`,`r`.`operated` AS `dateOperation`,`r`.`siiTypeInvoiceInFk` AS `siiTypeInvoiceInFk`,`r`.`cplusRectificationTypeFk` AS `cplusRectificationTypeFk`,`r`.`cplusSubjectOpFk` AS `cplusSubjectOpFk`,`r`.`cplusTaxBreakFk` AS `cplusTaxBreakFk`,`r`.`siiTrascendencyInvoiceInFk` AS `siiTrascendencyInvoiceInFk`,`r`.`bookEntried` AS `bookEntried`,`r`.`isVatDeductible` AS `isVatDeductible`,`r`.`withholdingSageFk` AS `withholdingSageFk`,`r`.`expenseFkDeductible` AS `expenseFkDeductible` from `vn`.`invoiceIn` `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 `recibida_intrastat`
--
/*!50001 DROP VIEW IF EXISTS `recibida_intrastat`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `recibida_intrastat` AS select `i`.`invoiceInFk` AS `recibida_id`,`i`.`intrastatFk` AS `Codintrastat`,`i`.`amount` AS `importe` from `vn`.`invoiceInIntrastat` `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 `recibida_iva`
--
/*!50001 DROP VIEW IF EXISTS `recibida_iva`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `recibida_iva` AS select `i`.`id` AS `id`,`i`.`invoiceInFk` AS `recibida_id`,`i`.`taxCodeFk` AS `iva_id`,`i`.`taxableBase` AS `bi`,`i`.`expenseFk` AS `gastos_id`,`i`.`foreignValue` AS `divisa`,`i`.`taxTypeSageFk` AS `taxTypeSageFk`,`i`.`transactionTypeSageFk` AS `transactionTypeSageFk`,`i`.`created` AS `MYSQL_TIME` from `vn`.`invoiceInTax` `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 `recibida_vencimiento`
--
/*!50001 DROP VIEW IF EXISTS `recibida_vencimiento`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `recibida_vencimiento` AS select `r`.`id` AS `id`,`r`.`invoiceInFk` AS `recibida_id`,`r`.`dueDated` AS `fecha`,`r`.`bankFk` AS `banco_id`,`r`.`amount` AS `cantidad`,`r`.`foreignValue` AS `divisa`,`r`.`created` AS `stamp` from `vn`.`invoiceInDueDay` `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 `recovery`
--
/*!50001 DROP VIEW IF EXISTS `recovery`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `recovery` AS select `r`.`id` AS `recovery_id`,`r`.`clientFk` AS `Id_Cliente`,`r`.`started` AS `dstart`,`r`.`finished` AS `dend`,`r`.`amount` AS `amount`,`r`.`period` AS `period` from `vn`.`recovery` `r` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `reference_rate`
--
/*!50001 DROP VIEW IF EXISTS `reference_rate`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `reference_rate` AS select `rr`.`currencyFk` AS `moneda_id`,`rr`.`dated` AS `date`,`rr`.`value` AS `rate` from `vn`.`referenceRate` `rr` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `reinos`
--
/*!50001 DROP VIEW IF EXISTS `reinos`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `reinos` AS select `r`.`id` AS `id`,`r`.`name` AS `reino`,`r`.`display` AS `display`,`r`.`color` AS `color`,`r`.`icon` AS `icon`,`r`.`merchandise` AS `mercancia`,`r`.`order` AS `orden`,`r`.`shortLife` AS `efimero` from `vn`.`itemCategory` `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 `state`
--
/*!50001 DROP VIEW IF EXISTS `state`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `state` AS select `s`.`id` AS `id`,`s`.`name` AS `name`,`s`.`order` AS `order`,`s`.`alertLevel` AS `alert_level`,`s`.`code` AS `code`,`s`.`sectorProdPriority` AS `sectorProdPriority`,`s`.`nextStateFk` AS `nextStateFk`,`s`.`isPreviousPreparable` AS `isPreviousPreparable`,`s`.`isPicked` AS `isPicked` from `vn`.`state` `s` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `tag`
--
/*!50001 DROP VIEW IF EXISTS `tag`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `tag` AS select `t`.`id` AS `id`,`t`.`name` AS `name`,`t`.`isFree` AS `isFree`,`t`.`isQuantitatif` AS `isQuantitatif`,`t`.`sourceTable` AS `sourceTable`,`t`.`unit` AS `unit` from `vn`.`tag` `t` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `tarifa_componentes`
--
/*!50001 DROP VIEW IF EXISTS `tarifa_componentes`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `tarifa_componentes` AS select `tarifa_componentes`.`Id_Componente` AS `Id_Componente`,`tarifa_componentes`.`Componente` AS `Componente`,`tarifa_componentes`.`tarifa_componentes_series_id` AS `tarifa_componentes_series_id`,`tarifa_componentes`.`tarifa_class` AS `tarifa_class`,`tarifa_componentes`.`tax` AS `tax`,`tarifa_componentes`.`is_renewable` AS `is_renewable` from `bi`.`tarifa_componentes` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `tarifa_componentes_series`
--
/*!50001 DROP VIEW IF EXISTS `tarifa_componentes_series`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `tarifa_componentes_series` AS select `tarifa_componentes_series`.`tarifa_componentes_series_id` AS `tarifa_componentes_series_id`,`tarifa_componentes_series`.`Serie` AS `Serie`,`tarifa_componentes_series`.`base` AS `base` from `bi`.`tarifa_componentes_series` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `tblContadores`
--
/*!50001 DROP VIEW IF EXISTS `tblContadores`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `tblContadores` AS select `c`.`id` AS `id`,`c`.`ochoa` AS `ochoa`,`c`.`invoiceOutFk` AS `nfactura`,`c`.`inventoried` AS `FechaInventario`,`c`.`itemLog` AS `HistoricoArticulo`,`c`.`weekGoal` AS `week_goal`,`c`.`photosPath` AS `Rutafotos`,`c`.`cashBoxNumber` AS `numCaja`,`c`.`redCode` AS `CodigoRojo`,`c`.`TabletTime` AS `Tablet_Hora`,`c`.`t0` AS `t0`,`c`.`t1` AS `t1`,`c`.`t2` AS `t2`,`c`.`t3` AS `t3`,`c`.`cc` AS `cc`,`c`.`palet` AS `palet`,`c`.`campaign` AS `campaign`,`c`.`campaignLife` AS `campaign_life`,`c`.`truckDays` AS `truck_days`,`c`.`transportCharges` AS `tasa_transporte`,`c`.`escanerPath` AS `escaner_path`,`c`.`printedTurn` AS `turnoimpreso`,`c`.`truckLength` AS `truck_length`,`c`.`fuelConsumption` AS `fuel_consumption`,`c`.`petrol` AS `petrol`,`c`.`maintenance` AS `maintenance`,`c`.`hourPrice` AS `hour_price`,`c`.`meterPrice` AS `meter_price`,`c`.`kmPrice` AS `km_price`,`c`.`routeOption` AS `route_option`,`c`.`dbproduccion` AS `dbproduccion`,`c`.`mdbServer` AS `mdbServer`,`c`.`fakeEmail` AS `fakeEmail`,`c`.`defaultersMaxAmount` AS `defaultersMaxAmount`,`c`.`ASIEN` AS `ASIEN` from `vn`.`config` `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 `thermograph`
--
/*!50001 DROP VIEW IF EXISTS `thermograph`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `thermograph` AS select `t`.`id` AS `thermograph_id`,`t`.`model` AS `model` from `vn`.`thermograph` `t` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `ticket_observation`
--
/*!50001 DROP VIEW IF EXISTS `ticket_observation`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `ticket_observation` AS select `to`.`id` AS `ticket_observation_id`,`to`.`ticketFk` AS `Id_Ticket`,`to`.`observationTypeFk` AS `observation_type_id`,`to`.`description` AS `text` from `vn`.`ticketObservation` `to` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `tickets_gestdoc`
--
/*!50001 DROP VIEW IF EXISTS `tickets_gestdoc`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `tickets_gestdoc` AS select `td`.`ticketFk` AS `Id_Ticket`,`td`.`dmsFk` AS `gestdoc_id` from `vn`.`ticketDms` `td` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `time`
--
/*!50001 DROP VIEW IF EXISTS `time`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `time` AS select `t`.`dated` AS `date`,`t`.`period` AS `period`,`t`.`month` AS `month`,`t`.`year` AS `year`,`t`.`day` AS `day`,`t`.`week` AS `week`,`t`.`yearMonth` AS `yearMonth` from `vn`.`time` `t` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `travel`
--
/*!50001 DROP VIEW IF EXISTS `travel`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `travel` AS select `t`.`id` AS `id`,`t`.`shipped` AS `shipment`,`t`.`shipmentHour` AS `shipment_hour`,`t`.`landed` AS `landing`,`t`.`landingHour` AS `landing_hour`,`t`.`warehouseInFk` AS `warehouse_id`,`t`.`warehouseOutFk` AS `warehouse_id_out`,`t`.`agencyModeFk` AS `agency_id`,`t`.`ref` AS `ref`,`t`.`isDelivered` AS `delivered`,`t`.`isReceived` AS `received`,`t`.`m3` AS `m3`,`t`.`kg` AS `kg`,`t`.`cargoSupplierFk` AS `cargoSupplierFk`,`t`.`totalEntries` AS `totalEntries`,`t`.`appointment` AS `appointment`,`t`.`awbFk` AS `awbFk` from `vn`.`travel` `t` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `v_Articles_botanical`
--
/*!50001 DROP VIEW IF EXISTS `v_Articles_botanical`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `v_Articles_botanical` AS select `ib`.`itemFk` AS `itemFk`,concat(`g`.`name`,' ',ifnull(`s`.`name`,'')) AS `ediBotanic` from (((`vn`.`itemBotanical` `ib` left join `vn`.`genus` `g` on(`g`.`id` = `ib`.`genusFk`)) left join `vn`.`specie` `s` on(`s`.`id` = `ib`.`specieFk`)) left join `vn`.`ediSpecie` `es` on(`es`.`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 `v_compres`
--
/*!50001 DROP VIEW IF EXISTS `v_compres`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `v_compres` AS select `TP`.`Id_Tipo` AS `Familia`,`RN`.`id` AS `reino_id`,`C`.`Id_Compra` AS `Id_Compra`,`C`.`Id_Entrada` AS `Id_Entrada`,`C`.`Id_Article` AS `Id_Article`,`C`.`Cantidad` AS `Cantidad`,`C`.`Costefijo` AS `Costefijo`,`C`.`Portefijo` AS `Portefijo`,`C`.`Novincular` AS `Novincular`,`C`.`Etiquetas` AS `Etiquetas`,`C`.`Packing` AS `Packing`,`C`.`grouping` AS `grouping`,`C`.`Comisionfija` AS `Comisionfija`,`C`.`Embalajefijo` AS `Embalajefijo`,`C`.`Id_Cubo` AS `Id_Cubo`,`C`.`Tarifa1` AS `Tarifa1`,`C`.`Tarifa2` AS `Tarifa2`,`C`.`Tarifa3` AS `Tarifa3`,`C`.`PVP` AS `PVP`,`C`.`Vida` AS `Vida`,`C`.`Id_Trabajador` AS `Id_Trabajador`,`C`.`punteo` AS `punteo`,`C`.`odbc_date` AS `odbc_date`,`E`.`Inventario` AS `Inventario`,`E`.`Id_Proveedor` AS `Id_Proveedor`,`E`.`Fecha` AS `Fecha`,`E`.`Confirmada` AS `Confirmada`,`E`.`Redada` AS `Redada`,`E`.`empresa_id` AS `empresa_id`,`E`.`travel_id` AS `travel_id`,`E`.`Pedida` AS `Pedida`,`E`.`recibida_id` AS `recibida_id`,`TR`.`id` AS `id`,`TR`.`shipment` AS `shipment`,`TR`.`landing` AS `landing`,`TR`.`warehouse_id` AS `warehouse_id`,`TR`.`warehouse_id_out` AS `warehouse_id_out`,`TR`.`agency_id` AS `agency_id`,`TR`.`ref` AS `ref`,`TR`.`delivered` AS `delivered`,`TR`.`received` AS `received`,`A`.`Article` AS `Article`,`A`.`Medida` AS `Medida`,`A`.`Tallos` AS `Tallos`,`C`.`caja` AS `caja`,`A`.`Categoria` AS `Categoria`,`A`.`id_origen` AS `id_origen`,`TP`.`Id_Tipo` AS `Tipo`,`A`.`tipo_id` AS `tipo_id`,`A`.`Color` AS `Color`,`A`.`Min` AS `Min`,`C`.`Costefijo` + `C`.`Embalajefijo` + `C`.`Comisionfija` + `C`.`Portefijo` AS `Coste`,`W_OUT`.`isFeedStock` AS `fuente`,if(`cb`.`Volumen` > 0,`cb`.`Volumen`,`cb`.`X` * `cb`.`Y` * if(`cb`.`Z` = 0,`A`.`Medida` + 10,`cb`.`Z`)) * `C`.`Etiquetas` AS `cm3`,`A`.`producer_id` AS `producer_id` from ((((((((`vn2008`.`Compres` `C` join `vn2008`.`Entradas` `E` on(`C`.`Id_Entrada` = `E`.`Id_Entrada`)) join `vn2008`.`travel` `TR` on(`TR`.`id` = `E`.`travel_id`)) join `vn`.`warehouse` `W_IN` on(`W_IN`.`id` = `TR`.`warehouse_id`)) join `vn`.`warehouse` `W_OUT` on(`W_OUT`.`id` = `TR`.`warehouse_id_out`)) join `vn2008`.`Articles` `A` on(`C`.`Id_Article` = `A`.`Id_Article`)) join `vn2008`.`Tipos` `TP` on(`A`.`tipo_id` = `TP`.`tipo_id`)) join `vn2008`.`reinos` `RN` on(`RN`.`id` = `TP`.`reino_id`)) join `vn2008`.`Cubos` `cb` on(`cb`.`Id_Cubo` = `C`.`Id_Cubo`)) where `W_IN`.`isFeedStock` = 0 and `E`.`Inventario` = 0 and `E`.`Redada` = 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 `v_empresa`
--
/*!50001 DROP VIEW IF EXISTS `v_empresa`*/;
/*!50001 SET @saved_cs_client = @@character_set_client */;
/*!50001 SET @saved_cs_results = @@character_set_results */;
/*!50001 SET @saved_col_connection = @@collation_connection */;
/*!50001 SET character_set_client = utf8mb4 */;
/*!50001 SET character_set_results = utf8mb4 */;
/*!50001 SET collation_connection = utf8mb4_unicode_ci */;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `v_empresa` AS select `e`.`logo` AS `logo`,`e`.`id` AS `id`,`e`.`registro` AS `registro`,`e`.`gerente_id` AS `gerente_id`,`e`.`alta` AS `alta`,`t`.`Nombre` AS `Nombre`,`t`.`Apellidos` AS `Apellidos`,`p`.`Proveedor` AS `Proveedor`,`p`.`Domicilio` AS `Domicilio`,`p`.`codpos` AS `CP`,`p`.`Localidad` AS `Localidad`,`p`.`NIF` AS `NIF`,`p`.`Telefono` AS `Telefono`,`p`.`Alias` AS `Alias`,`e`.`abbreviation` AS `abbreviation` from ((`vn2008`.`empresa` `e` join `vn2008`.`Trabajadores` `t` on(`t`.`Id_Trabajador` = `e`.`gerente_id`)) join `vn2008`.`Proveedores` `p` on(`p`.`Id_Proveedor` = `e`.`id`)) */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `versiones`
--
/*!50001 DROP VIEW IF EXISTS `versiones`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `versiones` AS select `m`.`app` AS `programa`,`m`.`version` AS `version`,0 AS `critical` from `vn`.`mdbVersion` `m` where `m`.`branchFk` = 'master' */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
--
-- Final view structure for view `warehouse_pickup`
--
/*!50001 DROP VIEW IF EXISTS `warehouse_pickup`*/;
/*!50001 SET @saved_cs_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`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `warehouse_pickup` AS select `wp`.`warehouseFk` AS `warehouse_id`,`wp`.`agencyModeFk` AS `agency_id` from `vn`.`warehousePickup` `wp` */;
/*!50001 SET character_set_client = @saved_cs_client */;
/*!50001 SET character_set_results = @saved_cs_results */;
/*!50001 SET collation_connection = @saved_col_connection */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2024-05-14 6:26:25